blob: 35f30b3727d8a6174f429c36a13bf13bc020ce4a [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,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000806 StringRef Name, const AttrVec *Attrs = nullptr,
807 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000808 DeclContext *DC = SemaRef.CurContext;
809 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
810 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
811 VarDecl *Decl =
812 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
813 if (Attrs) {
814 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
815 I != E; ++I)
816 Decl->addAttr(*I);
817 }
818 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000819 if (OrigRef) {
820 Decl->addAttr(
821 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
822 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000823 return Decl;
824}
825
826static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
827 SourceLocation Loc,
828 bool RefersToCapture = false) {
829 D->setReferenced();
830 D->markUsed(S.Context);
831 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
832 SourceLocation(), D, RefersToCapture, Loc, Ty,
833 VK_LValue);
834}
835
836void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
837 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000838 D = getCanonicalDecl(D);
839 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000840 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000841 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000842 "Additional reduction info may be specified only for reduction items.");
843 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
844 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000845 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000846 "Additional reduction info may be specified only once for reduction "
847 "items.");
848 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000849 Expr *&TaskgroupReductionRef =
850 Stack.back().first.back().TaskgroupReductionRef;
851 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000852 auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000853 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000854 TaskgroupReductionRef =
855 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000856 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000857}
858
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000859void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
860 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000861 D = getCanonicalDecl(D);
862 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000863 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000864 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000865 "Additional reduction info may be specified only for reduction items.");
866 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
867 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000868 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000869 "Additional reduction info may be specified only once for reduction "
870 "items.");
871 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000872 Expr *&TaskgroupReductionRef =
873 Stack.back().first.back().TaskgroupReductionRef;
874 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000875 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
876 ".task_red.");
877 TaskgroupReductionRef =
878 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000879 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000880}
881
Alexey Bataevf189cb72017-07-24 14:52:13 +0000882DSAStackTy::DSAVarData
883DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000884 BinaryOperatorKind &BOK,
885 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000887 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
888 if (Stack.back().first.empty())
889 return DSAVarData();
890 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000891 E = Stack.back().first.rend();
892 I != E; std::advance(I, 1)) {
893 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000894 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000895 continue;
896 auto &ReductionData = I->ReductionMap[D];
897 if (!ReductionData.ReductionOp ||
898 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000899 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000900 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000901 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000902 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
903 "expression for the descriptor is not "
904 "set.");
905 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000906 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
907 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000908 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000909 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000910}
911
Alexey Bataevf189cb72017-07-24 14:52:13 +0000912DSAStackTy::DSAVarData
913DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000914 const Expr *&ReductionRef,
915 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000916 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000917 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
918 if (Stack.back().first.empty())
919 return DSAVarData();
920 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000921 E = Stack.back().first.rend();
922 I != E; std::advance(I, 1)) {
923 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000924 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000925 continue;
926 auto &ReductionData = I->ReductionMap[D];
927 if (!ReductionData.ReductionOp ||
928 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000929 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000930 SR = ReductionData.ReductionRange;
931 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000932 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
933 "expression for the descriptor is not "
934 "set.");
935 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000936 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
937 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000938 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000939 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000940}
941
Alexey Bataeved09d242014-05-28 05:53:51 +0000942bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000943 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +0000944 if (!isStackEmpty()) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000945 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000946 Scope *TopScope = nullptr;
Alexey Bataev852525d2018-03-02 17:17:12 +0000947 while (I != E && !isParallelOrTaskRegion(I->Directive) &&
948 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000949 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000950 if (I == E)
951 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000952 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000953 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000954 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000955 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000956 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000957 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000958 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000959}
960
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000961DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
962 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000963 DSAVarData DVar;
964
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000965 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000966 auto TI = Threadprivates.find(D);
967 if (TI != Threadprivates.end()) {
968 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000969 DVar.CKind = OMPC_threadprivate;
970 return DVar;
Alexey Bataev817d7f32017-11-14 21:01:01 +0000971 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
972 DVar.RefExpr = buildDeclRefExpr(
973 SemaRef, VD, D->getType().getNonReferenceType(),
974 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
975 DVar.CKind = OMPC_threadprivate;
976 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +0000977 return DVar;
978 }
979 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
980 // in a Construct, C/C++, predetermined, p.1]
981 // Variables appearing in threadprivate directives are threadprivate.
982 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
983 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
984 SemaRef.getLangOpts().OpenMPUseTLS &&
985 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
986 (VD && VD->getStorageClass() == SC_Register &&
987 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
988 DVar.RefExpr = buildDeclRefExpr(
989 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
990 DVar.CKind = OMPC_threadprivate;
991 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
992 return DVar;
993 }
994 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
995 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
996 !isLoopControlVariable(D).first) {
997 auto IterTarget =
998 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
999 [](const SharingMapTy &Data) {
1000 return isOpenMPTargetExecutionDirective(Data.Directive);
1001 });
1002 if (IterTarget != Stack.back().first.rend()) {
1003 auto ParentIterTarget = std::next(IterTarget, 1);
1004 auto Iter = Stack.back().first.rbegin();
1005 while (Iter != ParentIterTarget) {
1006 if (isOpenMPLocal(VD, Iter)) {
1007 DVar.RefExpr =
1008 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1009 D->getLocation());
1010 DVar.CKind = OMPC_threadprivate;
1011 return DVar;
1012 }
1013 std::advance(Iter, 1);
1014 }
1015 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1016 auto DSAIter = IterTarget->SharingMap.find(D);
1017 if (DSAIter != IterTarget->SharingMap.end() &&
1018 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1019 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1020 DVar.CKind = OMPC_threadprivate;
1021 return DVar;
1022 } else if (!SemaRef.IsOpenMPCapturedByRef(
1023 D, std::distance(ParentIterTarget,
1024 Stack.back().first.rend()))) {
1025 DVar.RefExpr =
1026 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1027 IterTarget->ConstructLoc);
1028 DVar.CKind = OMPC_threadprivate;
1029 return DVar;
1030 }
1031 }
1032 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001033 }
1034
Alexey Bataev4b465392017-04-26 15:06:24 +00001035 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001036 // Not in OpenMP execution region and top scope was already checked.
1037 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001038
Alexey Bataev758e55e2013-09-06 18:03:48 +00001039 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001040 // in a Construct, C/C++, predetermined, p.4]
1041 // Static data members are shared.
1042 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1043 // in a Construct, C/C++, predetermined, p.7]
1044 // Variables with static storage duration that are declared in a scope
1045 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001046 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001047 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001048 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001049 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001050 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001051
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001052 DVar.CKind = OMPC_shared;
1053 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 }
1055
1056 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00001057 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1058 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001059 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1060 // in a Construct, C/C++, predetermined, p.6]
1061 // Variables with const qualified type having no mutable member are
1062 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001063 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001064 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001065 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1066 if (auto *CTD = CTSD->getSpecializedTemplate())
1067 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001068 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001069 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1070 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001071 // Variables with const-qualified type having no mutable member may be
1072 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001073 DSAVarData DVarTemp = hasDSA(
1074 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1075 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001076 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
Alexey Bataev9a757382018-02-16 19:16:54 +00001077 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001078
Alexey Bataev758e55e2013-09-06 18:03:48 +00001079 DVar.CKind = OMPC_shared;
1080 return DVar;
1081 }
1082
Alexey Bataev758e55e2013-09-06 18:03:48 +00001083 // Explicitly specified attributes and local variables with predetermined
1084 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001085 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001086 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001087 if (FromParent && I != EndI)
1088 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001089 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001090 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001091 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001092 DVar.CKind = I->SharingMap[D].Attributes;
1093 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001094 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001095 }
1096
1097 return DVar;
1098}
1099
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001100DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1101 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 if (isStackEmpty()) {
1103 StackTy::reverse_iterator I;
1104 return getDSA(I, D);
1105 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001106 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001107 auto StartI = Stack.back().first.rbegin();
1108 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001109 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001110 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001111 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001112}
1113
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001114DSAStackTy::DSAVarData
1115DSAStackTy::hasDSA(ValueDecl *D,
1116 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1117 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1118 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001119 if (isStackEmpty())
1120 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001121 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001122 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001123 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001124 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001125 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001126 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001127 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001128 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001129 auto NewI = I;
1130 DSAVarData DVar = getDSA(NewI, D);
1131 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001132 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001133 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001134 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001135}
1136
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001137DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1138 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1139 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1140 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001141 if (isStackEmpty())
1142 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001143 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001144 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001145 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001146 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001147 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001148 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001149 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001150 auto NewI = StartI;
1151 DSAVarData DVar = getDSA(NewI, D);
1152 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001153}
1154
Alexey Bataevaac108a2015-06-23 04:51:00 +00001155bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001156 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001157 unsigned Level, bool NotLastprivate) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001158 if (isStackEmpty())
1159 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001160 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001161 auto StartI = Stack.back().first.begin();
1162 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001163 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001164 return false;
1165 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001166 return (StartI->SharingMap.count(D) > 0) &&
1167 StartI->SharingMap[D].RefExpr.getPointer() &&
1168 CPred(StartI->SharingMap[D].Attributes) &&
1169 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001170}
1171
Samuel Antao4be30e92015-10-02 17:14:03 +00001172bool DSAStackTy::hasExplicitDirective(
1173 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1174 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001175 if (isStackEmpty())
1176 return false;
1177 auto StartI = Stack.back().first.begin();
1178 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001179 if (std::distance(StartI, EndI) <= (int)Level)
1180 return false;
1181 std::advance(StartI, Level);
1182 return DPred(StartI->Directive);
1183}
1184
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001185bool DSAStackTy::hasDirective(
1186 const llvm::function_ref<bool(OpenMPDirectiveKind,
1187 const DeclarationNameInfo &, SourceLocation)>
1188 &DPred,
1189 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001190 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001191 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001192 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001193 auto StartI = std::next(Stack.back().first.rbegin());
1194 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001195 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001196 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001197 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1198 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1199 return true;
1200 }
1201 return false;
1202}
1203
Alexey Bataev758e55e2013-09-06 18:03:48 +00001204void Sema::InitDataSharingAttributesStack() {
1205 VarDataSharingAttributesStack = new DSAStackTy(*this);
1206}
1207
1208#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1209
Alexey Bataev4b465392017-04-26 15:06:24 +00001210void Sema::pushOpenMPFunctionRegion() {
1211 DSAStack->pushFunction();
1212}
1213
1214void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1215 DSAStack->popFunction(OldFSI);
1216}
1217
Alexey Bataev92327c52018-03-26 16:40:55 +00001218static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
1219isDeclareTargetDeclaration(const ValueDecl *VD) {
1220 for (const auto *D : VD->redecls()) {
1221 if (!D->hasAttrs())
1222 continue;
1223 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
1224 return Attr->getMapType();
1225 }
1226 return llvm::None;
1227}
1228
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001229bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001230 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1231
1232 auto &Ctx = getASTContext();
1233 bool IsByRef = true;
1234
1235 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001236 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001237 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001238
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001239 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001240 // This table summarizes how a given variable should be passed to the device
1241 // given its type and the clauses where it appears. This table is based on
1242 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1243 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1244 //
1245 // =========================================================================
1246 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1247 // | |(tofrom:scalar)| | pvt | | | |
1248 // =========================================================================
1249 // | scl | | | | - | | bycopy|
1250 // | scl | | - | x | - | - | bycopy|
1251 // | scl | | x | - | - | - | null |
1252 // | scl | x | | | - | | byref |
1253 // | scl | x | - | x | - | - | bycopy|
1254 // | scl | x | x | - | - | - | null |
1255 // | scl | | - | - | - | x | byref |
1256 // | scl | x | - | - | - | x | byref |
1257 //
1258 // | agg | n.a. | | | - | | byref |
1259 // | agg | n.a. | - | x | - | - | byref |
1260 // | agg | n.a. | x | - | - | - | null |
1261 // | agg | n.a. | - | - | - | x | byref |
1262 // | agg | n.a. | - | - | - | x[] | byref |
1263 //
1264 // | ptr | n.a. | | | - | | bycopy|
1265 // | ptr | n.a. | - | x | - | - | bycopy|
1266 // | ptr | n.a. | x | - | - | - | null |
1267 // | ptr | n.a. | - | - | - | x | byref |
1268 // | ptr | n.a. | - | - | - | x[] | bycopy|
1269 // | ptr | n.a. | - | - | x | | bycopy|
1270 // | ptr | n.a. | - | - | x | x | bycopy|
1271 // | ptr | n.a. | - | - | x | x[] | bycopy|
1272 // =========================================================================
1273 // Legend:
1274 // scl - scalar
1275 // ptr - pointer
1276 // agg - aggregate
1277 // x - applies
1278 // - - invalid in this combination
1279 // [] - mapped with an array section
1280 // byref - should be mapped by reference
1281 // byval - should be mapped by value
1282 // null - initialize a local variable to null on the device
1283 //
1284 // Observations:
1285 // - All scalar declarations that show up in a map clause have to be passed
1286 // by reference, because they may have been mapped in the enclosing data
1287 // environment.
1288 // - If the scalar value does not fit the size of uintptr, it has to be
1289 // passed by reference, regardless the result in the table above.
1290 // - For pointers mapped by value that have either an implicit map or an
1291 // array section, the runtime library may pass the NULL value to the
1292 // device instead of the value passed to it by the compiler.
1293
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001294 if (Ty->isReferenceType())
1295 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001296
1297 // Locate map clauses and see if the variable being captured is referred to
1298 // in any of those clauses. Here we only care about variables, not fields,
1299 // because fields are part of aggregates.
1300 bool IsVariableUsedInMapClause = false;
1301 bool IsVariableAssociatedWithSection = false;
1302
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001303 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1304 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001305 MapExprComponents,
1306 OpenMPClauseKind WhereFoundClauseKind) {
1307 // Only the map clause information influences how a variable is
1308 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001309 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001310 if (WhereFoundClauseKind != OMPC_map)
1311 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001312
1313 auto EI = MapExprComponents.rbegin();
1314 auto EE = MapExprComponents.rend();
1315
1316 assert(EI != EE && "Invalid map expression!");
1317
1318 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1319 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1320
1321 ++EI;
1322 if (EI == EE)
1323 return false;
1324
1325 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1326 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1327 isa<MemberExpr>(EI->getAssociatedExpression())) {
1328 IsVariableAssociatedWithSection = true;
1329 // There is nothing more we need to know about this variable.
1330 return true;
1331 }
1332
1333 // Keep looking for more map info.
1334 return false;
1335 });
1336
1337 if (IsVariableUsedInMapClause) {
1338 // If variable is identified in a map clause it is always captured by
1339 // reference except if it is a pointer that is dereferenced somehow.
1340 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1341 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001342 // By default, all the data that has a scalar type is mapped by copy
1343 // (except for reduction variables).
1344 IsByRef =
1345 !Ty->isScalarType() ||
1346 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1347 DSAStack->hasExplicitDSA(
1348 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001349 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001350 }
1351
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001352 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001353 IsByRef =
1354 !DSAStack->hasExplicitDSA(
1355 D,
1356 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1357 Level, /*NotLastprivate=*/true) &&
1358 // If the variable is artificial and must be captured by value - try to
1359 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001360 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1361 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001362 }
1363
Samuel Antao86ace552016-04-27 22:40:57 +00001364 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001365 // and alignment, because the runtime library only deals with uintptr types.
1366 // If it does not fit the uintptr size, we need to pass the data by reference
1367 // instead.
1368 if (!IsByRef &&
1369 (Ctx.getTypeSizeInChars(Ty) >
1370 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001371 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001372 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001373 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001374
1375 return IsByRef;
1376}
1377
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001378unsigned Sema::getOpenMPNestingLevel() const {
1379 assert(getLangOpts().OpenMP);
1380 return DSAStack->getNestingLevel();
1381}
1382
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001383bool Sema::isInOpenMPTargetExecutionDirective() const {
1384 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1385 !DSAStack->isClauseParsingMode()) ||
1386 DSAStack->hasDirective(
1387 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1388 SourceLocation) -> bool {
1389 return isOpenMPTargetExecutionDirective(K);
1390 },
1391 false);
1392}
1393
Alexey Bataev90c228f2016-02-08 09:29:13 +00001394VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001395 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001396 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001397
1398 // If we are attempting to capture a global variable in a directive with
1399 // 'target' we return true so that this global is also mapped to the device.
1400 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001401 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001402 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) {
1403 // If the declaration is enclosed in a 'declare target' directive,
1404 // then it should not be captured.
1405 //
Alexey Bataev92327c52018-03-26 16:40:55 +00001406 if (isDeclareTargetDeclaration(VD))
1407 return nullptr;
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001408 return VD;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001409 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001410
Alexey Bataev48977c32015-08-04 08:10:48 +00001411 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1412 (!DSAStack->isClauseParsingMode() ||
1413 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001414 auto &&Info = DSAStack->isLoopControlVariable(D);
1415 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001416 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001417 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001418 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001419 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001420 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001421 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001422 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001423 DVarPrivate = DSAStack->hasDSA(
1424 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1425 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001426 if (DVarPrivate.CKind != OMPC_unknown)
1427 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001428 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001429 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001430}
1431
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001432void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1433 unsigned Level) const {
1434 SmallVector<OpenMPDirectiveKind, 4> Regions;
1435 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1436 FunctionScopesIndex -= Regions.size();
1437}
1438
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001439bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001440 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1441 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001442 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1443 Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001444 (DSAStack->isClauseParsingMode() &&
1445 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001446 // Consider taskgroup reduction descriptor variable a private to avoid
1447 // possible capture in the region.
1448 (DSAStack->hasExplicitDirective(
1449 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1450 Level) &&
1451 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001452}
1453
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001454void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1455 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1456 D = getCanonicalDecl(D);
1457 OpenMPClauseKind OMPC = OMPC_unknown;
1458 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1459 const unsigned NewLevel = I - 1;
1460 if (DSAStack->hasExplicitDSA(D,
1461 [&OMPC](const OpenMPClauseKind K) {
1462 if (isOpenMPPrivate(K)) {
1463 OMPC = K;
1464 return true;
1465 }
1466 return false;
1467 },
1468 NewLevel))
1469 break;
1470 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1471 D, NewLevel,
1472 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1473 OpenMPClauseKind) { return true; })) {
1474 OMPC = OMPC_map;
1475 break;
1476 }
1477 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1478 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001479 OMPC = OMPC_map;
1480 if (D->getType()->isScalarType() &&
1481 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1482 DefaultMapAttributes::DMA_tofrom_scalar)
1483 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001484 break;
1485 }
1486 }
1487 if (OMPC != OMPC_unknown)
1488 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1489}
1490
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001491bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001492 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1493 // Return true if the current level is no longer enclosed in a target region.
1494
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001495 auto *VD = dyn_cast<VarDecl>(D);
1496 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001497 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1498 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001499}
1500
Alexey Bataeved09d242014-05-28 05:53:51 +00001501void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001502
1503void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1504 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001505 Scope *CurScope, SourceLocation Loc) {
1506 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001507 PushExpressionEvaluationContext(
1508 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001509}
1510
Alexey Bataevaac108a2015-06-23 04:51:00 +00001511void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1512 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001513}
1514
Alexey Bataevaac108a2015-06-23 04:51:00 +00001515void Sema::EndOpenMPClause() {
1516 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001517}
1518
Alexey Bataev758e55e2013-09-06 18:03:48 +00001519void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001520 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1521 // A variable of class type (or array thereof) that appears in a lastprivate
1522 // clause requires an accessible, unambiguous default constructor for the
1523 // class type, unless the list item is also specified in a firstprivate
1524 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001525 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001526 for (auto *C : D->clauses()) {
1527 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1528 SmallVector<Expr *, 8> PrivateCopies;
1529 for (auto *DE : Clause->varlists()) {
1530 if (DE->isValueDependent() || DE->isTypeDependent()) {
1531 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001532 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001533 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001534 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001535 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1536 QualType Type = VD->getType().getNonReferenceType();
1537 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001538 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001539 // Generate helper private variable and initialize it with the
1540 // default value. The address of the original variable is replaced
1541 // by the address of the new private variable in CodeGen. This new
1542 // variable is not added to IdResolver, so the code in the OpenMP
1543 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001544 auto *VDPrivate = buildVarDecl(
1545 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001546 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001547 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001548 if (VDPrivate->isInvalidDecl())
1549 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001550 PrivateCopies.push_back(buildDeclRefExpr(
1551 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001552 } else {
1553 // The variable is also a firstprivate, so initialization sequence
1554 // for private copy is generated already.
1555 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001556 }
1557 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001558 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001559 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001560 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001561 }
1562 }
1563 }
1564
Alexey Bataev758e55e2013-09-06 18:03:48 +00001565 DSAStack->pop();
1566 DiscardCleanupsInEvaluationContext();
1567 PopExpressionEvaluationContext();
1568}
1569
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001570static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1571 Expr *NumIterations, Sema &SemaRef,
1572 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001573
Alexey Bataeva769e072013-03-22 06:34:35 +00001574namespace {
1575
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001576class VarDeclFilterCCC : public CorrectionCandidateCallback {
1577private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001578 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001579
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001580public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001581 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001582 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001583 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001584 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001585 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1587 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001588 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001589 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001590 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001591};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001592
1593class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1594private:
1595 Sema &SemaRef;
1596
1597public:
1598 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1599 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1600 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001601 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001602 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1603 SemaRef.getCurScope());
1604 }
1605 return false;
1606 }
1607};
1608
Alexey Bataeved09d242014-05-28 05:53:51 +00001609} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001610
1611ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1612 CXXScopeSpec &ScopeSpec,
1613 const DeclarationNameInfo &Id) {
1614 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1615 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1616
1617 if (Lookup.isAmbiguous())
1618 return ExprError();
1619
1620 VarDecl *VD;
1621 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001622 if (TypoCorrection Corrected = CorrectTypo(
1623 Id, LookupOrdinaryName, CurScope, nullptr,
1624 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001625 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001626 PDiag(Lookup.empty()
1627 ? diag::err_undeclared_var_use_suggest
1628 : diag::err_omp_expected_var_arg_suggest)
1629 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001630 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001631 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001632 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1633 : diag::err_omp_expected_var_arg)
1634 << Id.getName();
1635 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001636 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001637 } else {
1638 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001639 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001640 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1641 return ExprError();
1642 }
1643 }
1644 Lookup.suppressDiagnostics();
1645
1646 // OpenMP [2.9.2, Syntax, C/C++]
1647 // Variables must be file-scope, namespace-scope, or static block-scope.
1648 if (!VD->hasGlobalStorage()) {
1649 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001650 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1651 bool IsDecl =
1652 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001653 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001654 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1655 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001656 return ExprError();
1657 }
1658
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001659 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001660 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001661 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1662 // A threadprivate directive for file-scope variables must appear outside
1663 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001664 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1665 !getCurLexicalContext()->isTranslationUnit()) {
1666 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001667 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1668 bool IsDecl =
1669 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1670 Diag(VD->getLocation(),
1671 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1672 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001673 return ExprError();
1674 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001675 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1676 // A threadprivate directive for static class member variables must appear
1677 // in the class definition, in the same scope in which the member
1678 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001679 if (CanonicalVD->isStaticDataMember() &&
1680 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1681 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001682 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1683 bool IsDecl =
1684 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1685 Diag(VD->getLocation(),
1686 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1687 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001688 return ExprError();
1689 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001690 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1691 // A threadprivate directive for namespace-scope variables must appear
1692 // outside any definition or declaration other than the namespace
1693 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001694 if (CanonicalVD->getDeclContext()->isNamespace() &&
1695 (!getCurLexicalContext()->isFileContext() ||
1696 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1697 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001698 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1699 bool IsDecl =
1700 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1701 Diag(VD->getLocation(),
1702 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1703 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001704 return ExprError();
1705 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001706 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1707 // A threadprivate directive for static block-scope variables must appear
1708 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001709 if (CanonicalVD->isStaticLocal() && CurScope &&
1710 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001711 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001712 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1713 bool IsDecl =
1714 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1715 Diag(VD->getLocation(),
1716 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1717 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001718 return ExprError();
1719 }
1720
1721 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1722 // A threadprivate directive must lexically precede all references to any
1723 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001724 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001725 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001726 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001727 return ExprError();
1728 }
1729
1730 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001731 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1732 SourceLocation(), VD,
1733 /*RefersToEnclosingVariableOrCapture=*/false,
1734 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001735}
1736
Alexey Bataeved09d242014-05-28 05:53:51 +00001737Sema::DeclGroupPtrTy
1738Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1739 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001740 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001741 CurContext->addDecl(D);
1742 return DeclGroupPtrTy::make(DeclGroupRef(D));
1743 }
David Blaikie0403cb12016-01-15 23:43:25 +00001744 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001745}
1746
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001747namespace {
1748class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1749 Sema &SemaRef;
1750
1751public:
1752 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001753 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001754 if (VD->hasLocalStorage()) {
1755 SemaRef.Diag(E->getLocStart(),
1756 diag::err_omp_local_var_in_threadprivate_init)
1757 << E->getSourceRange();
1758 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1759 << VD << VD->getSourceRange();
1760 return true;
1761 }
1762 }
1763 return false;
1764 }
1765 bool VisitStmt(const Stmt *S) {
1766 for (auto Child : S->children()) {
1767 if (Child && Visit(Child))
1768 return true;
1769 }
1770 return false;
1771 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001772 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001773};
1774} // namespace
1775
Alexey Bataeved09d242014-05-28 05:53:51 +00001776OMPThreadPrivateDecl *
1777Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001778 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001779 for (auto &RefExpr : VarList) {
1780 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001781 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1782 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001783
Alexey Bataev376b4a42016-02-09 09:41:09 +00001784 // Mark variable as used.
1785 VD->setReferenced();
1786 VD->markUsed(Context);
1787
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001788 QualType QType = VD->getType();
1789 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1790 // It will be analyzed later.
1791 Vars.push_back(DE);
1792 continue;
1793 }
1794
Alexey Bataeva769e072013-03-22 06:34:35 +00001795 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1796 // A threadprivate variable must not have an incomplete type.
1797 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001798 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001799 continue;
1800 }
1801
1802 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1803 // A threadprivate variable must not have a reference type.
1804 if (VD->getType()->isReferenceType()) {
1805 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001806 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1807 bool IsDecl =
1808 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1809 Diag(VD->getLocation(),
1810 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1811 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001812 continue;
1813 }
1814
Samuel Antaof8b50122015-07-13 22:54:53 +00001815 // Check if this is a TLS variable. If TLS is not being supported, produce
1816 // the corresponding diagnostic.
1817 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1818 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1819 getLangOpts().OpenMPUseTLS &&
1820 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001821 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1822 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001823 Diag(ILoc, diag::err_omp_var_thread_local)
1824 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001825 bool IsDecl =
1826 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1827 Diag(VD->getLocation(),
1828 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1829 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001830 continue;
1831 }
1832
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001833 // Check if initial value of threadprivate variable reference variable with
1834 // local storage (it is not supported by runtime).
1835 if (auto Init = VD->getAnyInitializer()) {
1836 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001837 if (Checker.Visit(Init))
1838 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001839 }
1840
Alexey Bataeved09d242014-05-28 05:53:51 +00001841 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001842 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001843 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1844 Context, SourceRange(Loc, Loc)));
1845 if (auto *ML = Context.getASTMutationListener())
1846 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001847 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001848 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001849 if (!Vars.empty()) {
1850 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1851 Vars);
1852 D->setAccess(AS_public);
1853 }
1854 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001855}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001856
Alexey Bataev7ff55242014-06-19 09:13:45 +00001857static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001858 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001859 bool IsLoopIterVar = false) {
1860 if (DVar.RefExpr) {
1861 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1862 << getOpenMPClauseName(DVar.CKind);
1863 return;
1864 }
1865 enum {
1866 PDSA_StaticMemberShared,
1867 PDSA_StaticLocalVarShared,
1868 PDSA_LoopIterVarPrivate,
1869 PDSA_LoopIterVarLinear,
1870 PDSA_LoopIterVarLastprivate,
1871 PDSA_ConstVarShared,
1872 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001873 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001874 PDSA_LocalVarPrivate,
1875 PDSA_Implicit
1876 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001877 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001878 auto ReportLoc = D->getLocation();
1879 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001880 if (IsLoopIterVar) {
1881 if (DVar.CKind == OMPC_private)
1882 Reason = PDSA_LoopIterVarPrivate;
1883 else if (DVar.CKind == OMPC_lastprivate)
1884 Reason = PDSA_LoopIterVarLastprivate;
1885 else
1886 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001887 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1888 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001889 Reason = PDSA_TaskVarFirstprivate;
1890 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001891 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001892 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001893 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001894 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001895 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001896 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001897 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001898 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001899 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001900 ReportHint = true;
1901 Reason = PDSA_LocalVarPrivate;
1902 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001903 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001904 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001905 << Reason << ReportHint
1906 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1907 } else if (DVar.ImplicitDSALoc.isValid()) {
1908 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1909 << getOpenMPClauseName(DVar.CKind);
1910 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001911}
1912
Alexey Bataev758e55e2013-09-06 18:03:48 +00001913namespace {
1914class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1915 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001916 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001917 bool ErrorFound;
1918 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001919 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001920 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001921 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001922 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001923
Alexey Bataev758e55e2013-09-06 18:03:48 +00001924public:
1925 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001926 if (E->isTypeDependent() || E->isValueDependent() ||
1927 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1928 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001929 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001930 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001931 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001932 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001933 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001934
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001935 auto DVar = Stack->getTopDSA(VD, false);
1936 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001937 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001938 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001939
Alexey Bataevafe50572017-10-06 17:00:28 +00001940 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00001941 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
1942 isDeclareTargetDeclaration(VD);
1943 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
1944 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00001945 return;
1946
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001947 auto ELoc = E->getExprLoc();
1948 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001949 // The default(none) clause requires that each variable that is referenced
1950 // in the construct, and does not have a predetermined data-sharing
1951 // attribute, must have its data-sharing attribute explicitly determined
1952 // by being listed in a data-sharing attribute clause.
1953 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001954 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001955 VarsWithInheritedDSA.count(VD) == 0) {
1956 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001957 return;
1958 }
1959
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001960 if (isOpenMPTargetExecutionDirective(DKind) &&
1961 !Stack->isLoopControlVariable(VD).first) {
1962 if (!Stack->checkMappableExprComponentListsForDecl(
1963 VD, /*CurrentRegionOnly=*/true,
1964 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1965 StackComponents,
1966 OpenMPClauseKind) {
1967 // Variable is used if it has been marked as an array, array
1968 // section or the variable iself.
1969 return StackComponents.size() == 1 ||
1970 std::all_of(
1971 std::next(StackComponents.rbegin()),
1972 StackComponents.rend(),
1973 [](const OMPClauseMappableExprCommon::
1974 MappableComponent &MC) {
1975 return MC.getAssociatedDeclaration() ==
1976 nullptr &&
1977 (isa<OMPArraySectionExpr>(
1978 MC.getAssociatedExpression()) ||
1979 isa<ArraySubscriptExpr>(
1980 MC.getAssociatedExpression()));
1981 });
1982 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001983 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001984 // By default lambdas are captured as firstprivates.
1985 if (const auto *RD =
1986 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001987 IsFirstprivate = RD->isLambda();
1988 IsFirstprivate =
1989 IsFirstprivate ||
1990 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00001991 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001992 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001993 ImplicitFirstprivate.emplace_back(E);
1994 else
1995 ImplicitMap.emplace_back(E);
1996 return;
1997 }
1998 }
1999
Alexey Bataev758e55e2013-09-06 18:03:48 +00002000 // OpenMP [2.9.3.6, Restrictions, p.2]
2001 // A list item that appears in a reduction clause of the innermost
2002 // enclosing worksharing or parallel construct may not be accessed in an
2003 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002004 DVar = Stack->hasInnermostDSA(
2005 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
2006 [](OpenMPDirectiveKind K) -> bool {
2007 return isOpenMPParallelDirective(K) ||
2008 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2009 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002010 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002011 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002012 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002013 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2014 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002015 return;
2016 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002017
2018 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002019 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002020 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2021 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002022 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002023 }
2024 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002025 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002026 if (E->isTypeDependent() || E->isValueDependent() ||
2027 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2028 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002029 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002030 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002031 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002032 if (!FD)
2033 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002034 auto DVar = Stack->getTopDSA(FD, false);
2035 // Check if the variable has explicit DSA set and stop analysis if it
2036 // so.
2037 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2038 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002039
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002040 if (isOpenMPTargetExecutionDirective(DKind) &&
2041 !Stack->isLoopControlVariable(FD).first &&
2042 !Stack->checkMappableExprComponentListsForDecl(
2043 FD, /*CurrentRegionOnly=*/true,
2044 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2045 StackComponents,
2046 OpenMPClauseKind) {
2047 return isa<CXXThisExpr>(
2048 cast<MemberExpr>(
2049 StackComponents.back().getAssociatedExpression())
2050 ->getBase()
2051 ->IgnoreParens());
2052 })) {
2053 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2054 // A bit-field cannot appear in a map clause.
2055 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002056 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002057 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002058 ImplicitMap.emplace_back(E);
2059 return;
2060 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002061
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002062 auto ELoc = E->getExprLoc();
2063 // OpenMP [2.9.3.6, Restrictions, p.2]
2064 // A list item that appears in a reduction clause of the innermost
2065 // enclosing worksharing or parallel construct may not be accessed in
2066 // an explicit task.
2067 DVar = Stack->hasInnermostDSA(
2068 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
2069 [](OpenMPDirectiveKind K) -> bool {
2070 return isOpenMPParallelDirective(K) ||
2071 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2072 },
2073 /*FromParent=*/true);
2074 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2075 ErrorFound = true;
2076 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2077 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
2078 return;
2079 }
2080
2081 // Define implicit data-sharing attributes for task.
2082 DVar = Stack->getImplicitDSA(FD, false);
2083 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2084 !Stack->isLoopControlVariable(FD).first)
2085 ImplicitFirstprivate.push_back(E);
2086 return;
2087 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002088 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002089 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002090 if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2091 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002092 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002093 auto *VD = cast<ValueDecl>(
2094 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2095 if (!Stack->checkMappableExprComponentListsForDecl(
2096 VD, /*CurrentRegionOnly=*/true,
2097 [&CurComponents](
2098 OMPClauseMappableExprCommon::MappableExprComponentListRef
2099 StackComponents,
2100 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002101 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002102 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002103 for (const auto &SC : llvm::reverse(StackComponents)) {
2104 // Do both expressions have the same kind?
2105 if (CCI->getAssociatedExpression()->getStmtClass() !=
2106 SC.getAssociatedExpression()->getStmtClass())
2107 if (!(isa<OMPArraySectionExpr>(
2108 SC.getAssociatedExpression()) &&
2109 isa<ArraySubscriptExpr>(
2110 CCI->getAssociatedExpression())))
2111 return false;
2112
2113 Decl *CCD = CCI->getAssociatedDeclaration();
2114 Decl *SCD = SC.getAssociatedDeclaration();
2115 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2116 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2117 if (SCD != CCD)
2118 return false;
2119 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002120 if (CCI == CCE)
2121 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002122 }
2123 return true;
2124 })) {
2125 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002126 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002127 } else
2128 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002129 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002130 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002131 for (auto *C : S->clauses()) {
2132 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002133 // for task|target directives.
2134 // Skip analysis of arguments of implicitly defined map clause for target
2135 // directives.
2136 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2137 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002138 for (auto *CC : C->children()) {
2139 if (CC)
2140 Visit(CC);
2141 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002142 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002143 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002144 }
2145 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002146 for (auto *C : S->children()) {
2147 if (C && !isa<OMPExecutableDirective>(C))
2148 Visit(C);
2149 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002150 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002151
2152 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002153 ArrayRef<Expr *> getImplicitFirstprivate() const {
2154 return ImplicitFirstprivate;
2155 }
2156 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002157 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002158 return VarsWithInheritedDSA;
2159 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002160
Alexey Bataev7ff55242014-06-19 09:13:45 +00002161 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2162 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002163};
Alexey Bataeved09d242014-05-28 05:53:51 +00002164} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002165
Alexey Bataevbae9a792014-06-27 10:37:06 +00002166void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002167 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002168 case OMPD_parallel:
2169 case OMPD_parallel_for:
2170 case OMPD_parallel_for_simd:
2171 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002172 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002173 case OMPD_teams_distribute:
2174 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002175 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002176 QualType KmpInt32PtrTy =
2177 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002178 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002179 std::make_pair(".global_tid.", KmpInt32PtrTy),
2180 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2181 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002182 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002183 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2184 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002185 break;
2186 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002187 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002188 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002189 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002190 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002191 case OMPD_target_teams_distribute:
2192 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002193 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2194 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2195 QualType KmpInt32PtrTy =
2196 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2197 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002198 FunctionProtoType::ExtProtoInfo EPI;
2199 EPI.Variadic = true;
2200 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2201 Sema::CapturedParamNameType Params[] = {
2202 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002203 std::make_pair(".part_id.", KmpInt32PtrTy),
2204 std::make_pair(".privates.", VoidPtrTy),
2205 std::make_pair(
2206 ".copy_fn.",
2207 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002208 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2209 std::make_pair(StringRef(), QualType()) // __context with shared vars
2210 };
2211 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2212 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002213 // Mark this captured region as inlined, because we don't use outlined
2214 // function directly.
2215 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2216 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002217 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002218 Sema::CapturedParamNameType ParamsTarget[] = {
2219 std::make_pair(StringRef(), QualType()) // __context with shared vars
2220 };
2221 // Start a captured region for 'target' with no implicit parameters.
2222 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2223 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002224 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002225 std::make_pair(".global_tid.", KmpInt32PtrTy),
2226 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2227 std::make_pair(StringRef(), QualType()) // __context with shared vars
2228 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002229 // Start a captured region for 'teams' or 'parallel'. Both regions have
2230 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002231 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002232 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002233 break;
2234 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002235 case OMPD_target:
2236 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002237 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2238 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2239 QualType KmpInt32PtrTy =
2240 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2241 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002242 FunctionProtoType::ExtProtoInfo EPI;
2243 EPI.Variadic = true;
2244 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2245 Sema::CapturedParamNameType Params[] = {
2246 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002247 std::make_pair(".part_id.", KmpInt32PtrTy),
2248 std::make_pair(".privates.", VoidPtrTy),
2249 std::make_pair(
2250 ".copy_fn.",
2251 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002252 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2253 std::make_pair(StringRef(), QualType()) // __context with shared vars
2254 };
2255 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2256 Params);
2257 // Mark this captured region as inlined, because we don't use outlined
2258 // function directly.
2259 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2260 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002261 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002262 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2263 std::make_pair(StringRef(), QualType()));
2264 break;
2265 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002266 case OMPD_simd:
2267 case OMPD_for:
2268 case OMPD_for_simd:
2269 case OMPD_sections:
2270 case OMPD_section:
2271 case OMPD_single:
2272 case OMPD_master:
2273 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002274 case OMPD_taskgroup:
2275 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002276 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002277 case OMPD_ordered:
2278 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002279 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002280 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002281 std::make_pair(StringRef(), QualType()) // __context with shared vars
2282 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002283 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2284 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002285 break;
2286 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002287 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002288 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2289 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2290 QualType KmpInt32PtrTy =
2291 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2292 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002293 FunctionProtoType::ExtProtoInfo EPI;
2294 EPI.Variadic = true;
2295 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002296 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002297 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002298 std::make_pair(".part_id.", KmpInt32PtrTy),
2299 std::make_pair(".privates.", VoidPtrTy),
2300 std::make_pair(
2301 ".copy_fn.",
2302 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002303 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002304 std::make_pair(StringRef(), QualType()) // __context with shared vars
2305 };
2306 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2307 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002308 // Mark this captured region as inlined, because we don't use outlined
2309 // function directly.
2310 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2311 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002312 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002313 break;
2314 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002315 case OMPD_taskloop:
2316 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002317 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002318 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2319 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002320 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002321 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2322 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002323 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002324 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2325 .withConst();
2326 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2327 QualType KmpInt32PtrTy =
2328 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2329 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002330 FunctionProtoType::ExtProtoInfo EPI;
2331 EPI.Variadic = true;
2332 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002333 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002334 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002335 std::make_pair(".part_id.", KmpInt32PtrTy),
2336 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002337 std::make_pair(
2338 ".copy_fn.",
2339 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2340 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2341 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002342 std::make_pair(".ub.", KmpUInt64Ty),
2343 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002344 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002345 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002346 std::make_pair(StringRef(), QualType()) // __context with shared vars
2347 };
2348 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2349 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002350 // Mark this captured region as inlined, because we don't use outlined
2351 // function directly.
2352 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2353 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002354 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002355 break;
2356 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002357 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002358 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002359 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002360 QualType KmpInt32PtrTy =
2361 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2362 Sema::CapturedParamNameType Params[] = {
2363 std::make_pair(".global_tid.", KmpInt32PtrTy),
2364 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002365 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2366 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002367 std::make_pair(StringRef(), QualType()) // __context with shared vars
2368 };
2369 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2370 Params);
2371 break;
2372 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002373 case OMPD_target_teams_distribute_parallel_for:
2374 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002375 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002376 QualType KmpInt32PtrTy =
2377 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002378 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002379
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002380 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002381 FunctionProtoType::ExtProtoInfo EPI;
2382 EPI.Variadic = true;
2383 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2384 Sema::CapturedParamNameType Params[] = {
2385 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002386 std::make_pair(".part_id.", KmpInt32PtrTy),
2387 std::make_pair(".privates.", VoidPtrTy),
2388 std::make_pair(
2389 ".copy_fn.",
2390 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002391 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2392 std::make_pair(StringRef(), QualType()) // __context with shared vars
2393 };
2394 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2395 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002396 // Mark this captured region as inlined, because we don't use outlined
2397 // function directly.
2398 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2399 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002400 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002401 Sema::CapturedParamNameType ParamsTarget[] = {
2402 std::make_pair(StringRef(), QualType()) // __context with shared vars
2403 };
2404 // Start a captured region for 'target' with no implicit parameters.
2405 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2406 ParamsTarget);
2407
2408 Sema::CapturedParamNameType ParamsTeams[] = {
2409 std::make_pair(".global_tid.", KmpInt32PtrTy),
2410 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2411 std::make_pair(StringRef(), QualType()) // __context with shared vars
2412 };
2413 // Start a captured region for 'target' with no implicit parameters.
2414 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2415 ParamsTeams);
2416
2417 Sema::CapturedParamNameType ParamsParallel[] = {
2418 std::make_pair(".global_tid.", KmpInt32PtrTy),
2419 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002420 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2421 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00002422 std::make_pair(StringRef(), QualType()) // __context with shared vars
2423 };
2424 // Start a captured region for 'teams' or 'parallel'. Both regions have
2425 // the same implicit parameters.
2426 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2427 ParamsParallel);
2428 break;
2429 }
2430
Alexey Bataev46506272017-12-05 17:41:34 +00002431 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002432 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002433 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00002434 QualType KmpInt32PtrTy =
2435 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2436
2437 Sema::CapturedParamNameType ParamsTeams[] = {
2438 std::make_pair(".global_tid.", KmpInt32PtrTy),
2439 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2440 std::make_pair(StringRef(), QualType()) // __context with shared vars
2441 };
2442 // Start a captured region for 'target' with no implicit parameters.
2443 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2444 ParamsTeams);
2445
2446 Sema::CapturedParamNameType ParamsParallel[] = {
2447 std::make_pair(".global_tid.", KmpInt32PtrTy),
2448 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002449 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2450 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00002451 std::make_pair(StringRef(), QualType()) // __context with shared vars
2452 };
2453 // Start a captured region for 'teams' or 'parallel'. Both regions have
2454 // the same implicit parameters.
2455 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2456 ParamsParallel);
2457 break;
2458 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002459 case OMPD_target_update:
2460 case OMPD_target_enter_data:
2461 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002462 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2463 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2464 QualType KmpInt32PtrTy =
2465 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2466 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00002467 FunctionProtoType::ExtProtoInfo EPI;
2468 EPI.Variadic = true;
2469 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2470 Sema::CapturedParamNameType Params[] = {
2471 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002472 std::make_pair(".part_id.", KmpInt32PtrTy),
2473 std::make_pair(".privates.", VoidPtrTy),
2474 std::make_pair(
2475 ".copy_fn.",
2476 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00002477 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2478 std::make_pair(StringRef(), QualType()) // __context with shared vars
2479 };
2480 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2481 Params);
2482 // Mark this captured region as inlined, because we don't use outlined
2483 // function directly.
2484 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2485 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002486 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00002487 break;
2488 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002489 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002490 case OMPD_taskyield:
2491 case OMPD_barrier:
2492 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002493 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002494 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002495 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002496 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002497 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002498 case OMPD_declare_target:
2499 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002500 llvm_unreachable("OpenMP Directive is not allowed");
2501 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002502 llvm_unreachable("Unknown OpenMP directive");
2503 }
2504}
2505
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002506int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2507 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2508 getOpenMPCaptureRegions(CaptureRegions, DKind);
2509 return CaptureRegions.size();
2510}
2511
Alexey Bataev3392d762016-02-16 11:18:12 +00002512static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002513 Expr *CaptureExpr, bool WithInit,
2514 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002515 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002516 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002517 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002518 QualType Ty = Init->getType();
2519 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002520 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002521 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002522 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002523 Ty = C.getPointerType(Ty);
2524 ExprResult Res =
2525 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2526 if (!Res.isUsable())
2527 return nullptr;
2528 Init = Res.get();
2529 }
Alexey Bataev61205072016-03-02 04:57:40 +00002530 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002531 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002532 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2533 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002534 if (!WithInit)
2535 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002536 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002537 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002538 return CED;
2539}
2540
Alexey Bataev61205072016-03-02 04:57:40 +00002541static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2542 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002543 OMPCapturedExprDecl *CD;
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002544 if (auto *VD = S.IsOpenMPCapturedDecl(D)) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002545 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002546 } else {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002547 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2548 /*AsExpression=*/false);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002549 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002550 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002551 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002552}
2553
Alexey Bataev5a3af132016-03-29 08:58:54 +00002554static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002555 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002556 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002557 OMPCapturedExprDecl *CD = buildCaptureDecl(
2558 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2559 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002560 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2561 CaptureExpr->getExprLoc());
2562 }
2563 ExprResult Res = Ref;
2564 if (!S.getLangOpts().CPlusPlus &&
2565 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002566 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002567 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002568 if (!Res.isUsable())
2569 return ExprError();
2570 }
2571 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002572}
2573
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002574namespace {
2575// OpenMP directives parsed in this section are represented as a
2576// CapturedStatement with an associated statement. If a syntax error
2577// is detected during the parsing of the associated statement, the
2578// compiler must abort processing and close the CapturedStatement.
2579//
2580// Combined directives such as 'target parallel' have more than one
2581// nested CapturedStatements. This RAII ensures that we unwind out
2582// of all the nested CapturedStatements when an error is found.
2583class CaptureRegionUnwinderRAII {
2584private:
2585 Sema &S;
2586 bool &ErrorFound;
2587 OpenMPDirectiveKind DKind;
2588
2589public:
2590 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2591 OpenMPDirectiveKind DKind)
2592 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2593 ~CaptureRegionUnwinderRAII() {
2594 if (ErrorFound) {
2595 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2596 while (--ThisCaptureLevel >= 0)
2597 S.ActOnCapturedRegionError();
2598 }
2599 }
2600};
2601} // namespace
2602
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002603StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2604 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002605 bool ErrorFound = false;
2606 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2607 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002608 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002609 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002610 return StmtError();
2611 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002612
Alexey Bataev2ba67042017-11-28 21:11:44 +00002613 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2614 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002615 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002616 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002617 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002618 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002619 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002620 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002621 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2622 Clause->getClauseKind() == OMPC_in_reduction) {
2623 // Capture taskgroup task_reduction descriptors inside the tasking regions
2624 // with the corresponding in_reduction items.
2625 auto *IRC = cast<OMPInReductionClause>(Clause);
2626 for (auto *E : IRC->taskgroup_descriptors())
2627 if (E)
2628 MarkDeclarationsReferencedInExpr(E);
2629 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002630 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002631 Clause->getClauseKind() == OMPC_copyprivate ||
2632 (getLangOpts().OpenMPUseTLS &&
2633 getASTContext().getTargetInfo().isTLSSupported() &&
2634 Clause->getClauseKind() == OMPC_copyin)) {
2635 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002636 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002637 for (auto *VarRef : Clause->children()) {
2638 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002639 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002640 }
2641 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002642 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002643 } else if (CaptureRegions.size() > 1 ||
2644 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002645 if (auto *C = OMPClauseWithPreInit::get(Clause))
2646 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002647 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2648 if (auto *E = C->getPostUpdateExpr())
2649 MarkDeclarationsReferencedInExpr(E);
2650 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002651 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002652 if (Clause->getClauseKind() == OMPC_schedule)
2653 SC = cast<OMPScheduleClause>(Clause);
2654 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002655 OC = cast<OMPOrderedClause>(Clause);
2656 else if (Clause->getClauseKind() == OMPC_linear)
2657 LCs.push_back(cast<OMPLinearClause>(Clause));
2658 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002659 // OpenMP, 2.7.1 Loop Construct, Restrictions
2660 // The nonmonotonic modifier cannot be specified if an ordered clause is
2661 // specified.
2662 if (SC &&
2663 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2664 SC->getSecondScheduleModifier() ==
2665 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2666 OC) {
2667 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2668 ? SC->getFirstScheduleModifierLoc()
2669 : SC->getSecondScheduleModifierLoc(),
2670 diag::err_omp_schedule_nonmonotonic_ordered)
2671 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2672 ErrorFound = true;
2673 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002674 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2675 for (auto *C : LCs) {
2676 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2677 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2678 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002679 ErrorFound = true;
2680 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002681 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2682 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2683 OC->getNumForLoops()) {
2684 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2685 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2686 ErrorFound = true;
2687 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002688 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002689 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002690 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002691 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002692 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002693 // Mark all variables in private list clauses as used in inner region.
2694 // Required for proper codegen of combined directives.
2695 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002696 if (ThisCaptureRegion != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002697 for (auto *C : PICs) {
2698 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2699 // Find the particular capture region for the clause if the
2700 // directive is a combined one with multiple capture regions.
2701 // If the directive is not a combined one, the capture region
2702 // associated with the clause is OMPD_unknown and is generated
2703 // only once.
2704 if (CaptureRegion == ThisCaptureRegion ||
2705 CaptureRegion == OMPD_unknown) {
2706 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2707 for (auto *D : DS->decls())
2708 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2709 }
2710 }
2711 }
2712 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002713 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002714 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002715 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002716}
2717
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002718static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2719 OpenMPDirectiveKind CancelRegion,
2720 SourceLocation StartLoc) {
2721 // CancelRegion is only needed for cancel and cancellation_point.
2722 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2723 return false;
2724
2725 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2726 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2727 return false;
2728
2729 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2730 << getOpenMPDirectiveName(CancelRegion);
2731 return true;
2732}
2733
2734static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002735 OpenMPDirectiveKind CurrentRegion,
2736 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002737 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002738 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002739 if (Stack->getCurScope()) {
2740 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002741 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002742 bool NestingProhibited = false;
2743 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002744 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002745 enum {
2746 NoRecommend,
2747 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002748 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002749 ShouldBeInTargetRegion,
2750 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002751 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002752 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002753 // OpenMP [2.16, Nesting of Regions]
2754 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002755 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002756 // An ordered construct with the simd clause is the only OpenMP
2757 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002758 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002759 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2760 // message.
2761 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2762 ? diag::err_omp_prohibited_region_simd
2763 : diag::warn_omp_nesting_simd);
2764 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002765 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002766 if (ParentRegion == OMPD_atomic) {
2767 // OpenMP [2.16, Nesting of Regions]
2768 // OpenMP constructs may not be nested inside an atomic region.
2769 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2770 return true;
2771 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002772 if (CurrentRegion == OMPD_section) {
2773 // OpenMP [2.7.2, sections Construct, Restrictions]
2774 // Orphaned section directives are prohibited. That is, the section
2775 // directives must appear within the sections construct and must not be
2776 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002777 if (ParentRegion != OMPD_sections &&
2778 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002779 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2780 << (ParentRegion != OMPD_unknown)
2781 << getOpenMPDirectiveName(ParentRegion);
2782 return true;
2783 }
2784 return false;
2785 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002786 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002787 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002788 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002789 if (ParentRegion == OMPD_unknown &&
2790 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002791 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002792 if (CurrentRegion == OMPD_cancellation_point ||
2793 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002794 // OpenMP [2.16, Nesting of Regions]
2795 // A cancellation point construct for which construct-type-clause is
2796 // taskgroup must be nested inside a task construct. A cancellation
2797 // point construct for which construct-type-clause is not taskgroup must
2798 // be closely nested inside an OpenMP construct that matches the type
2799 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002800 // A cancel construct for which construct-type-clause is taskgroup must be
2801 // nested inside a task construct. A cancel construct for which
2802 // construct-type-clause is not taskgroup must be closely nested inside an
2803 // OpenMP construct that matches the type specified in
2804 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002805 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002806 !((CancelRegion == OMPD_parallel &&
2807 (ParentRegion == OMPD_parallel ||
2808 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002809 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002810 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002811 ParentRegion == OMPD_target_parallel_for ||
2812 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002813 ParentRegion == OMPD_teams_distribute_parallel_for ||
2814 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002815 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2816 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002817 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2818 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002819 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002820 // OpenMP [2.16, Nesting of Regions]
2821 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002822 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002823 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002824 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002825 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2826 // OpenMP [2.16, Nesting of Regions]
2827 // A critical region may not be nested (closely or otherwise) inside a
2828 // critical region with the same name. Note that this restriction is not
2829 // sufficient to prevent deadlock.
2830 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002831 bool DeadLock = Stack->hasDirective(
2832 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2833 const DeclarationNameInfo &DNI,
2834 SourceLocation Loc) -> bool {
2835 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2836 PreviousCriticalLoc = Loc;
2837 return true;
2838 } else
2839 return false;
2840 },
2841 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002842 if (DeadLock) {
2843 SemaRef.Diag(StartLoc,
2844 diag::err_omp_prohibited_region_critical_same_name)
2845 << CurrentName.getName();
2846 if (PreviousCriticalLoc.isValid())
2847 SemaRef.Diag(PreviousCriticalLoc,
2848 diag::note_omp_previous_critical_region);
2849 return true;
2850 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002851 } else if (CurrentRegion == OMPD_barrier) {
2852 // OpenMP [2.16, Nesting of Regions]
2853 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002854 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002855 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2856 isOpenMPTaskingDirective(ParentRegion) ||
2857 ParentRegion == OMPD_master ||
2858 ParentRegion == OMPD_critical ||
2859 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002860 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002861 !isOpenMPParallelDirective(CurrentRegion) &&
2862 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002863 // OpenMP [2.16, Nesting of Regions]
2864 // A worksharing region may not be closely nested inside a worksharing,
2865 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002866 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2867 isOpenMPTaskingDirective(ParentRegion) ||
2868 ParentRegion == OMPD_master ||
2869 ParentRegion == OMPD_critical ||
2870 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002871 Recommend = ShouldBeInParallelRegion;
2872 } else if (CurrentRegion == OMPD_ordered) {
2873 // OpenMP [2.16, Nesting of Regions]
2874 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002875 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002876 // An ordered region must be closely nested inside a loop region (or
2877 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002878 // OpenMP [2.8.1,simd Construct, Restrictions]
2879 // An ordered construct with the simd clause is the only OpenMP construct
2880 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002881 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002882 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002883 !(isOpenMPSimdDirective(ParentRegion) ||
2884 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002885 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002886 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002887 // OpenMP [2.16, Nesting of Regions]
2888 // If specified, a teams construct must be contained within a target
2889 // construct.
2890 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002891 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002892 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002893 }
Kelvin Libf594a52016-12-17 05:48:59 +00002894 if (!NestingProhibited &&
2895 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2896 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2897 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002898 // OpenMP [2.16, Nesting of Regions]
2899 // distribute, parallel, parallel sections, parallel workshare, and the
2900 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2901 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002902 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2903 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002904 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002905 }
David Majnemer9d168222016-08-05 17:44:54 +00002906 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002907 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002908 // OpenMP 4.5 [2.17 Nesting of Regions]
2909 // The region associated with the distribute construct must be strictly
2910 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002911 NestingProhibited =
2912 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002913 Recommend = ShouldBeInTeamsRegion;
2914 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002915 if (!NestingProhibited &&
2916 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2917 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2918 // OpenMP 4.5 [2.17 Nesting of Regions]
2919 // If a target, target update, target data, target enter data, or
2920 // target exit data construct is encountered during execution of a
2921 // target region, the behavior is unspecified.
2922 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002923 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2924 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002925 if (isOpenMPTargetExecutionDirective(K)) {
2926 OffendingRegion = K;
2927 return true;
2928 } else
2929 return false;
2930 },
2931 false /* don't skip top directive */);
2932 CloseNesting = false;
2933 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002934 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002935 if (OrphanSeen) {
2936 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2937 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2938 } else {
2939 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2940 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2941 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2942 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002943 return true;
2944 }
2945 }
2946 return false;
2947}
2948
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002949static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2950 ArrayRef<OMPClause *> Clauses,
2951 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2952 bool ErrorFound = false;
2953 unsigned NamedModifiersNumber = 0;
2954 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2955 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002956 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002957 for (const auto *C : Clauses) {
2958 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2959 // At most one if clause without a directive-name-modifier can appear on
2960 // the directive.
2961 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2962 if (FoundNameModifiers[CurNM]) {
2963 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2964 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2965 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2966 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002967 } else if (CurNM != OMPD_unknown) {
2968 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002969 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002970 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002971 FoundNameModifiers[CurNM] = IC;
2972 if (CurNM == OMPD_unknown)
2973 continue;
2974 // Check if the specified name modifier is allowed for the current
2975 // directive.
2976 // At most one if clause with the particular directive-name-modifier can
2977 // appear on the directive.
2978 bool MatchFound = false;
2979 for (auto NM : AllowedNameModifiers) {
2980 if (CurNM == NM) {
2981 MatchFound = true;
2982 break;
2983 }
2984 }
2985 if (!MatchFound) {
2986 S.Diag(IC->getNameModifierLoc(),
2987 diag::err_omp_wrong_if_directive_name_modifier)
2988 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2989 ErrorFound = true;
2990 }
2991 }
2992 }
2993 // If any if clause on the directive includes a directive-name-modifier then
2994 // all if clauses on the directive must include a directive-name-modifier.
2995 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2996 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2997 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2998 diag::err_omp_no_more_if_clause);
2999 } else {
3000 std::string Values;
3001 std::string Sep(", ");
3002 unsigned AllowedCnt = 0;
3003 unsigned TotalAllowedNum =
3004 AllowedNameModifiers.size() - NamedModifiersNumber;
3005 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3006 ++Cnt) {
3007 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3008 if (!FoundNameModifiers[NM]) {
3009 Values += "'";
3010 Values += getOpenMPDirectiveName(NM);
3011 Values += "'";
3012 if (AllowedCnt + 2 == TotalAllowedNum)
3013 Values += " or ";
3014 else if (AllowedCnt + 1 != TotalAllowedNum)
3015 Values += Sep;
3016 ++AllowedCnt;
3017 }
3018 }
3019 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
3020 diag::err_omp_unnamed_if_clause)
3021 << (TotalAllowedNum > 1) << Values;
3022 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00003023 for (auto Loc : NameModifierLoc) {
3024 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3025 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003026 ErrorFound = true;
3027 }
3028 return ErrorFound;
3029}
3030
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003031StmtResult Sema::ActOnOpenMPExecutableDirective(
3032 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3033 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3034 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003035 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003036 // First check CancelRegion which is then used in checkNestingOfRegions.
3037 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3038 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003039 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003040 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003041
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003042 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003043 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003044 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003045 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003046 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003047 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3048
3049 // Check default data sharing attributes for referenced variables.
3050 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003051 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3052 Stmt *S = AStmt;
3053 while (--ThisCaptureLevel >= 0)
3054 S = cast<CapturedStmt>(S)->getCapturedStmt();
3055 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003056 if (DSAChecker.isErrorFound())
3057 return StmtError();
3058 // Generate list of implicitly defined firstprivate variables.
3059 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003060
Alexey Bataev88202be2017-07-27 13:20:36 +00003061 SmallVector<Expr *, 4> ImplicitFirstprivates(
3062 DSAChecker.getImplicitFirstprivate().begin(),
3063 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003064 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3065 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003066 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3067 for (auto *C : Clauses) {
3068 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3069 for (auto *E : IRC->taskgroup_descriptors())
3070 if (E)
3071 ImplicitFirstprivates.emplace_back(E);
3072 }
3073 }
3074 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003075 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003076 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3077 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003078 ClausesWithImplicit.push_back(Implicit);
3079 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003080 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00003081 } else
3082 ErrorFound = true;
3083 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003084 if (!ImplicitMaps.empty()) {
3085 if (OMPClause *Implicit = ActOnOpenMPMapClause(
3086 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3087 SourceLocation(), SourceLocation(), ImplicitMaps,
3088 SourceLocation(), SourceLocation(), SourceLocation())) {
3089 ClausesWithImplicit.emplace_back(Implicit);
3090 ErrorFound |=
3091 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3092 } else
3093 ErrorFound = true;
3094 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003095 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003096
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003097 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003098 switch (Kind) {
3099 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003100 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3101 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003102 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003103 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003104 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003105 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3106 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003107 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003108 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003109 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3110 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003111 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003112 case OMPD_for_simd:
3113 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3114 EndLoc, VarsWithInheritedDSA);
3115 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003116 case OMPD_sections:
3117 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3118 EndLoc);
3119 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003120 case OMPD_section:
3121 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003122 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003123 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3124 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003125 case OMPD_single:
3126 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3127 EndLoc);
3128 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003129 case OMPD_master:
3130 assert(ClausesWithImplicit.empty() &&
3131 "No clauses are allowed for 'omp master' directive");
3132 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3133 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003134 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003135 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3136 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003137 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003138 case OMPD_parallel_for:
3139 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3140 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003141 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003142 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003143 case OMPD_parallel_for_simd:
3144 Res = ActOnOpenMPParallelForSimdDirective(
3145 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003146 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003147 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003148 case OMPD_parallel_sections:
3149 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3150 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003151 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003152 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003153 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003154 Res =
3155 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003156 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003157 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003158 case OMPD_taskyield:
3159 assert(ClausesWithImplicit.empty() &&
3160 "No clauses are allowed for 'omp taskyield' directive");
3161 assert(AStmt == nullptr &&
3162 "No associated statement allowed for 'omp taskyield' directive");
3163 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3164 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003165 case OMPD_barrier:
3166 assert(ClausesWithImplicit.empty() &&
3167 "No clauses are allowed for 'omp barrier' directive");
3168 assert(AStmt == nullptr &&
3169 "No associated statement allowed for 'omp barrier' directive");
3170 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3171 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003172 case OMPD_taskwait:
3173 assert(ClausesWithImplicit.empty() &&
3174 "No clauses are allowed for 'omp taskwait' directive");
3175 assert(AStmt == nullptr &&
3176 "No associated statement allowed for 'omp taskwait' directive");
3177 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3178 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003179 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003180 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3181 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003182 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003183 case OMPD_flush:
3184 assert(AStmt == nullptr &&
3185 "No associated statement allowed for 'omp flush' directive");
3186 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3187 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003188 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003189 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3190 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003191 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003192 case OMPD_atomic:
3193 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3194 EndLoc);
3195 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003196 case OMPD_teams:
3197 Res =
3198 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3199 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003200 case OMPD_target:
3201 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3202 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003203 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003204 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003205 case OMPD_target_parallel:
3206 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3207 StartLoc, EndLoc);
3208 AllowedNameModifiers.push_back(OMPD_target);
3209 AllowedNameModifiers.push_back(OMPD_parallel);
3210 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003211 case OMPD_target_parallel_for:
3212 Res = ActOnOpenMPTargetParallelForDirective(
3213 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3214 AllowedNameModifiers.push_back(OMPD_target);
3215 AllowedNameModifiers.push_back(OMPD_parallel);
3216 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003217 case OMPD_cancellation_point:
3218 assert(ClausesWithImplicit.empty() &&
3219 "No clauses are allowed for 'omp cancellation point' directive");
3220 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3221 "cancellation point' directive");
3222 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3223 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003224 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003225 assert(AStmt == nullptr &&
3226 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003227 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3228 CancelRegion);
3229 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003230 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003231 case OMPD_target_data:
3232 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3233 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003234 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003235 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003236 case OMPD_target_enter_data:
3237 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003238 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003239 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3240 break;
Samuel Antao72590762016-01-19 20:04:50 +00003241 case OMPD_target_exit_data:
3242 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003243 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003244 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3245 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003246 case OMPD_taskloop:
3247 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3248 EndLoc, VarsWithInheritedDSA);
3249 AllowedNameModifiers.push_back(OMPD_taskloop);
3250 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003251 case OMPD_taskloop_simd:
3252 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3253 EndLoc, VarsWithInheritedDSA);
3254 AllowedNameModifiers.push_back(OMPD_taskloop);
3255 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003256 case OMPD_distribute:
3257 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3258 EndLoc, VarsWithInheritedDSA);
3259 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003260 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003261 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3262 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003263 AllowedNameModifiers.push_back(OMPD_target_update);
3264 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003265 case OMPD_distribute_parallel_for:
3266 Res = ActOnOpenMPDistributeParallelForDirective(
3267 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3268 AllowedNameModifiers.push_back(OMPD_parallel);
3269 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003270 case OMPD_distribute_parallel_for_simd:
3271 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3272 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3273 AllowedNameModifiers.push_back(OMPD_parallel);
3274 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003275 case OMPD_distribute_simd:
3276 Res = ActOnOpenMPDistributeSimdDirective(
3277 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3278 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003279 case OMPD_target_parallel_for_simd:
3280 Res = ActOnOpenMPTargetParallelForSimdDirective(
3281 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3282 AllowedNameModifiers.push_back(OMPD_target);
3283 AllowedNameModifiers.push_back(OMPD_parallel);
3284 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003285 case OMPD_target_simd:
3286 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3287 EndLoc, VarsWithInheritedDSA);
3288 AllowedNameModifiers.push_back(OMPD_target);
3289 break;
Kelvin Li02532872016-08-05 14:37:37 +00003290 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003291 Res = ActOnOpenMPTeamsDistributeDirective(
3292 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003293 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003294 case OMPD_teams_distribute_simd:
3295 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3296 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3297 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003298 case OMPD_teams_distribute_parallel_for_simd:
3299 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3300 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3301 AllowedNameModifiers.push_back(OMPD_parallel);
3302 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003303 case OMPD_teams_distribute_parallel_for:
3304 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3305 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3306 AllowedNameModifiers.push_back(OMPD_parallel);
3307 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003308 case OMPD_target_teams:
3309 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3310 EndLoc);
3311 AllowedNameModifiers.push_back(OMPD_target);
3312 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003313 case OMPD_target_teams_distribute:
3314 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3315 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3316 AllowedNameModifiers.push_back(OMPD_target);
3317 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003318 case OMPD_target_teams_distribute_parallel_for:
3319 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3320 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3321 AllowedNameModifiers.push_back(OMPD_target);
3322 AllowedNameModifiers.push_back(OMPD_parallel);
3323 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003324 case OMPD_target_teams_distribute_parallel_for_simd:
3325 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3326 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3327 AllowedNameModifiers.push_back(OMPD_target);
3328 AllowedNameModifiers.push_back(OMPD_parallel);
3329 break;
Kelvin Lida681182017-01-10 18:08:18 +00003330 case OMPD_target_teams_distribute_simd:
3331 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3332 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3333 AllowedNameModifiers.push_back(OMPD_target);
3334 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003335 case OMPD_declare_target:
3336 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003337 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003338 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003339 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003340 llvm_unreachable("OpenMP Directive is not allowed");
3341 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003342 llvm_unreachable("Unknown OpenMP directive");
3343 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003344
Alexey Bataev4acb8592014-07-07 13:01:15 +00003345 for (auto P : VarsWithInheritedDSA) {
3346 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3347 << P.first << P.second->getSourceRange();
3348 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003349 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3350
3351 if (!AllowedNameModifiers.empty())
3352 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3353 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003354
Alexey Bataeved09d242014-05-28 05:53:51 +00003355 if (ErrorFound)
3356 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003357 return Res;
3358}
3359
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003360Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3361 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003362 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003363 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3364 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003365 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003366 assert(Linears.size() == LinModifiers.size());
3367 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003368 if (!DG || DG.get().isNull())
3369 return DeclGroupPtrTy();
3370
3371 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003372 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003373 return DG;
3374 }
3375 auto *ADecl = DG.get().getSingleDecl();
3376 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3377 ADecl = FTD->getTemplatedDecl();
3378
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003379 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3380 if (!FD) {
3381 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003382 return DeclGroupPtrTy();
3383 }
3384
Alexey Bataev2af33e32016-04-07 12:45:37 +00003385 // OpenMP [2.8.2, declare simd construct, Description]
3386 // The parameter of the simdlen clause must be a constant positive integer
3387 // expression.
3388 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003389 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003390 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003391 // OpenMP [2.8.2, declare simd construct, Description]
3392 // The special this pointer can be used as if was one of the arguments to the
3393 // function in any of the linear, aligned, or uniform clauses.
3394 // The uniform clause declares one or more arguments to have an invariant
3395 // value for all concurrent invocations of the function in the execution of a
3396 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003397 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3398 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003399 for (auto *E : Uniforms) {
3400 E = E->IgnoreParenImpCasts();
3401 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3402 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3403 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3404 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003405 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3406 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003407 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003408 }
3409 if (isa<CXXThisExpr>(E)) {
3410 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003411 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003412 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003413 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3414 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003415 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003416 // OpenMP [2.8.2, declare simd construct, Description]
3417 // The aligned clause declares that the object to which each list item points
3418 // is aligned to the number of bytes expressed in the optional parameter of
3419 // the aligned clause.
3420 // The special this pointer can be used as if was one of the arguments to the
3421 // function in any of the linear, aligned, or uniform clauses.
3422 // The type of list items appearing in the aligned clause must be array,
3423 // pointer, reference to array, or reference to pointer.
3424 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3425 Expr *AlignedThis = nullptr;
3426 for (auto *E : Aligneds) {
3427 E = E->IgnoreParenImpCasts();
3428 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3429 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3430 auto *CanonPVD = PVD->getCanonicalDecl();
3431 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3432 FD->getParamDecl(PVD->getFunctionScopeIndex())
3433 ->getCanonicalDecl() == CanonPVD) {
3434 // OpenMP [2.8.1, simd construct, Restrictions]
3435 // A list-item cannot appear in more than one aligned clause.
3436 if (AlignedArgs.count(CanonPVD) > 0) {
3437 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3438 << 1 << E->getSourceRange();
3439 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3440 diag::note_omp_explicit_dsa)
3441 << getOpenMPClauseName(OMPC_aligned);
3442 continue;
3443 }
3444 AlignedArgs[CanonPVD] = E;
3445 QualType QTy = PVD->getType()
3446 .getNonReferenceType()
3447 .getUnqualifiedType()
3448 .getCanonicalType();
3449 const Type *Ty = QTy.getTypePtrOrNull();
3450 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3451 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3452 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3453 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3454 }
3455 continue;
3456 }
3457 }
3458 if (isa<CXXThisExpr>(E)) {
3459 if (AlignedThis) {
3460 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3461 << 2 << E->getSourceRange();
3462 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3463 << getOpenMPClauseName(OMPC_aligned);
3464 }
3465 AlignedThis = E;
3466 continue;
3467 }
3468 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3469 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3470 }
3471 // The optional parameter of the aligned clause, alignment, must be a constant
3472 // positive integer expression. If no optional parameter is specified,
3473 // implementation-defined default alignments for SIMD instructions on the
3474 // target platforms are assumed.
3475 SmallVector<Expr *, 4> NewAligns;
3476 for (auto *E : Alignments) {
3477 ExprResult Align;
3478 if (E)
3479 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3480 NewAligns.push_back(Align.get());
3481 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003482 // OpenMP [2.8.2, declare simd construct, Description]
3483 // The linear clause declares one or more list items to be private to a SIMD
3484 // lane and to have a linear relationship with respect to the iteration space
3485 // of a loop.
3486 // The special this pointer can be used as if was one of the arguments to the
3487 // function in any of the linear, aligned, or uniform clauses.
3488 // When a linear-step expression is specified in a linear clause it must be
3489 // either a constant integer expression or an integer-typed parameter that is
3490 // specified in a uniform clause on the directive.
3491 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3492 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3493 auto MI = LinModifiers.begin();
3494 for (auto *E : Linears) {
3495 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3496 ++MI;
3497 E = E->IgnoreParenImpCasts();
3498 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3499 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3500 auto *CanonPVD = PVD->getCanonicalDecl();
3501 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3502 FD->getParamDecl(PVD->getFunctionScopeIndex())
3503 ->getCanonicalDecl() == CanonPVD) {
3504 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3505 // A list-item cannot appear in more than one linear clause.
3506 if (LinearArgs.count(CanonPVD) > 0) {
3507 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3508 << getOpenMPClauseName(OMPC_linear)
3509 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3510 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3511 diag::note_omp_explicit_dsa)
3512 << getOpenMPClauseName(OMPC_linear);
3513 continue;
3514 }
3515 // Each argument can appear in at most one uniform or linear clause.
3516 if (UniformedArgs.count(CanonPVD) > 0) {
3517 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3518 << getOpenMPClauseName(OMPC_linear)
3519 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3520 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3521 diag::note_omp_explicit_dsa)
3522 << getOpenMPClauseName(OMPC_uniform);
3523 continue;
3524 }
3525 LinearArgs[CanonPVD] = E;
3526 if (E->isValueDependent() || E->isTypeDependent() ||
3527 E->isInstantiationDependent() ||
3528 E->containsUnexpandedParameterPack())
3529 continue;
3530 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3531 PVD->getOriginalType());
3532 continue;
3533 }
3534 }
3535 if (isa<CXXThisExpr>(E)) {
3536 if (UniformedLinearThis) {
3537 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3538 << getOpenMPClauseName(OMPC_linear)
3539 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3540 << E->getSourceRange();
3541 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3542 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3543 : OMPC_linear);
3544 continue;
3545 }
3546 UniformedLinearThis = E;
3547 if (E->isValueDependent() || E->isTypeDependent() ||
3548 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3549 continue;
3550 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3551 E->getType());
3552 continue;
3553 }
3554 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3555 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3556 }
3557 Expr *Step = nullptr;
3558 Expr *NewStep = nullptr;
3559 SmallVector<Expr *, 4> NewSteps;
3560 for (auto *E : Steps) {
3561 // Skip the same step expression, it was checked already.
3562 if (Step == E || !E) {
3563 NewSteps.push_back(E ? NewStep : nullptr);
3564 continue;
3565 }
3566 Step = E;
3567 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3568 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3569 auto *CanonPVD = PVD->getCanonicalDecl();
3570 if (UniformedArgs.count(CanonPVD) == 0) {
3571 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3572 << Step->getSourceRange();
3573 } else if (E->isValueDependent() || E->isTypeDependent() ||
3574 E->isInstantiationDependent() ||
3575 E->containsUnexpandedParameterPack() ||
3576 CanonPVD->getType()->hasIntegerRepresentation())
3577 NewSteps.push_back(Step);
3578 else {
3579 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3580 << Step->getSourceRange();
3581 }
3582 continue;
3583 }
3584 NewStep = Step;
3585 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3586 !Step->isInstantiationDependent() &&
3587 !Step->containsUnexpandedParameterPack()) {
3588 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3589 .get();
3590 if (NewStep)
3591 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3592 }
3593 NewSteps.push_back(NewStep);
3594 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003595 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3596 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003597 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003598 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3599 const_cast<Expr **>(Linears.data()), Linears.size(),
3600 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3601 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003602 ADecl->addAttr(NewAttr);
3603 return ConvertDeclToDeclGroup(ADecl);
3604}
3605
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003606StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3607 Stmt *AStmt,
3608 SourceLocation StartLoc,
3609 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003610 if (!AStmt)
3611 return StmtError();
3612
Alexey Bataev9959db52014-05-06 10:08:46 +00003613 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3614 // 1.2.2 OpenMP Language Terminology
3615 // Structured block - An executable statement with a single entry at the
3616 // top and a single exit at the bottom.
3617 // The point of exit cannot be a branch out of the structured block.
3618 // longjmp() and throw() must not violate the entry/exit criteria.
3619 CS->getCapturedDecl()->setNothrow();
3620
Reid Kleckner87a31802018-03-12 21:43:02 +00003621 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003622
Alexey Bataev25e5b442015-09-15 12:52:43 +00003623 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3624 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003625}
3626
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003627namespace {
3628/// \brief Helper class for checking canonical form of the OpenMP loops and
3629/// extracting iteration space of each loop in the loop nest, that will be used
3630/// for IR generation.
3631class OpenMPIterationSpaceChecker {
3632 /// \brief Reference to Sema.
3633 Sema &SemaRef;
3634 /// \brief A location for diagnostics (when there is no some better location).
3635 SourceLocation DefaultLoc;
3636 /// \brief A location for diagnostics (when increment is not compatible).
3637 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003638 /// \brief A source location for referring to loop init later.
3639 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003640 /// \brief A source location for referring to condition later.
3641 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003642 /// \brief A source location for referring to increment later.
3643 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003644 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003645 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003646 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003647 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003648 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003649 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003650 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003651 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003652 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003653 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003654 /// \brief This flag is true when condition is one of:
3655 /// Var < UB
3656 /// Var <= UB
3657 /// UB > Var
3658 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003659 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003660 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003661 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003662 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003663 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003664
3665public:
3666 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003667 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003668 /// \brief Check init-expr for canonical loop form and save loop counter
3669 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003670 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003671 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3672 /// for less/greater and for strict/non-strict comparison.
3673 bool CheckCond(Expr *S);
3674 /// \brief Check incr-expr for canonical loop form and return true if it
3675 /// does not conform, otherwise save loop step (#Step).
3676 bool CheckInc(Expr *S);
3677 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003678 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003679 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003680 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003681 /// \brief Source range of the loop init.
3682 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3683 /// \brief Source range of the loop condition.
3684 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3685 /// \brief Source range of the loop increment.
3686 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3687 /// \brief True if the step should be subtracted.
3688 bool ShouldSubtractStep() const { return SubtractStep; }
3689 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003690 Expr *
3691 BuildNumIterations(Scope *S, const bool LimitedType,
3692 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003693 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003694 Expr *BuildPreCond(Scope *S, Expr *Cond,
3695 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003696 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003697 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3698 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003699 /// \brief Build reference expression to the private counter be used for
3700 /// codegen.
3701 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003702 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003703 Expr *BuildCounterInit() const;
3704 /// \brief Build step of the counter be used for codegen.
3705 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003706 /// \brief Return true if any expression is dependent.
3707 bool Dependent() const;
3708
3709private:
3710 /// \brief Check the right-hand side of an assignment in the increment
3711 /// expression.
3712 bool CheckIncRHS(Expr *RHS);
3713 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003714 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003715 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003716 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003717 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003718 /// \brief Helper to set loop increment.
3719 bool SetStep(Expr *NewStep, bool Subtract);
3720};
3721
3722bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003723 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003724 assert(!LB && !UB && !Step);
3725 return false;
3726 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003727 return LCDecl->getType()->isDependentType() ||
3728 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3729 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003730}
3731
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003732bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3733 Expr *NewLCRefExpr,
3734 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003735 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003736 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003737 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003738 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003739 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003740 LCDecl = getCanonicalDecl(NewLCDecl);
3741 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003742 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3743 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003744 if ((Ctor->isCopyOrMoveConstructor() ||
3745 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3746 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003747 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003748 LB = NewLB;
3749 return false;
3750}
3751
3752bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003753 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003754 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003755 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3756 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003757 if (!NewUB)
3758 return true;
3759 UB = NewUB;
3760 TestIsLessOp = LessOp;
3761 TestIsStrictOp = StrictOp;
3762 ConditionSrcRange = SR;
3763 ConditionLoc = SL;
3764 return false;
3765}
3766
3767bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3768 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003769 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003770 if (!NewStep)
3771 return true;
3772 if (!NewStep->isValueDependent()) {
3773 // Check that the step is integer expression.
3774 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003775 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3776 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003777 if (Val.isInvalid())
3778 return true;
3779 NewStep = Val.get();
3780
3781 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3782 // If test-expr is of form var relational-op b and relational-op is < or
3783 // <= then incr-expr must cause var to increase on each iteration of the
3784 // loop. If test-expr is of form var relational-op b and relational-op is
3785 // > or >= then incr-expr must cause var to decrease on each iteration of
3786 // the loop.
3787 // If test-expr is of form b relational-op var and relational-op is < or
3788 // <= then incr-expr must cause var to decrease on each iteration of the
3789 // loop. If test-expr is of form b relational-op var and relational-op is
3790 // > or >= then incr-expr must cause var to increase on each iteration of
3791 // the loop.
3792 llvm::APSInt Result;
3793 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3794 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3795 bool IsConstNeg =
3796 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003797 bool IsConstPos =
3798 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003799 bool IsConstZero = IsConstant && !Result.getBoolValue();
3800 if (UB && (IsConstZero ||
3801 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003802 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003803 SemaRef.Diag(NewStep->getExprLoc(),
3804 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003805 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003806 SemaRef.Diag(ConditionLoc,
3807 diag::note_omp_loop_cond_requres_compatible_incr)
3808 << TestIsLessOp << ConditionSrcRange;
3809 return true;
3810 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003811 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003812 NewStep =
3813 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3814 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003815 Subtract = !Subtract;
3816 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003817 }
3818
3819 Step = NewStep;
3820 SubtractStep = Subtract;
3821 return false;
3822}
3823
Alexey Bataev9c821032015-04-30 04:23:23 +00003824bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003825 // Check init-expr for canonical loop form and save loop counter
3826 // variable - #Var and its initialization value - #LB.
3827 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3828 // var = lb
3829 // integer-type var = lb
3830 // random-access-iterator-type var = lb
3831 // pointer-type var = lb
3832 //
3833 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003834 if (EmitDiags) {
3835 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3836 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003837 return true;
3838 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003839 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3840 if (!ExprTemp->cleanupsHaveSideEffects())
3841 S = ExprTemp->getSubExpr();
3842
Alexander Musmana5f070a2014-10-01 06:03:56 +00003843 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003844 if (Expr *E = dyn_cast<Expr>(S))
3845 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003846 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003847 if (BO->getOpcode() == BO_Assign) {
3848 auto *LHS = BO->getLHS()->IgnoreParens();
3849 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3850 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3851 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3852 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3853 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3854 }
3855 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3856 if (ME->isArrow() &&
3857 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3858 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3859 }
3860 }
David Majnemer9d168222016-08-05 17:44:54 +00003861 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003862 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003863 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003864 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003865 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003866 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003867 SemaRef.Diag(S->getLocStart(),
3868 diag::ext_omp_loop_not_canonical_init)
3869 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003870 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003871 }
3872 }
3873 }
David Majnemer9d168222016-08-05 17:44:54 +00003874 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003875 if (CE->getOperator() == OO_Equal) {
3876 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003877 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003878 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3879 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3880 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3881 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3882 }
3883 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3884 if (ME->isArrow() &&
3885 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3886 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3887 }
3888 }
3889 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003890
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003891 if (Dependent() || SemaRef.CurContext->isDependentContext())
3892 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003893 if (EmitDiags) {
3894 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3895 << S->getSourceRange();
3896 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003897 return true;
3898}
3899
Alexey Bataev23b69422014-06-18 07:08:49 +00003900/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003901/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003902static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003903 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003904 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003905 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003906 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3907 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003908 if ((Ctor->isCopyOrMoveConstructor() ||
3909 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3910 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003911 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003912 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003913 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003914 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003915 }
3916 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3917 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3918 return getCanonicalDecl(ME->getMemberDecl());
3919 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003920}
3921
3922bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3923 // Check test-expr for canonical form, save upper-bound UB, flags for
3924 // less/greater and for strict/non-strict comparison.
3925 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3926 // var relational-op b
3927 // b relational-op var
3928 //
3929 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003930 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003931 return true;
3932 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003933 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003934 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003935 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003936 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003937 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003938 return SetUB(BO->getRHS(),
3939 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3940 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3941 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003942 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003943 return SetUB(BO->getLHS(),
3944 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3945 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3946 BO->getSourceRange(), BO->getOperatorLoc());
3947 }
David Majnemer9d168222016-08-05 17:44:54 +00003948 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003949 if (CE->getNumArgs() == 2) {
3950 auto Op = CE->getOperator();
3951 switch (Op) {
3952 case OO_Greater:
3953 case OO_GreaterEqual:
3954 case OO_Less:
3955 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003956 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003957 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3958 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3959 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003960 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003961 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3962 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3963 CE->getOperatorLoc());
3964 break;
3965 default:
3966 break;
3967 }
3968 }
3969 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003970 if (Dependent() || SemaRef.CurContext->isDependentContext())
3971 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003972 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003973 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003974 return true;
3975}
3976
3977bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3978 // RHS of canonical loop form increment can be:
3979 // var + incr
3980 // incr + var
3981 // var - incr
3982 //
3983 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003984 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003985 if (BO->isAdditiveOp()) {
3986 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003987 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003988 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003989 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003990 return SetStep(BO->getLHS(), false);
3991 }
David Majnemer9d168222016-08-05 17:44:54 +00003992 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003993 bool IsAdd = CE->getOperator() == OO_Plus;
3994 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003995 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003996 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003997 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003998 return SetStep(CE->getArg(0), false);
3999 }
4000 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004001 if (Dependent() || SemaRef.CurContext->isDependentContext())
4002 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004003 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004004 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004005 return true;
4006}
4007
4008bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
4009 // Check incr-expr for canonical loop form and return true if it
4010 // does not conform.
4011 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4012 // ++var
4013 // var++
4014 // --var
4015 // var--
4016 // var += incr
4017 // var -= incr
4018 // var = var + incr
4019 // var = incr + var
4020 // var = var - incr
4021 //
4022 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004023 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004024 return true;
4025 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004026 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4027 if (!ExprTemp->cleanupsHaveSideEffects())
4028 S = ExprTemp->getSubExpr();
4029
Alexander Musmana5f070a2014-10-01 06:03:56 +00004030 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004031 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004032 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004033 if (UO->isIncrementDecrementOp() &&
4034 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00004035 return SetStep(SemaRef
4036 .ActOnIntegerConstant(UO->getLocStart(),
4037 (UO->isDecrementOp() ? -1 : 1))
4038 .get(),
4039 false);
4040 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004041 switch (BO->getOpcode()) {
4042 case BO_AddAssign:
4043 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004044 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004045 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4046 break;
4047 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004048 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004049 return CheckIncRHS(BO->getRHS());
4050 break;
4051 default:
4052 break;
4053 }
David Majnemer9d168222016-08-05 17:44:54 +00004054 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004055 switch (CE->getOperator()) {
4056 case OO_PlusPlus:
4057 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004058 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00004059 return SetStep(SemaRef
4060 .ActOnIntegerConstant(
4061 CE->getLocStart(),
4062 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4063 .get(),
4064 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004065 break;
4066 case OO_PlusEqual:
4067 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004068 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004069 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4070 break;
4071 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004072 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004073 return CheckIncRHS(CE->getArg(1));
4074 break;
4075 default:
4076 break;
4077 }
4078 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004079 if (Dependent() || SemaRef.CurContext->isDependentContext())
4080 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004081 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004082 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004083 return true;
4084}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004085
Alexey Bataev5a3af132016-03-29 08:58:54 +00004086static ExprResult
4087tryBuildCapture(Sema &SemaRef, Expr *Capture,
4088 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004089 if (SemaRef.CurContext->isDependentContext())
4090 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004091 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4092 return SemaRef.PerformImplicitConversion(
4093 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4094 /*AllowExplicit=*/true);
4095 auto I = Captures.find(Capture);
4096 if (I != Captures.end())
4097 return buildCapture(SemaRef, Capture, I->second);
4098 DeclRefExpr *Ref = nullptr;
4099 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4100 Captures[Capture] = Ref;
4101 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004102}
4103
Alexander Musmana5f070a2014-10-01 06:03:56 +00004104/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004105Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4106 Scope *S, const bool LimitedType,
4107 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004108 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004109 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004110 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004111 SemaRef.getLangOpts().CPlusPlus) {
4112 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004113 auto *UBExpr = TestIsLessOp ? UB : LB;
4114 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004115 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4116 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004117 if (!Upper || !Lower)
4118 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004119
4120 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4121
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004122 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004123 // BuildBinOp already emitted error, this one is to point user to upper
4124 // and lower bound, and to tell what is passed to 'operator-'.
4125 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4126 << Upper->getSourceRange() << Lower->getSourceRange();
4127 return nullptr;
4128 }
4129 }
4130
4131 if (!Diff.isUsable())
4132 return nullptr;
4133
4134 // Upper - Lower [- 1]
4135 if (TestIsStrictOp)
4136 Diff = SemaRef.BuildBinOp(
4137 S, DefaultLoc, BO_Sub, Diff.get(),
4138 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4139 if (!Diff.isUsable())
4140 return nullptr;
4141
4142 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00004143 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4144 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004145 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004146 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004147 if (!Diff.isUsable())
4148 return nullptr;
4149
4150 // Parentheses (for dumping/debugging purposes only).
4151 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4152 if (!Diff.isUsable())
4153 return nullptr;
4154
4155 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004156 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004157 if (!Diff.isUsable())
4158 return nullptr;
4159
Alexander Musman174b3ca2014-10-06 11:16:29 +00004160 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004161 QualType Type = Diff.get()->getType();
4162 auto &C = SemaRef.Context;
4163 bool UseVarType = VarType->hasIntegerRepresentation() &&
4164 C.getTypeSize(Type) > C.getTypeSize(VarType);
4165 if (!Type->isIntegerType() || UseVarType) {
4166 unsigned NewSize =
4167 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4168 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4169 : Type->hasSignedIntegerRepresentation();
4170 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004171 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4172 Diff = SemaRef.PerformImplicitConversion(
4173 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4174 if (!Diff.isUsable())
4175 return nullptr;
4176 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004177 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004178 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004179 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4180 if (NewSize != C.getTypeSize(Type)) {
4181 if (NewSize < C.getTypeSize(Type)) {
4182 assert(NewSize == 64 && "incorrect loop var size");
4183 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4184 << InitSrcRange << ConditionSrcRange;
4185 }
4186 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004187 NewSize, Type->hasSignedIntegerRepresentation() ||
4188 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004189 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4190 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4191 Sema::AA_Converting, true);
4192 if (!Diff.isUsable())
4193 return nullptr;
4194 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004195 }
4196 }
4197
Alexander Musmana5f070a2014-10-01 06:03:56 +00004198 return Diff.get();
4199}
4200
Alexey Bataev5a3af132016-03-29 08:58:54 +00004201Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4202 Scope *S, Expr *Cond,
4203 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004204 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4205 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4206 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004207
Alexey Bataev5a3af132016-03-29 08:58:54 +00004208 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4209 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4210 if (!NewLB.isUsable() || !NewUB.isUsable())
4211 return nullptr;
4212
Alexey Bataev62dbb972015-04-22 11:59:37 +00004213 auto CondExpr = SemaRef.BuildBinOp(
4214 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4215 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004216 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004217 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004218 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4219 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004220 CondExpr = SemaRef.PerformImplicitConversion(
4221 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4222 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004223 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004224 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4225 // Otherwise use original loop conditon and evaluate it in runtime.
4226 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4227}
4228
Alexander Musmana5f070a2014-10-01 06:03:56 +00004229/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004230DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004231 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004232 auto *VD = dyn_cast<VarDecl>(LCDecl);
4233 if (!VD) {
4234 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4235 auto *Ref = buildDeclRefExpr(
4236 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004237 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4238 // If the loop control decl is explicitly marked as private, do not mark it
4239 // as captured again.
4240 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4241 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004242 return Ref;
4243 }
4244 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004245 DefaultLoc);
4246}
4247
4248Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004249 if (LCDecl && !LCDecl->isInvalidDecl()) {
4250 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004251 auto *PrivateVar = buildVarDecl(
4252 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4253 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4254 isa<VarDecl>(LCDecl)
4255 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4256 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004257 if (PrivateVar->isInvalidDecl())
4258 return nullptr;
4259 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4260 }
4261 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004262}
4263
Samuel Antao4c8035b2016-12-12 18:00:20 +00004264/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004265Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4266
4267/// \brief Build step of the counter be used for codegen.
4268Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4269
4270/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004271struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004272 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004273 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004274 /// \brief This expression calculates the number of iterations in the loop.
4275 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004276 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004277 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004278 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004279 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004280 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004281 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004282 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004283 /// \brief This is step for the #CounterVar used to generate its update:
4284 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004285 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004286 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004287 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004288 /// \brief Source range of the loop init.
4289 SourceRange InitSrcRange;
4290 /// \brief Source range of the loop condition.
4291 SourceRange CondSrcRange;
4292 /// \brief Source range of the loop increment.
4293 SourceRange IncSrcRange;
4294};
4295
Alexey Bataev23b69422014-06-18 07:08:49 +00004296} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004297
Alexey Bataev9c821032015-04-30 04:23:23 +00004298void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4299 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4300 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004301 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4302 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004303 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4304 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004305 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4306 if (auto *D = ISC.GetLoopDecl()) {
4307 auto *VD = dyn_cast<VarDecl>(D);
4308 if (!VD) {
4309 if (auto *Private = IsOpenMPCapturedDecl(D))
4310 VD = Private;
4311 else {
4312 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4313 /*WithInit=*/false);
4314 VD = cast<VarDecl>(Ref->getDecl());
4315 }
4316 }
4317 DSAStack->addLoopControlVariable(D, VD);
4318 }
4319 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004320 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004321 }
4322}
4323
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004324/// \brief Called on a for stmt to check and extract its iteration space
4325/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004326static bool CheckOpenMPIterationSpace(
4327 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4328 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004329 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004330 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004331 LoopIterationSpace &ResultIterSpace,
4332 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004333 // OpenMP [2.6, Canonical Loop Form]
4334 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004335 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004336 if (!For) {
4337 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004338 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4339 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4340 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4341 if (NestedLoopCount > 1) {
4342 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4343 SemaRef.Diag(DSA.getConstructLoc(),
4344 diag::note_omp_collapse_ordered_expr)
4345 << 2 << CollapseLoopCountExpr->getSourceRange()
4346 << OrderedLoopCountExpr->getSourceRange();
4347 else if (CollapseLoopCountExpr)
4348 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4349 diag::note_omp_collapse_ordered_expr)
4350 << 0 << CollapseLoopCountExpr->getSourceRange();
4351 else
4352 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4353 diag::note_omp_collapse_ordered_expr)
4354 << 1 << OrderedLoopCountExpr->getSourceRange();
4355 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004356 return true;
4357 }
4358 assert(For->getBody());
4359
4360 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4361
4362 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004363 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004364 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004365 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004366
4367 bool HasErrors = false;
4368
4369 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004370 if (auto *LCDecl = ISC.GetLoopDecl()) {
4371 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004372
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004373 // OpenMP [2.6, Canonical Loop Form]
4374 // Var is one of the following:
4375 // A variable of signed or unsigned integer type.
4376 // For C++, a variable of a random access iterator type.
4377 // For C, a variable of a pointer type.
4378 auto VarType = LCDecl->getType().getNonReferenceType();
4379 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4380 !VarType->isPointerType() &&
4381 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4382 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4383 << SemaRef.getLangOpts().CPlusPlus;
4384 HasErrors = true;
4385 }
4386
4387 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4388 // a Construct
4389 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4390 // parallel for construct is (are) private.
4391 // The loop iteration variable in the associated for-loop of a simd
4392 // construct with just one associated for-loop is linear with a
4393 // constant-linear-step that is the increment of the associated for-loop.
4394 // Exclude loop var from the list of variables with implicitly defined data
4395 // sharing attributes.
4396 VarsWithImplicitDSA.erase(LCDecl);
4397
4398 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4399 // in a Construct, C/C++].
4400 // The loop iteration variable in the associated for-loop of a simd
4401 // construct with just one associated for-loop may be listed in a linear
4402 // clause with a constant-linear-step that is the increment of the
4403 // associated for-loop.
4404 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4405 // parallel for construct may be listed in a private or lastprivate clause.
4406 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4407 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4408 // declared in the loop and it is predetermined as a private.
4409 auto PredeterminedCKind =
4410 isOpenMPSimdDirective(DKind)
4411 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4412 : OMPC_private;
4413 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4414 DVar.CKind != PredeterminedCKind) ||
4415 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4416 isOpenMPDistributeDirective(DKind)) &&
4417 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4418 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4419 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4420 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4421 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4422 << getOpenMPClauseName(PredeterminedCKind);
4423 if (DVar.RefExpr == nullptr)
4424 DVar.CKind = PredeterminedCKind;
4425 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4426 HasErrors = true;
4427 } else if (LoopDeclRefExpr != nullptr) {
4428 // Make the loop iteration variable private (for worksharing constructs),
4429 // linear (for simd directives with the only one associated loop) or
4430 // lastprivate (for simd directives with several collapsed or ordered
4431 // loops).
4432 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004433 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4434 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004435 /*FromParent=*/false);
4436 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4437 }
4438
4439 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4440
4441 // Check test-expr.
4442 HasErrors |= ISC.CheckCond(For->getCond());
4443
4444 // Check incr-expr.
4445 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004446 }
4447
Alexander Musmana5f070a2014-10-01 06:03:56 +00004448 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004449 return HasErrors;
4450
Alexander Musmana5f070a2014-10-01 06:03:56 +00004451 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004452 ResultIterSpace.PreCond =
4453 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004454 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004455 DSA.getCurScope(),
4456 (isOpenMPWorksharingDirective(DKind) ||
4457 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4458 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004459 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004460 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004461 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4462 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4463 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4464 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4465 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4466 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4467
Alexey Bataev62dbb972015-04-22 11:59:37 +00004468 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4469 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004470 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004471 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004472 ResultIterSpace.CounterInit == nullptr ||
4473 ResultIterSpace.CounterStep == nullptr);
4474
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004475 return HasErrors;
4476}
4477
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004478/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004479static ExprResult
4480BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4481 ExprResult Start,
4482 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004483 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004484 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4485 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004486 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004487 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004488 VarRef.get()->getType())) {
4489 NewStart = SemaRef.PerformImplicitConversion(
4490 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4491 /*AllowExplicit=*/true);
4492 if (!NewStart.isUsable())
4493 return ExprError();
4494 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004495
4496 auto Init =
4497 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4498 return Init;
4499}
4500
Alexander Musmana5f070a2014-10-01 06:03:56 +00004501/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004502static ExprResult
4503BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4504 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4505 ExprResult Step, bool Subtract,
4506 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004507 // Add parentheses (for debugging purposes only).
4508 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4509 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4510 !Step.isUsable())
4511 return ExprError();
4512
Alexey Bataev5a3af132016-03-29 08:58:54 +00004513 ExprResult NewStep = Step;
4514 if (Captures)
4515 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004516 if (NewStep.isInvalid())
4517 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004518 ExprResult Update =
4519 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004520 if (!Update.isUsable())
4521 return ExprError();
4522
Alexey Bataevc0214e02016-02-16 12:13:49 +00004523 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4524 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004525 ExprResult NewStart = Start;
4526 if (Captures)
4527 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004528 if (NewStart.isInvalid())
4529 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004530
Alexey Bataevc0214e02016-02-16 12:13:49 +00004531 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4532 ExprResult SavedUpdate = Update;
4533 ExprResult UpdateVal;
4534 if (VarRef.get()->getType()->isOverloadableType() ||
4535 NewStart.get()->getType()->isOverloadableType() ||
4536 Update.get()->getType()->isOverloadableType()) {
4537 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4538 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4539 Update =
4540 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4541 if (Update.isUsable()) {
4542 UpdateVal =
4543 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4544 VarRef.get(), SavedUpdate.get());
4545 if (UpdateVal.isUsable()) {
4546 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4547 UpdateVal.get());
4548 }
4549 }
4550 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4551 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004552
Alexey Bataevc0214e02016-02-16 12:13:49 +00004553 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4554 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4555 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4556 NewStart.get(), SavedUpdate.get());
4557 if (!Update.isUsable())
4558 return ExprError();
4559
Alexey Bataev11481f52016-02-17 10:29:05 +00004560 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4561 VarRef.get()->getType())) {
4562 Update = SemaRef.PerformImplicitConversion(
4563 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4564 if (!Update.isUsable())
4565 return ExprError();
4566 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004567
4568 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4569 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004570 return Update;
4571}
4572
4573/// \brief Convert integer expression \a E to make it have at least \a Bits
4574/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004575static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004576 if (E == nullptr)
4577 return ExprError();
4578 auto &C = SemaRef.Context;
4579 QualType OldType = E->getType();
4580 unsigned HasBits = C.getTypeSize(OldType);
4581 if (HasBits >= Bits)
4582 return ExprResult(E);
4583 // OK to convert to signed, because new type has more bits than old.
4584 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4585 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4586 true);
4587}
4588
4589/// \brief Check if the given expression \a E is a constant integer that fits
4590/// into \a Bits bits.
4591static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4592 if (E == nullptr)
4593 return false;
4594 llvm::APSInt Result;
4595 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4596 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4597 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004598}
4599
Alexey Bataev5a3af132016-03-29 08:58:54 +00004600/// Build preinits statement for the given declarations.
4601static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004602 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004603 if (!PreInits.empty()) {
4604 return new (Context) DeclStmt(
4605 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4606 SourceLocation(), SourceLocation());
4607 }
4608 return nullptr;
4609}
4610
4611/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004612static Stmt *
4613buildPreInits(ASTContext &Context,
4614 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004615 if (!Captures.empty()) {
4616 SmallVector<Decl *, 16> PreInits;
4617 for (auto &Pair : Captures)
4618 PreInits.push_back(Pair.second->getDecl());
4619 return buildPreInits(Context, PreInits);
4620 }
4621 return nullptr;
4622}
4623
4624/// Build postupdate expression for the given list of postupdates expressions.
4625static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4626 Expr *PostUpdate = nullptr;
4627 if (!PostUpdates.empty()) {
4628 for (auto *E : PostUpdates) {
4629 Expr *ConvE = S.BuildCStyleCastExpr(
4630 E->getExprLoc(),
4631 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4632 E->getExprLoc(), E)
4633 .get();
4634 PostUpdate = PostUpdate
4635 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4636 PostUpdate, ConvE)
4637 .get()
4638 : ConvE;
4639 }
4640 }
4641 return PostUpdate;
4642}
4643
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004644/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004645/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4646/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004647static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004648CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4649 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4650 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004651 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004652 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004653 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004654 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004655 // Found 'collapse' clause - calculate collapse number.
4656 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004657 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004658 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004659 }
4660 if (OrderedLoopCountExpr) {
4661 // Found 'ordered' clause - calculate collapse number.
4662 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004663 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4664 if (Result.getLimitedValue() < NestedLoopCount) {
4665 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4666 diag::err_omp_wrong_ordered_loop_count)
4667 << OrderedLoopCountExpr->getSourceRange();
4668 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4669 diag::note_collapse_loop_count)
4670 << CollapseLoopCountExpr->getSourceRange();
4671 }
4672 NestedLoopCount = Result.getLimitedValue();
4673 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004674 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004675 // This is helper routine for loop directives (e.g., 'for', 'simd',
4676 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004677 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004678 SmallVector<LoopIterationSpace, 4> IterSpaces;
4679 IterSpaces.resize(NestedLoopCount);
4680 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004681 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004682 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004683 NestedLoopCount, CollapseLoopCountExpr,
4684 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004685 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004686 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004687 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004688 // OpenMP [2.8.1, simd construct, Restrictions]
4689 // All loops associated with the construct must be perfectly nested; that
4690 // is, there must be no intervening code nor any OpenMP directive between
4691 // any two loops.
4692 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004693 }
4694
Alexander Musmana5f070a2014-10-01 06:03:56 +00004695 Built.clear(/* size */ NestedLoopCount);
4696
4697 if (SemaRef.CurContext->isDependentContext())
4698 return NestedLoopCount;
4699
4700 // An example of what is generated for the following code:
4701 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004702 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004703 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004704 // for (k = 0; k < NK; ++k)
4705 // for (j = J0; j < NJ; j+=2) {
4706 // <loop body>
4707 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004708 //
4709 // We generate the code below.
4710 // Note: the loop body may be outlined in CodeGen.
4711 // Note: some counters may be C++ classes, operator- is used to find number of
4712 // iterations and operator+= to calculate counter value.
4713 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4714 // or i64 is currently supported).
4715 //
4716 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4717 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4718 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4719 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4720 // // similar updates for vars in clauses (e.g. 'linear')
4721 // <loop body (using local i and j)>
4722 // }
4723 // i = NI; // assign final values of counters
4724 // j = NJ;
4725 //
4726
4727 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4728 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004729 // Precondition tests if there is at least one iteration (all conditions are
4730 // true).
4731 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004732 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004733 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004734 32 /* Bits */, SemaRef
4735 .PerformImplicitConversion(
4736 N0->IgnoreImpCasts(), N0->getType(),
4737 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004738 .get(),
4739 SemaRef);
4740 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004741 64 /* Bits */, SemaRef
4742 .PerformImplicitConversion(
4743 N0->IgnoreImpCasts(), N0->getType(),
4744 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004745 .get(),
4746 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004747
4748 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4749 return NestedLoopCount;
4750
4751 auto &C = SemaRef.Context;
4752 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4753
4754 Scope *CurScope = DSA.getCurScope();
4755 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004756 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004757 PreCond =
4758 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4759 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004760 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004761 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004762 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004763 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4764 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004765 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004766 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004767 SemaRef
4768 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4769 Sema::AA_Converting,
4770 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004771 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004772 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004773 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004774 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004775 SemaRef
4776 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4777 Sema::AA_Converting,
4778 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004779 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004780 }
4781
4782 // Choose either the 32-bit or 64-bit version.
4783 ExprResult LastIteration = LastIteration64;
4784 if (LastIteration32.isUsable() &&
4785 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4786 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4787 FitsInto(
4788 32 /* Bits */,
4789 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4790 LastIteration64.get(), SemaRef)))
4791 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004792 QualType VType = LastIteration.get()->getType();
4793 QualType RealVType = VType;
4794 QualType StrideVType = VType;
4795 if (isOpenMPTaskLoopDirective(DKind)) {
4796 VType =
4797 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4798 StrideVType =
4799 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4800 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004801
4802 if (!LastIteration.isUsable())
4803 return 0;
4804
4805 // Save the number of iterations.
4806 ExprResult NumIterations = LastIteration;
4807 {
4808 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004809 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4810 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004811 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4812 if (!LastIteration.isUsable())
4813 return 0;
4814 }
4815
4816 // Calculate the last iteration number beforehand instead of doing this on
4817 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4818 llvm::APSInt Result;
4819 bool IsConstant =
4820 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4821 ExprResult CalcLastIteration;
4822 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004823 ExprResult SaveRef =
4824 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004825 LastIteration = SaveRef;
4826
4827 // Prepare SaveRef + 1.
4828 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004829 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004830 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4831 if (!NumIterations.isUsable())
4832 return 0;
4833 }
4834
4835 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4836
David Majnemer9d168222016-08-05 17:44:54 +00004837 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004838 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004839 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4840 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004841 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004842 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4843 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004844 SemaRef.AddInitializerToDecl(LBDecl,
4845 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4846 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004847
4848 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004849 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4850 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004851 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004852 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004853
4854 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4855 // This will be used to implement clause 'lastprivate'.
4856 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004857 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4858 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004859 SemaRef.AddInitializerToDecl(ILDecl,
4860 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4861 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004862
4863 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004864 VarDecl *STDecl =
4865 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4866 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004867 SemaRef.AddInitializerToDecl(STDecl,
4868 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4869 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004870
4871 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004872 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004873 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4874 UB.get(), LastIteration.get());
4875 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4876 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4877 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4878 CondOp.get());
4879 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004880
4881 // If we have a combined directive that combines 'distribute', 'for' or
4882 // 'simd' we need to be able to access the bounds of the schedule of the
4883 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4884 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4885 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004886
Carlo Bertolliffafe102017-04-20 00:39:39 +00004887 // Lower bound variable, initialized with zero.
4888 VarDecl *CombLBDecl =
4889 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4890 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4891 SemaRef.AddInitializerToDecl(
4892 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4893 /*DirectInit*/ false);
4894
4895 // Upper bound variable, initialized with last iteration number.
4896 VarDecl *CombUBDecl =
4897 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4898 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4899 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4900 /*DirectInit*/ false);
4901
4902 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4903 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4904 ExprResult CombCondOp =
4905 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4906 LastIteration.get(), CombUB.get());
4907 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4908 CombCondOp.get());
4909 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4910
4911 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004912 // We expect to have at least 2 more parameters than the 'parallel'
4913 // directive does - the lower and upper bounds of the previous schedule.
4914 assert(CD->getNumParams() >= 4 &&
4915 "Unexpected number of parameters in loop combined directive");
4916
4917 // Set the proper type for the bounds given what we learned from the
4918 // enclosed loops.
4919 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4920 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4921
4922 // Previous lower and upper bounds are obtained from the region
4923 // parameters.
4924 PrevLB =
4925 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4926 PrevUB =
4927 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4928 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004929 }
4930
4931 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004932 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004933 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004934 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004935 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4936 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004937 Expr *RHS =
4938 (isOpenMPWorksharingDirective(DKind) ||
4939 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4940 ? LB.get()
4941 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004942 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4943 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004944
4945 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4946 Expr *CombRHS =
4947 (isOpenMPWorksharingDirective(DKind) ||
4948 isOpenMPTaskLoopDirective(DKind) ||
4949 isOpenMPDistributeDirective(DKind))
4950 ? CombLB.get()
4951 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4952 CombInit =
4953 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4954 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4955 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004956 }
4957
Alexander Musmanc6388682014-12-15 07:07:06 +00004958 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004959 SourceLocation CondLoc = AStmt->getLocStart();
Alexander Musmanc6388682014-12-15 07:07:06 +00004960 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004961 (isOpenMPWorksharingDirective(DKind) ||
4962 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004963 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4964 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4965 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004966 ExprResult CombCond;
4967 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4968 CombCond =
4969 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4970 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004971 // Loop increment (IV = IV + 1)
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004972 SourceLocation IncLoc = AStmt->getLocStart();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004973 ExprResult Inc =
4974 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4975 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4976 if (!Inc.isUsable())
4977 return 0;
4978 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004979 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4980 if (!Inc.isUsable())
4981 return 0;
4982
4983 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4984 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004985 // In combined construct, add combined version that use CombLB and CombUB
4986 // base variables for the update
4987 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004988 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4989 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004990 // LB + ST
4991 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4992 if (!NextLB.isUsable())
4993 return 0;
4994 // LB = LB + ST
4995 NextLB =
4996 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4997 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4998 if (!NextLB.isUsable())
4999 return 0;
5000 // UB + ST
5001 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5002 if (!NextUB.isUsable())
5003 return 0;
5004 // UB = UB + ST
5005 NextUB =
5006 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5007 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
5008 if (!NextUB.isUsable())
5009 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005010 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5011 CombNextLB =
5012 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5013 if (!NextLB.isUsable())
5014 return 0;
5015 // LB = LB + ST
5016 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5017 CombNextLB.get());
5018 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
5019 if (!CombNextLB.isUsable())
5020 return 0;
5021 // UB + ST
5022 CombNextUB =
5023 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5024 if (!CombNextUB.isUsable())
5025 return 0;
5026 // UB = UB + ST
5027 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5028 CombNextUB.get());
5029 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
5030 if (!CombNextUB.isUsable())
5031 return 0;
5032 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005033 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005034
Carlo Bertolliffafe102017-04-20 00:39:39 +00005035 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005036 // directive with for as IV = IV + ST; ensure upper bound expression based
5037 // on PrevUB instead of NumIterations - used to implement 'for' when found
5038 // in combination with 'distribute', like in 'distribute parallel for'
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005039 SourceLocation DistIncLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005040 ExprResult DistCond, DistInc, PrevEUB;
5041 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5042 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5043 assert(DistCond.isUsable() && "distribute cond expr was not built");
5044
5045 DistInc =
5046 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5047 assert(DistInc.isUsable() && "distribute inc expr was not built");
5048 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5049 DistInc.get());
5050 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5051 assert(DistInc.isUsable() && "distribute inc expr was not built");
5052
5053 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5054 // construct
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005055 SourceLocation DistEUBLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005056 ExprResult IsUBGreater =
5057 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5058 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5059 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5060 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5061 CondOp.get());
5062 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5063 }
5064
Alexander Musmana5f070a2014-10-01 06:03:56 +00005065 // Build updates and final values of the loop counters.
5066 bool HasErrors = false;
5067 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005068 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005069 Built.Updates.resize(NestedLoopCount);
5070 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00005071 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005072 {
5073 ExprResult Div;
5074 // Go from inner nested loop to outer.
5075 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5076 LoopIterationSpace &IS = IterSpaces[Cnt];
5077 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5078 // Build: Iter = (IV / Div) % IS.NumIters
5079 // where Div is product of previous iterations' IS.NumIters.
5080 ExprResult Iter;
5081 if (Div.isUsable()) {
5082 Iter =
5083 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5084 } else {
5085 Iter = IV;
5086 assert((Cnt == (int)NestedLoopCount - 1) &&
5087 "unusable div expected on first iteration only");
5088 }
5089
5090 if (Cnt != 0 && Iter.isUsable())
5091 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5092 IS.NumIterations);
5093 if (!Iter.isUsable()) {
5094 HasErrors = true;
5095 break;
5096 }
5097
Alexey Bataev39f915b82015-05-08 10:41:21 +00005098 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005099 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5100 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
5101 IS.CounterVar->getExprLoc(),
5102 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005103 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005104 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005105 if (!Init.isUsable()) {
5106 HasErrors = true;
5107 break;
5108 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00005109 ExprResult Update = BuildCounterUpdate(
5110 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5111 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005112 if (!Update.isUsable()) {
5113 HasErrors = true;
5114 break;
5115 }
5116
5117 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5118 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005119 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005120 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005121 if (!Final.isUsable()) {
5122 HasErrors = true;
5123 break;
5124 }
5125
5126 // Build Div for the next iteration: Div <- Div * IS.NumIters
5127 if (Cnt != 0) {
5128 if (Div.isUnset())
5129 Div = IS.NumIterations;
5130 else
5131 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5132 IS.NumIterations);
5133
5134 // Add parentheses (for debugging purposes only).
5135 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00005136 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005137 if (!Div.isUsable()) {
5138 HasErrors = true;
5139 break;
5140 }
Alexey Bataev8b427062016-05-25 12:36:08 +00005141 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005142 }
5143 if (!Update.isUsable() || !Final.isUsable()) {
5144 HasErrors = true;
5145 break;
5146 }
5147 // Save results
5148 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005149 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005150 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005151 Built.Updates[Cnt] = Update.get();
5152 Built.Finals[Cnt] = Final.get();
5153 }
5154 }
5155
5156 if (HasErrors)
5157 return 0;
5158
5159 // Save results
5160 Built.IterationVarRef = IV.get();
5161 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005162 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005163 Built.CalcLastIteration =
5164 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005165 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005166 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005167 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005168 Built.Init = Init.get();
5169 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005170 Built.LB = LB.get();
5171 Built.UB = UB.get();
5172 Built.IL = IL.get();
5173 Built.ST = ST.get();
5174 Built.EUB = EUB.get();
5175 Built.NLB = NextLB.get();
5176 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005177 Built.PrevLB = PrevLB.get();
5178 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005179 Built.DistInc = DistInc.get();
5180 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005181 Built.DistCombinedFields.LB = CombLB.get();
5182 Built.DistCombinedFields.UB = CombUB.get();
5183 Built.DistCombinedFields.EUB = CombEUB.get();
5184 Built.DistCombinedFields.Init = CombInit.get();
5185 Built.DistCombinedFields.Cond = CombCond.get();
5186 Built.DistCombinedFields.NLB = CombNextLB.get();
5187 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005188
Alexey Bataev8b427062016-05-25 12:36:08 +00005189 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5190 // Fill data for doacross depend clauses.
5191 for (auto Pair : DSA.getDoacrossDependClauses()) {
5192 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5193 Pair.first->setCounterValue(CounterVal);
5194 else {
5195 if (NestedLoopCount != Pair.second.size() ||
5196 NestedLoopCount != LoopMultipliers.size() + 1) {
5197 // Erroneous case - clause has some problems.
5198 Pair.first->setCounterValue(CounterVal);
5199 continue;
5200 }
5201 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5202 auto I = Pair.second.rbegin();
5203 auto IS = IterSpaces.rbegin();
5204 auto ILM = LoopMultipliers.rbegin();
5205 Expr *UpCounterVal = CounterVal;
5206 Expr *Multiplier = nullptr;
5207 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5208 if (I->first) {
5209 assert(IS->CounterStep);
5210 Expr *NormalizedOffset =
5211 SemaRef
5212 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5213 I->first, IS->CounterStep)
5214 .get();
5215 if (Multiplier) {
5216 NormalizedOffset =
5217 SemaRef
5218 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5219 NormalizedOffset, Multiplier)
5220 .get();
5221 }
5222 assert(I->second == OO_Plus || I->second == OO_Minus);
5223 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005224 UpCounterVal = SemaRef
5225 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5226 UpCounterVal, NormalizedOffset)
5227 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005228 }
5229 Multiplier = *ILM;
5230 ++I;
5231 ++IS;
5232 ++ILM;
5233 }
5234 Pair.first->setCounterValue(UpCounterVal);
5235 }
5236 }
5237
Alexey Bataevabfc0692014-06-25 06:52:00 +00005238 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005239}
5240
Alexey Bataev10e775f2015-07-30 11:36:16 +00005241static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005242 auto CollapseClauses =
5243 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5244 if (CollapseClauses.begin() != CollapseClauses.end())
5245 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005246 return nullptr;
5247}
5248
Alexey Bataev10e775f2015-07-30 11:36:16 +00005249static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005250 auto OrderedClauses =
5251 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5252 if (OrderedClauses.begin() != OrderedClauses.end())
5253 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005254 return nullptr;
5255}
5256
Kelvin Lic5609492016-07-15 04:39:07 +00005257static bool checkSimdlenSafelenSpecified(Sema &S,
5258 const ArrayRef<OMPClause *> Clauses) {
5259 OMPSafelenClause *Safelen = nullptr;
5260 OMPSimdlenClause *Simdlen = nullptr;
5261
5262 for (auto *Clause : Clauses) {
5263 if (Clause->getClauseKind() == OMPC_safelen)
5264 Safelen = cast<OMPSafelenClause>(Clause);
5265 else if (Clause->getClauseKind() == OMPC_simdlen)
5266 Simdlen = cast<OMPSimdlenClause>(Clause);
5267 if (Safelen && Simdlen)
5268 break;
5269 }
5270
5271 if (Simdlen && Safelen) {
5272 llvm::APSInt SimdlenRes, SafelenRes;
5273 auto SimdlenLength = Simdlen->getSimdlen();
5274 auto SafelenLength = Safelen->getSafelen();
5275 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5276 SimdlenLength->isInstantiationDependent() ||
5277 SimdlenLength->containsUnexpandedParameterPack())
5278 return false;
5279 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5280 SafelenLength->isInstantiationDependent() ||
5281 SafelenLength->containsUnexpandedParameterPack())
5282 return false;
5283 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5284 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5285 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5286 // If both simdlen and safelen clauses are specified, the value of the
5287 // simdlen parameter must be less than or equal to the value of the safelen
5288 // parameter.
5289 if (SimdlenRes > SafelenRes) {
5290 S.Diag(SimdlenLength->getExprLoc(),
5291 diag::err_omp_wrong_simdlen_safelen_values)
5292 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5293 return true;
5294 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005295 }
5296 return false;
5297}
5298
Alexey Bataev4acb8592014-07-07 13:01:15 +00005299StmtResult Sema::ActOnOpenMPSimdDirective(
5300 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5301 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005302 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005303 if (!AStmt)
5304 return StmtError();
5305
5306 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005307 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005308 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5309 // define the nested loops number.
5310 unsigned NestedLoopCount = CheckOpenMPLoop(
5311 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5312 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005313 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005314 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005315
Alexander Musmana5f070a2014-10-01 06:03:56 +00005316 assert((CurContext->isDependentContext() || B.builtAll()) &&
5317 "omp simd loop exprs were not built");
5318
Alexander Musman3276a272015-03-21 10:12:56 +00005319 if (!CurContext->isDependentContext()) {
5320 // Finalize the clauses that need pre-built expressions for CodeGen.
5321 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005322 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005323 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005324 B.NumIterations, *this, CurScope,
5325 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005326 return StmtError();
5327 }
5328 }
5329
Kelvin Lic5609492016-07-15 04:39:07 +00005330 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005331 return StmtError();
5332
Reid Kleckner87a31802018-03-12 21:43:02 +00005333 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005334 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5335 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005336}
5337
Alexey Bataev4acb8592014-07-07 13:01:15 +00005338StmtResult Sema::ActOnOpenMPForDirective(
5339 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5340 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005341 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005342 if (!AStmt)
5343 return StmtError();
5344
5345 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005346 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005347 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5348 // define the nested loops number.
5349 unsigned NestedLoopCount = CheckOpenMPLoop(
5350 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5351 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005352 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005353 return StmtError();
5354
Alexander Musmana5f070a2014-10-01 06:03:56 +00005355 assert((CurContext->isDependentContext() || B.builtAll()) &&
5356 "omp for loop exprs were not built");
5357
Alexey Bataev54acd402015-08-04 11:18:19 +00005358 if (!CurContext->isDependentContext()) {
5359 // Finalize the clauses that need pre-built expressions for CodeGen.
5360 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005361 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005362 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005363 B.NumIterations, *this, CurScope,
5364 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005365 return StmtError();
5366 }
5367 }
5368
Reid Kleckner87a31802018-03-12 21:43:02 +00005369 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005370 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005371 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005372}
5373
Alexander Musmanf82886e2014-09-18 05:12:34 +00005374StmtResult Sema::ActOnOpenMPForSimdDirective(
5375 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5376 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005377 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005378 if (!AStmt)
5379 return StmtError();
5380
5381 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005382 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005383 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5384 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005385 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005386 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5387 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5388 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005389 if (NestedLoopCount == 0)
5390 return StmtError();
5391
Alexander Musmanc6388682014-12-15 07:07:06 +00005392 assert((CurContext->isDependentContext() || B.builtAll()) &&
5393 "omp for simd loop exprs were not built");
5394
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005395 if (!CurContext->isDependentContext()) {
5396 // Finalize the clauses that need pre-built expressions for CodeGen.
5397 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005398 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005399 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005400 B.NumIterations, *this, CurScope,
5401 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005402 return StmtError();
5403 }
5404 }
5405
Kelvin Lic5609492016-07-15 04:39:07 +00005406 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005407 return StmtError();
5408
Reid Kleckner87a31802018-03-12 21:43:02 +00005409 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005410 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5411 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005412}
5413
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005414StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5415 Stmt *AStmt,
5416 SourceLocation StartLoc,
5417 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005418 if (!AStmt)
5419 return StmtError();
5420
5421 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005422 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005423 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005424 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005425 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005426 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005427 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005428 return StmtError();
5429 // All associated statements must be '#pragma omp section' except for
5430 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005431 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005432 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5433 if (SectionStmt)
5434 Diag(SectionStmt->getLocStart(),
5435 diag::err_omp_sections_substmt_not_section);
5436 return StmtError();
5437 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005438 cast<OMPSectionDirective>(SectionStmt)
5439 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005440 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005441 } else {
5442 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5443 return StmtError();
5444 }
5445
Reid Kleckner87a31802018-03-12 21:43:02 +00005446 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005447
Alexey Bataev25e5b442015-09-15 12:52:43 +00005448 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5449 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005450}
5451
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005452StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5453 SourceLocation StartLoc,
5454 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005455 if (!AStmt)
5456 return StmtError();
5457
5458 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005459
Reid Kleckner87a31802018-03-12 21:43:02 +00005460 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005461 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005462
Alexey Bataev25e5b442015-09-15 12:52:43 +00005463 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5464 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005465}
5466
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005467StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5468 Stmt *AStmt,
5469 SourceLocation StartLoc,
5470 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005471 if (!AStmt)
5472 return StmtError();
5473
5474 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005475
Reid Kleckner87a31802018-03-12 21:43:02 +00005476 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005477
Alexey Bataev3255bf32015-01-19 05:20:46 +00005478 // OpenMP [2.7.3, single Construct, Restrictions]
5479 // The copyprivate clause must not be used with the nowait clause.
5480 OMPClause *Nowait = nullptr;
5481 OMPClause *Copyprivate = nullptr;
5482 for (auto *Clause : Clauses) {
5483 if (Clause->getClauseKind() == OMPC_nowait)
5484 Nowait = Clause;
5485 else if (Clause->getClauseKind() == OMPC_copyprivate)
5486 Copyprivate = Clause;
5487 if (Copyprivate && Nowait) {
5488 Diag(Copyprivate->getLocStart(),
5489 diag::err_omp_single_copyprivate_with_nowait);
5490 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5491 return StmtError();
5492 }
5493 }
5494
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005495 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5496}
5497
Alexander Musman80c22892014-07-17 08:54:58 +00005498StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5499 SourceLocation StartLoc,
5500 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005501 if (!AStmt)
5502 return StmtError();
5503
5504 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005505
Reid Kleckner87a31802018-03-12 21:43:02 +00005506 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00005507
5508 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5509}
5510
Alexey Bataev28c75412015-12-15 08:19:24 +00005511StmtResult Sema::ActOnOpenMPCriticalDirective(
5512 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5513 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005514 if (!AStmt)
5515 return StmtError();
5516
5517 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005518
Alexey Bataev28c75412015-12-15 08:19:24 +00005519 bool ErrorFound = false;
5520 llvm::APSInt Hint;
5521 SourceLocation HintLoc;
5522 bool DependentHint = false;
5523 for (auto *C : Clauses) {
5524 if (C->getClauseKind() == OMPC_hint) {
5525 if (!DirName.getName()) {
5526 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5527 ErrorFound = true;
5528 }
5529 Expr *E = cast<OMPHintClause>(C)->getHint();
5530 if (E->isTypeDependent() || E->isValueDependent() ||
5531 E->isInstantiationDependent())
5532 DependentHint = true;
5533 else {
5534 Hint = E->EvaluateKnownConstInt(Context);
5535 HintLoc = C->getLocStart();
5536 }
5537 }
5538 }
5539 if (ErrorFound)
5540 return StmtError();
5541 auto Pair = DSAStack->getCriticalWithHint(DirName);
5542 if (Pair.first && DirName.getName() && !DependentHint) {
5543 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5544 Diag(StartLoc, diag::err_omp_critical_with_hint);
5545 if (HintLoc.isValid()) {
5546 Diag(HintLoc, diag::note_omp_critical_hint_here)
5547 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5548 } else
5549 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5550 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5551 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5552 << 1
5553 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5554 /*Radix=*/10, /*Signed=*/false);
5555 } else
5556 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5557 }
5558 }
5559
Reid Kleckner87a31802018-03-12 21:43:02 +00005560 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005561
Alexey Bataev28c75412015-12-15 08:19:24 +00005562 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5563 Clauses, AStmt);
5564 if (!Pair.first && DirName.getName() && !DependentHint)
5565 DSAStack->addCriticalWithHint(Dir, Hint);
5566 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005567}
5568
Alexey Bataev4acb8592014-07-07 13:01:15 +00005569StmtResult Sema::ActOnOpenMPParallelForDirective(
5570 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5571 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005572 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005573 if (!AStmt)
5574 return StmtError();
5575
Alexey Bataev4acb8592014-07-07 13:01:15 +00005576 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5577 // 1.2.2 OpenMP Language Terminology
5578 // Structured block - An executable statement with a single entry at the
5579 // top and a single exit at the bottom.
5580 // The point of exit cannot be a branch out of the structured block.
5581 // longjmp() and throw() must not violate the entry/exit criteria.
5582 CS->getCapturedDecl()->setNothrow();
5583
Alexander Musmanc6388682014-12-15 07:07:06 +00005584 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005585 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5586 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005587 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005588 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5589 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5590 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005591 if (NestedLoopCount == 0)
5592 return StmtError();
5593
Alexander Musmana5f070a2014-10-01 06:03:56 +00005594 assert((CurContext->isDependentContext() || B.builtAll()) &&
5595 "omp parallel for loop exprs were not built");
5596
Alexey Bataev54acd402015-08-04 11:18:19 +00005597 if (!CurContext->isDependentContext()) {
5598 // Finalize the clauses that need pre-built expressions for CodeGen.
5599 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005600 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005601 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005602 B.NumIterations, *this, CurScope,
5603 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005604 return StmtError();
5605 }
5606 }
5607
Reid Kleckner87a31802018-03-12 21:43:02 +00005608 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005609 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005610 NestedLoopCount, Clauses, AStmt, B,
5611 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005612}
5613
Alexander Musmane4e893b2014-09-23 09:33:00 +00005614StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5615 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5616 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005617 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005618 if (!AStmt)
5619 return StmtError();
5620
Alexander Musmane4e893b2014-09-23 09:33:00 +00005621 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5622 // 1.2.2 OpenMP Language Terminology
5623 // Structured block - An executable statement with a single entry at the
5624 // top and a single exit at the bottom.
5625 // The point of exit cannot be a branch out of the structured block.
5626 // longjmp() and throw() must not violate the entry/exit criteria.
5627 CS->getCapturedDecl()->setNothrow();
5628
Alexander Musmanc6388682014-12-15 07:07:06 +00005629 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005630 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5631 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005632 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005633 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5634 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5635 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005636 if (NestedLoopCount == 0)
5637 return StmtError();
5638
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005639 if (!CurContext->isDependentContext()) {
5640 // Finalize the clauses that need pre-built expressions for CodeGen.
5641 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005642 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005643 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005644 B.NumIterations, *this, CurScope,
5645 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005646 return StmtError();
5647 }
5648 }
5649
Kelvin Lic5609492016-07-15 04:39:07 +00005650 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005651 return StmtError();
5652
Reid Kleckner87a31802018-03-12 21:43:02 +00005653 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005654 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005655 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005656}
5657
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005658StmtResult
5659Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5660 Stmt *AStmt, SourceLocation StartLoc,
5661 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005662 if (!AStmt)
5663 return StmtError();
5664
5665 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005666 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005667 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005668 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005669 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005670 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005671 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005672 return StmtError();
5673 // All associated statements must be '#pragma omp section' except for
5674 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005675 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005676 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5677 if (SectionStmt)
5678 Diag(SectionStmt->getLocStart(),
5679 diag::err_omp_parallel_sections_substmt_not_section);
5680 return StmtError();
5681 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005682 cast<OMPSectionDirective>(SectionStmt)
5683 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005684 }
5685 } else {
5686 Diag(AStmt->getLocStart(),
5687 diag::err_omp_parallel_sections_not_compound_stmt);
5688 return StmtError();
5689 }
5690
Reid Kleckner87a31802018-03-12 21:43:02 +00005691 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005692
Alexey Bataev25e5b442015-09-15 12:52:43 +00005693 return OMPParallelSectionsDirective::Create(
5694 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005695}
5696
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005697StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5698 Stmt *AStmt, SourceLocation StartLoc,
5699 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005700 if (!AStmt)
5701 return StmtError();
5702
David Majnemer9d168222016-08-05 17:44:54 +00005703 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005704 // 1.2.2 OpenMP Language Terminology
5705 // Structured block - An executable statement with a single entry at the
5706 // top and a single exit at the bottom.
5707 // The point of exit cannot be a branch out of the structured block.
5708 // longjmp() and throw() must not violate the entry/exit criteria.
5709 CS->getCapturedDecl()->setNothrow();
5710
Reid Kleckner87a31802018-03-12 21:43:02 +00005711 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005712
Alexey Bataev25e5b442015-09-15 12:52:43 +00005713 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5714 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005715}
5716
Alexey Bataev68446b72014-07-18 07:47:19 +00005717StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5718 SourceLocation EndLoc) {
5719 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5720}
5721
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005722StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5723 SourceLocation EndLoc) {
5724 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5725}
5726
Alexey Bataev2df347a2014-07-18 10:17:07 +00005727StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5728 SourceLocation EndLoc) {
5729 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5730}
5731
Alexey Bataev169d96a2017-07-18 20:17:46 +00005732StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5733 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005734 SourceLocation StartLoc,
5735 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005736 if (!AStmt)
5737 return StmtError();
5738
5739 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005740
Reid Kleckner87a31802018-03-12 21:43:02 +00005741 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005742
Alexey Bataev169d96a2017-07-18 20:17:46 +00005743 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005744 AStmt,
5745 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005746}
5747
Alexey Bataev6125da92014-07-21 11:26:11 +00005748StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5749 SourceLocation StartLoc,
5750 SourceLocation EndLoc) {
5751 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5752 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5753}
5754
Alexey Bataev346265e2015-09-25 10:37:12 +00005755StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5756 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005757 SourceLocation StartLoc,
5758 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005759 OMPClause *DependFound = nullptr;
5760 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005761 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005762 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005763 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005764 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005765 for (auto *C : Clauses) {
5766 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5767 DependFound = C;
5768 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5769 if (DependSourceClause) {
5770 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5771 << getOpenMPDirectiveName(OMPD_ordered)
5772 << getOpenMPClauseName(OMPC_depend) << 2;
5773 ErrorFound = true;
5774 } else
5775 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005776 if (DependSinkClause) {
5777 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5778 << 0;
5779 ErrorFound = true;
5780 }
5781 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5782 if (DependSourceClause) {
5783 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5784 << 1;
5785 ErrorFound = true;
5786 }
5787 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005788 }
5789 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005790 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005791 else if (C->getClauseKind() == OMPC_simd)
5792 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005793 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005794 if (!ErrorFound && !SC &&
5795 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005796 // OpenMP [2.8.1,simd Construct, Restrictions]
5797 // An ordered construct with the simd clause is the only OpenMP construct
5798 // that can appear in the simd region.
5799 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005800 ErrorFound = true;
5801 } else if (DependFound && (TC || SC)) {
5802 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5803 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5804 ErrorFound = true;
5805 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5806 Diag(DependFound->getLocStart(),
5807 diag::err_omp_ordered_directive_without_param);
5808 ErrorFound = true;
5809 } else if (TC || Clauses.empty()) {
5810 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5811 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5812 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5813 << (TC != nullptr);
5814 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5815 ErrorFound = true;
5816 }
5817 }
5818 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005819 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005820
5821 if (AStmt) {
5822 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5823
Reid Kleckner87a31802018-03-12 21:43:02 +00005824 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005825 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005826
5827 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005828}
5829
Alexey Bataev1d160b12015-03-13 12:27:31 +00005830namespace {
5831/// \brief Helper class for checking expression in 'omp atomic [update]'
5832/// construct.
5833class OpenMPAtomicUpdateChecker {
5834 /// \brief Error results for atomic update expressions.
5835 enum ExprAnalysisErrorCode {
5836 /// \brief A statement is not an expression statement.
5837 NotAnExpression,
5838 /// \brief Expression is not builtin binary or unary operation.
5839 NotABinaryOrUnaryExpression,
5840 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5841 NotAnUnaryIncDecExpression,
5842 /// \brief An expression is not of scalar type.
5843 NotAScalarType,
5844 /// \brief A binary operation is not an assignment operation.
5845 NotAnAssignmentOp,
5846 /// \brief RHS part of the binary operation is not a binary expression.
5847 NotABinaryExpression,
5848 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5849 /// expression.
5850 NotABinaryOperator,
5851 /// \brief RHS binary operation does not have reference to the updated LHS
5852 /// part.
5853 NotAnUpdateExpression,
5854 /// \brief No errors is found.
5855 NoError
5856 };
5857 /// \brief Reference to Sema.
5858 Sema &SemaRef;
5859 /// \brief A location for note diagnostics (when error is found).
5860 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005861 /// \brief 'x' lvalue part of the source atomic expression.
5862 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005863 /// \brief 'expr' rvalue part of the source atomic expression.
5864 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005865 /// \brief Helper expression of the form
5866 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5867 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5868 Expr *UpdateExpr;
5869 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5870 /// important for non-associative operations.
5871 bool IsXLHSInRHSPart;
5872 BinaryOperatorKind Op;
5873 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005874 /// \brief true if the source expression is a postfix unary operation, false
5875 /// if it is a prefix unary operation.
5876 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005877
5878public:
5879 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005880 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005881 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005882 /// \brief Check specified statement that it is suitable for 'atomic update'
5883 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005884 /// expression. If DiagId and NoteId == 0, then only check is performed
5885 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005886 /// \param DiagId Diagnostic which should be emitted if error is found.
5887 /// \param NoteId Diagnostic note for the main error message.
5888 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005889 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005890 /// \brief Return the 'x' lvalue part of the source atomic expression.
5891 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005892 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5893 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005894 /// \brief Return the update expression used in calculation of the updated
5895 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5896 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5897 Expr *getUpdateExpr() const { return UpdateExpr; }
5898 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5899 /// false otherwise.
5900 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5901
Alexey Bataevb78ca832015-04-01 03:33:17 +00005902 /// \brief true if the source expression is a postfix unary operation, false
5903 /// if it is a prefix unary operation.
5904 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5905
Alexey Bataev1d160b12015-03-13 12:27:31 +00005906private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005907 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5908 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005909};
5910} // namespace
5911
5912bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5913 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5914 ExprAnalysisErrorCode ErrorFound = NoError;
5915 SourceLocation ErrorLoc, NoteLoc;
5916 SourceRange ErrorRange, NoteRange;
5917 // Allowed constructs are:
5918 // x = x binop expr;
5919 // x = expr binop x;
5920 if (AtomicBinOp->getOpcode() == BO_Assign) {
5921 X = AtomicBinOp->getLHS();
5922 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5923 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5924 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5925 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5926 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005927 Op = AtomicInnerBinOp->getOpcode();
5928 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005929 auto *LHS = AtomicInnerBinOp->getLHS();
5930 auto *RHS = AtomicInnerBinOp->getRHS();
5931 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5932 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5933 /*Canonical=*/true);
5934 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5935 /*Canonical=*/true);
5936 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5937 /*Canonical=*/true);
5938 if (XId == LHSId) {
5939 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005940 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005941 } else if (XId == RHSId) {
5942 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005943 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005944 } else {
5945 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5946 ErrorRange = AtomicInnerBinOp->getSourceRange();
5947 NoteLoc = X->getExprLoc();
5948 NoteRange = X->getSourceRange();
5949 ErrorFound = NotAnUpdateExpression;
5950 }
5951 } else {
5952 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5953 ErrorRange = AtomicInnerBinOp->getSourceRange();
5954 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5955 NoteRange = SourceRange(NoteLoc, NoteLoc);
5956 ErrorFound = NotABinaryOperator;
5957 }
5958 } else {
5959 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5960 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5961 ErrorFound = NotABinaryExpression;
5962 }
5963 } else {
5964 ErrorLoc = AtomicBinOp->getExprLoc();
5965 ErrorRange = AtomicBinOp->getSourceRange();
5966 NoteLoc = AtomicBinOp->getOperatorLoc();
5967 NoteRange = SourceRange(NoteLoc, NoteLoc);
5968 ErrorFound = NotAnAssignmentOp;
5969 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005970 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005971 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5972 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5973 return true;
5974 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005975 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005976 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005977}
5978
5979bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5980 unsigned NoteId) {
5981 ExprAnalysisErrorCode ErrorFound = NoError;
5982 SourceLocation ErrorLoc, NoteLoc;
5983 SourceRange ErrorRange, NoteRange;
5984 // Allowed constructs are:
5985 // x++;
5986 // x--;
5987 // ++x;
5988 // --x;
5989 // x binop= expr;
5990 // x = x binop expr;
5991 // x = expr binop x;
5992 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5993 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5994 if (AtomicBody->getType()->isScalarType() ||
5995 AtomicBody->isInstantiationDependent()) {
5996 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5997 AtomicBody->IgnoreParenImpCasts())) {
5998 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005999 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006000 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006001 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006002 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006003 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006004 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006005 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6006 AtomicBody->IgnoreParenImpCasts())) {
6007 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006008 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006009 return true;
David Majnemer9d168222016-08-05 17:44:54 +00006010 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
6011 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006012 // Check for Unary Operation
6013 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006014 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006015 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6016 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006017 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006018 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6019 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006020 } else {
6021 ErrorFound = NotAnUnaryIncDecExpression;
6022 ErrorLoc = AtomicUnaryOp->getExprLoc();
6023 ErrorRange = AtomicUnaryOp->getSourceRange();
6024 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6025 NoteRange = SourceRange(NoteLoc, NoteLoc);
6026 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006027 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006028 ErrorFound = NotABinaryOrUnaryExpression;
6029 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6030 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6031 }
6032 } else {
6033 ErrorFound = NotAScalarType;
6034 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
6035 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6036 }
6037 } else {
6038 ErrorFound = NotAnExpression;
6039 NoteLoc = ErrorLoc = S->getLocStart();
6040 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6041 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006042 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006043 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6044 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6045 return true;
6046 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006047 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006048 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006049 // Build an update expression of form 'OpaqueValueExpr(x) binop
6050 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6051 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6052 auto *OVEX = new (SemaRef.getASTContext())
6053 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6054 auto *OVEExpr = new (SemaRef.getASTContext())
6055 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6056 auto Update =
6057 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6058 IsXLHSInRHSPart ? OVEExpr : OVEX);
6059 if (Update.isInvalid())
6060 return true;
6061 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6062 Sema::AA_Casting);
6063 if (Update.isInvalid())
6064 return true;
6065 UpdateExpr = Update.get();
6066 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006067 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006068}
6069
Alexey Bataev0162e452014-07-22 10:10:35 +00006070StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6071 Stmt *AStmt,
6072 SourceLocation StartLoc,
6073 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006074 if (!AStmt)
6075 return StmtError();
6076
David Majnemer9d168222016-08-05 17:44:54 +00006077 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006078 // 1.2.2 OpenMP Language Terminology
6079 // Structured block - An executable statement with a single entry at the
6080 // top and a single exit at the bottom.
6081 // The point of exit cannot be a branch out of the structured block.
6082 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006083 OpenMPClauseKind AtomicKind = OMPC_unknown;
6084 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006085 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006086 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006087 C->getClauseKind() == OMPC_update ||
6088 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006089 if (AtomicKind != OMPC_unknown) {
6090 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
6091 << SourceRange(C->getLocStart(), C->getLocEnd());
6092 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6093 << getOpenMPClauseName(AtomicKind);
6094 } else {
6095 AtomicKind = C->getClauseKind();
6096 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006097 }
6098 }
6099 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006100
Alexey Bataev459dec02014-07-24 06:46:57 +00006101 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006102 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6103 Body = EWC->getSubExpr();
6104
Alexey Bataev62cec442014-11-18 10:14:22 +00006105 Expr *X = nullptr;
6106 Expr *V = nullptr;
6107 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006108 Expr *UE = nullptr;
6109 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006110 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006111 // OpenMP [2.12.6, atomic Construct]
6112 // In the next expressions:
6113 // * x and v (as applicable) are both l-value expressions with scalar type.
6114 // * During the execution of an atomic region, multiple syntactic
6115 // occurrences of x must designate the same storage location.
6116 // * Neither of v and expr (as applicable) may access the storage location
6117 // designated by x.
6118 // * Neither of x and expr (as applicable) may access the storage location
6119 // designated by v.
6120 // * expr is an expression with scalar type.
6121 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6122 // * binop, binop=, ++, and -- are not overloaded operators.
6123 // * The expression x binop expr must be numerically equivalent to x binop
6124 // (expr). This requirement is satisfied if the operators in expr have
6125 // precedence greater than binop, or by using parentheses around expr or
6126 // subexpressions of expr.
6127 // * The expression expr binop x must be numerically equivalent to (expr)
6128 // binop x. This requirement is satisfied if the operators in expr have
6129 // precedence equal to or greater than binop, or by using parentheses around
6130 // expr or subexpressions of expr.
6131 // * For forms that allow multiple occurrences of x, the number of times
6132 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006133 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006134 enum {
6135 NotAnExpression,
6136 NotAnAssignmentOp,
6137 NotAScalarType,
6138 NotAnLValue,
6139 NoError
6140 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006141 SourceLocation ErrorLoc, NoteLoc;
6142 SourceRange ErrorRange, NoteRange;
6143 // If clause is read:
6144 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00006145 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6146 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006147 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6148 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6149 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6150 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6151 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6152 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6153 if (!X->isLValue() || !V->isLValue()) {
6154 auto NotLValueExpr = X->isLValue() ? V : X;
6155 ErrorFound = NotAnLValue;
6156 ErrorLoc = AtomicBinOp->getExprLoc();
6157 ErrorRange = AtomicBinOp->getSourceRange();
6158 NoteLoc = NotLValueExpr->getExprLoc();
6159 NoteRange = NotLValueExpr->getSourceRange();
6160 }
6161 } else if (!X->isInstantiationDependent() ||
6162 !V->isInstantiationDependent()) {
6163 auto NotScalarExpr =
6164 (X->isInstantiationDependent() || X->getType()->isScalarType())
6165 ? V
6166 : X;
6167 ErrorFound = NotAScalarType;
6168 ErrorLoc = AtomicBinOp->getExprLoc();
6169 ErrorRange = AtomicBinOp->getSourceRange();
6170 NoteLoc = NotScalarExpr->getExprLoc();
6171 NoteRange = NotScalarExpr->getSourceRange();
6172 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006173 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006174 ErrorFound = NotAnAssignmentOp;
6175 ErrorLoc = AtomicBody->getExprLoc();
6176 ErrorRange = AtomicBody->getSourceRange();
6177 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6178 : AtomicBody->getExprLoc();
6179 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6180 : AtomicBody->getSourceRange();
6181 }
6182 } else {
6183 ErrorFound = NotAnExpression;
6184 NoteLoc = ErrorLoc = Body->getLocStart();
6185 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006186 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006187 if (ErrorFound != NoError) {
6188 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6189 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006190 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6191 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006192 return StmtError();
6193 } else if (CurContext->isDependentContext())
6194 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006195 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006196 enum {
6197 NotAnExpression,
6198 NotAnAssignmentOp,
6199 NotAScalarType,
6200 NotAnLValue,
6201 NoError
6202 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006203 SourceLocation ErrorLoc, NoteLoc;
6204 SourceRange ErrorRange, NoteRange;
6205 // If clause is write:
6206 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00006207 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6208 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006209 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6210 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006211 X = AtomicBinOp->getLHS();
6212 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006213 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6214 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6215 if (!X->isLValue()) {
6216 ErrorFound = NotAnLValue;
6217 ErrorLoc = AtomicBinOp->getExprLoc();
6218 ErrorRange = AtomicBinOp->getSourceRange();
6219 NoteLoc = X->getExprLoc();
6220 NoteRange = X->getSourceRange();
6221 }
6222 } else if (!X->isInstantiationDependent() ||
6223 !E->isInstantiationDependent()) {
6224 auto NotScalarExpr =
6225 (X->isInstantiationDependent() || X->getType()->isScalarType())
6226 ? E
6227 : X;
6228 ErrorFound = NotAScalarType;
6229 ErrorLoc = AtomicBinOp->getExprLoc();
6230 ErrorRange = AtomicBinOp->getSourceRange();
6231 NoteLoc = NotScalarExpr->getExprLoc();
6232 NoteRange = NotScalarExpr->getSourceRange();
6233 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006234 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006235 ErrorFound = NotAnAssignmentOp;
6236 ErrorLoc = AtomicBody->getExprLoc();
6237 ErrorRange = AtomicBody->getSourceRange();
6238 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6239 : AtomicBody->getExprLoc();
6240 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6241 : AtomicBody->getSourceRange();
6242 }
6243 } else {
6244 ErrorFound = NotAnExpression;
6245 NoteLoc = ErrorLoc = Body->getLocStart();
6246 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006247 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006248 if (ErrorFound != NoError) {
6249 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6250 << ErrorRange;
6251 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6252 << NoteRange;
6253 return StmtError();
6254 } else if (CurContext->isDependentContext())
6255 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006256 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006257 // If clause is update:
6258 // x++;
6259 // x--;
6260 // ++x;
6261 // --x;
6262 // x binop= expr;
6263 // x = x binop expr;
6264 // x = expr binop x;
6265 OpenMPAtomicUpdateChecker Checker(*this);
6266 if (Checker.checkStatement(
6267 Body, (AtomicKind == OMPC_update)
6268 ? diag::err_omp_atomic_update_not_expression_statement
6269 : diag::err_omp_atomic_not_expression_statement,
6270 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006271 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006272 if (!CurContext->isDependentContext()) {
6273 E = Checker.getExpr();
6274 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006275 UE = Checker.getUpdateExpr();
6276 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006277 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006278 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006279 enum {
6280 NotAnAssignmentOp,
6281 NotACompoundStatement,
6282 NotTwoSubstatements,
6283 NotASpecificExpression,
6284 NoError
6285 } ErrorFound = NoError;
6286 SourceLocation ErrorLoc, NoteLoc;
6287 SourceRange ErrorRange, NoteRange;
6288 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6289 // If clause is a capture:
6290 // v = x++;
6291 // v = x--;
6292 // v = ++x;
6293 // v = --x;
6294 // v = x binop= expr;
6295 // v = x = x binop expr;
6296 // v = x = expr binop x;
6297 auto *AtomicBinOp =
6298 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6299 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6300 V = AtomicBinOp->getLHS();
6301 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6302 OpenMPAtomicUpdateChecker Checker(*this);
6303 if (Checker.checkStatement(
6304 Body, diag::err_omp_atomic_capture_not_expression_statement,
6305 diag::note_omp_atomic_update))
6306 return StmtError();
6307 E = Checker.getExpr();
6308 X = Checker.getX();
6309 UE = Checker.getUpdateExpr();
6310 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6311 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006312 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006313 ErrorLoc = AtomicBody->getExprLoc();
6314 ErrorRange = AtomicBody->getSourceRange();
6315 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6316 : AtomicBody->getExprLoc();
6317 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6318 : AtomicBody->getSourceRange();
6319 ErrorFound = NotAnAssignmentOp;
6320 }
6321 if (ErrorFound != NoError) {
6322 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6323 << ErrorRange;
6324 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6325 return StmtError();
6326 } else if (CurContext->isDependentContext()) {
6327 UE = V = E = X = nullptr;
6328 }
6329 } else {
6330 // If clause is a capture:
6331 // { v = x; x = expr; }
6332 // { v = x; x++; }
6333 // { v = x; x--; }
6334 // { v = x; ++x; }
6335 // { v = x; --x; }
6336 // { v = x; x binop= expr; }
6337 // { v = x; x = x binop expr; }
6338 // { v = x; x = expr binop x; }
6339 // { x++; v = x; }
6340 // { x--; v = x; }
6341 // { ++x; v = x; }
6342 // { --x; v = x; }
6343 // { x binop= expr; v = x; }
6344 // { x = x binop expr; v = x; }
6345 // { x = expr binop x; v = x; }
6346 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6347 // Check that this is { expr1; expr2; }
6348 if (CS->size() == 2) {
6349 auto *First = CS->body_front();
6350 auto *Second = CS->body_back();
6351 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6352 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6353 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6354 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6355 // Need to find what subexpression is 'v' and what is 'x'.
6356 OpenMPAtomicUpdateChecker Checker(*this);
6357 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6358 BinaryOperator *BinOp = nullptr;
6359 if (IsUpdateExprFound) {
6360 BinOp = dyn_cast<BinaryOperator>(First);
6361 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6362 }
6363 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6364 // { v = x; x++; }
6365 // { v = x; x--; }
6366 // { v = x; ++x; }
6367 // { v = x; --x; }
6368 // { v = x; x binop= expr; }
6369 // { v = x; x = x binop expr; }
6370 // { v = x; x = expr binop x; }
6371 // Check that the first expression has form v = x.
6372 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6373 llvm::FoldingSetNodeID XId, PossibleXId;
6374 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6375 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6376 IsUpdateExprFound = XId == PossibleXId;
6377 if (IsUpdateExprFound) {
6378 V = BinOp->getLHS();
6379 X = Checker.getX();
6380 E = Checker.getExpr();
6381 UE = Checker.getUpdateExpr();
6382 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006383 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006384 }
6385 }
6386 if (!IsUpdateExprFound) {
6387 IsUpdateExprFound = !Checker.checkStatement(First);
6388 BinOp = nullptr;
6389 if (IsUpdateExprFound) {
6390 BinOp = dyn_cast<BinaryOperator>(Second);
6391 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6392 }
6393 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6394 // { x++; v = x; }
6395 // { x--; v = x; }
6396 // { ++x; v = x; }
6397 // { --x; v = x; }
6398 // { x binop= expr; v = x; }
6399 // { x = x binop expr; v = x; }
6400 // { x = expr binop x; v = x; }
6401 // Check that the second expression has form v = x.
6402 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6403 llvm::FoldingSetNodeID XId, PossibleXId;
6404 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6405 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6406 IsUpdateExprFound = XId == PossibleXId;
6407 if (IsUpdateExprFound) {
6408 V = BinOp->getLHS();
6409 X = Checker.getX();
6410 E = Checker.getExpr();
6411 UE = Checker.getUpdateExpr();
6412 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006413 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006414 }
6415 }
6416 }
6417 if (!IsUpdateExprFound) {
6418 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006419 auto *FirstExpr = dyn_cast<Expr>(First);
6420 auto *SecondExpr = dyn_cast<Expr>(Second);
6421 if (!FirstExpr || !SecondExpr ||
6422 !(FirstExpr->isInstantiationDependent() ||
6423 SecondExpr->isInstantiationDependent())) {
6424 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6425 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006426 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006427 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6428 : First->getLocStart();
6429 NoteRange = ErrorRange = FirstBinOp
6430 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006431 : SourceRange(ErrorLoc, ErrorLoc);
6432 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006433 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6434 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6435 ErrorFound = NotAnAssignmentOp;
6436 NoteLoc = ErrorLoc = SecondBinOp
6437 ? SecondBinOp->getOperatorLoc()
6438 : Second->getLocStart();
6439 NoteRange = ErrorRange =
6440 SecondBinOp ? SecondBinOp->getSourceRange()
6441 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006442 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006443 auto *PossibleXRHSInFirst =
6444 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6445 auto *PossibleXLHSInSecond =
6446 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6447 llvm::FoldingSetNodeID X1Id, X2Id;
6448 PossibleXRHSInFirst->Profile(X1Id, Context,
6449 /*Canonical=*/true);
6450 PossibleXLHSInSecond->Profile(X2Id, Context,
6451 /*Canonical=*/true);
6452 IsUpdateExprFound = X1Id == X2Id;
6453 if (IsUpdateExprFound) {
6454 V = FirstBinOp->getLHS();
6455 X = SecondBinOp->getLHS();
6456 E = SecondBinOp->getRHS();
6457 UE = nullptr;
6458 IsXLHSInRHSPart = false;
6459 IsPostfixUpdate = true;
6460 } else {
6461 ErrorFound = NotASpecificExpression;
6462 ErrorLoc = FirstBinOp->getExprLoc();
6463 ErrorRange = FirstBinOp->getSourceRange();
6464 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6465 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6466 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006467 }
6468 }
6469 }
6470 }
6471 } else {
6472 NoteLoc = ErrorLoc = Body->getLocStart();
6473 NoteRange = ErrorRange =
6474 SourceRange(Body->getLocStart(), Body->getLocStart());
6475 ErrorFound = NotTwoSubstatements;
6476 }
6477 } else {
6478 NoteLoc = ErrorLoc = Body->getLocStart();
6479 NoteRange = ErrorRange =
6480 SourceRange(Body->getLocStart(), Body->getLocStart());
6481 ErrorFound = NotACompoundStatement;
6482 }
6483 if (ErrorFound != NoError) {
6484 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6485 << ErrorRange;
6486 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6487 return StmtError();
6488 } else if (CurContext->isDependentContext()) {
6489 UE = V = E = X = nullptr;
6490 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006491 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006492 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006493
Reid Kleckner87a31802018-03-12 21:43:02 +00006494 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00006495
Alexey Bataev62cec442014-11-18 10:14:22 +00006496 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006497 X, V, E, UE, IsXLHSInRHSPart,
6498 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006499}
6500
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006501StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6502 Stmt *AStmt,
6503 SourceLocation StartLoc,
6504 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006505 if (!AStmt)
6506 return StmtError();
6507
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006508 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6509 // 1.2.2 OpenMP Language Terminology
6510 // Structured block - An executable statement with a single entry at the
6511 // top and a single exit at the bottom.
6512 // The point of exit cannot be a branch out of the structured block.
6513 // longjmp() and throw() must not violate the entry/exit criteria.
6514 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006515 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6516 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6517 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6518 // 1.2.2 OpenMP Language Terminology
6519 // Structured block - An executable statement with a single entry at the
6520 // top and a single exit at the bottom.
6521 // The point of exit cannot be a branch out of the structured block.
6522 // longjmp() and throw() must not violate the entry/exit criteria.
6523 CS->getCapturedDecl()->setNothrow();
6524 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006525
Alexey Bataev13314bf2014-10-09 04:18:56 +00006526 // OpenMP [2.16, Nesting of Regions]
6527 // If specified, a teams construct must be contained within a target
6528 // construct. That target construct must contain no statements or directives
6529 // outside of the teams construct.
6530 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00006531 Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006532 bool OMPTeamsFound = true;
6533 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6534 auto I = CS->body_begin();
6535 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006536 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006537 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6538 OMPTeamsFound = false;
6539 break;
6540 }
6541 ++I;
6542 }
6543 assert(I != CS->body_end() && "Not found statement");
6544 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006545 } else {
6546 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6547 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006548 }
6549 if (!OMPTeamsFound) {
6550 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6551 Diag(DSAStack->getInnerTeamsRegionLoc(),
6552 diag::note_omp_nested_teams_construct_here);
6553 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6554 << isa<OMPExecutableDirective>(S);
6555 return StmtError();
6556 }
6557 }
6558
Reid Kleckner87a31802018-03-12 21:43:02 +00006559 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006560
6561 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6562}
6563
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006564StmtResult
6565Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6566 Stmt *AStmt, SourceLocation StartLoc,
6567 SourceLocation EndLoc) {
6568 if (!AStmt)
6569 return StmtError();
6570
6571 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6572 // 1.2.2 OpenMP Language Terminology
6573 // Structured block - An executable statement with a single entry at the
6574 // top and a single exit at the bottom.
6575 // The point of exit cannot be a branch out of the structured block.
6576 // longjmp() and throw() must not violate the entry/exit criteria.
6577 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006578 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6579 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6580 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6581 // 1.2.2 OpenMP Language Terminology
6582 // Structured block - An executable statement with a single entry at the
6583 // top and a single exit at the bottom.
6584 // The point of exit cannot be a branch out of the structured block.
6585 // longjmp() and throw() must not violate the entry/exit criteria.
6586 CS->getCapturedDecl()->setNothrow();
6587 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006588
Reid Kleckner87a31802018-03-12 21:43:02 +00006589 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006590
6591 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6592 AStmt);
6593}
6594
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006595StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6596 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6597 SourceLocation EndLoc,
6598 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6599 if (!AStmt)
6600 return StmtError();
6601
6602 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6603 // 1.2.2 OpenMP Language Terminology
6604 // Structured block - An executable statement with a single entry at the
6605 // top and a single exit at the bottom.
6606 // The point of exit cannot be a branch out of the structured block.
6607 // longjmp() and throw() must not violate the entry/exit criteria.
6608 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006609 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6610 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6611 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6612 // 1.2.2 OpenMP Language Terminology
6613 // Structured block - An executable statement with a single entry at the
6614 // top and a single exit at the bottom.
6615 // The point of exit cannot be a branch out of the structured block.
6616 // longjmp() and throw() must not violate the entry/exit criteria.
6617 CS->getCapturedDecl()->setNothrow();
6618 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006619
6620 OMPLoopDirective::HelperExprs B;
6621 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6622 // define the nested loops number.
6623 unsigned NestedLoopCount =
6624 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006625 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006626 VarsWithImplicitDSA, B);
6627 if (NestedLoopCount == 0)
6628 return StmtError();
6629
6630 assert((CurContext->isDependentContext() || B.builtAll()) &&
6631 "omp target parallel for loop exprs were not built");
6632
6633 if (!CurContext->isDependentContext()) {
6634 // Finalize the clauses that need pre-built expressions for CodeGen.
6635 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006636 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006637 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006638 B.NumIterations, *this, CurScope,
6639 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006640 return StmtError();
6641 }
6642 }
6643
Reid Kleckner87a31802018-03-12 21:43:02 +00006644 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006645 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6646 NestedLoopCount, Clauses, AStmt,
6647 B, DSAStack->isCancelRegion());
6648}
6649
Alexey Bataev95b64a92017-05-30 16:00:04 +00006650/// Check for existence of a map clause in the list of clauses.
6651static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6652 const OpenMPClauseKind K) {
6653 return llvm::any_of(
6654 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6655}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006656
Alexey Bataev95b64a92017-05-30 16:00:04 +00006657template <typename... Params>
6658static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6659 const Params... ClauseTypes) {
6660 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006661}
6662
Michael Wong65f367f2015-07-21 13:44:28 +00006663StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6664 Stmt *AStmt,
6665 SourceLocation StartLoc,
6666 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006667 if (!AStmt)
6668 return StmtError();
6669
6670 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6671
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006672 // OpenMP [2.10.1, Restrictions, p. 97]
6673 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006674 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6675 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6676 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006677 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006678 return StmtError();
6679 }
6680
Reid Kleckner87a31802018-03-12 21:43:02 +00006681 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00006682
6683 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6684 AStmt);
6685}
6686
Samuel Antaodf67fc42016-01-19 19:15:56 +00006687StmtResult
6688Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6689 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006690 SourceLocation EndLoc, Stmt *AStmt) {
6691 if (!AStmt)
6692 return StmtError();
6693
6694 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6695 // 1.2.2 OpenMP Language Terminology
6696 // Structured block - An executable statement with a single entry at the
6697 // top and a single exit at the bottom.
6698 // The point of exit cannot be a branch out of the structured block.
6699 // longjmp() and throw() must not violate the entry/exit criteria.
6700 CS->getCapturedDecl()->setNothrow();
6701 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6702 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6703 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6704 // 1.2.2 OpenMP Language Terminology
6705 // Structured block - An executable statement with a single entry at the
6706 // top and a single exit at the bottom.
6707 // The point of exit cannot be a branch out of the structured block.
6708 // longjmp() and throw() must not violate the entry/exit criteria.
6709 CS->getCapturedDecl()->setNothrow();
6710 }
6711
Samuel Antaodf67fc42016-01-19 19:15:56 +00006712 // OpenMP [2.10.2, Restrictions, p. 99]
6713 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006714 if (!hasClauses(Clauses, OMPC_map)) {
6715 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6716 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006717 return StmtError();
6718 }
6719
Alexey Bataev7828b252017-11-21 17:08:48 +00006720 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6721 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006722}
6723
Samuel Antao72590762016-01-19 20:04:50 +00006724StmtResult
6725Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6726 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006727 SourceLocation EndLoc, Stmt *AStmt) {
6728 if (!AStmt)
6729 return StmtError();
6730
6731 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6732 // 1.2.2 OpenMP Language Terminology
6733 // Structured block - An executable statement with a single entry at the
6734 // top and a single exit at the bottom.
6735 // The point of exit cannot be a branch out of the structured block.
6736 // longjmp() and throw() must not violate the entry/exit criteria.
6737 CS->getCapturedDecl()->setNothrow();
6738 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6739 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6740 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6741 // 1.2.2 OpenMP Language Terminology
6742 // Structured block - An executable statement with a single entry at the
6743 // top and a single exit at the bottom.
6744 // The point of exit cannot be a branch out of the structured block.
6745 // longjmp() and throw() must not violate the entry/exit criteria.
6746 CS->getCapturedDecl()->setNothrow();
6747 }
6748
Samuel Antao72590762016-01-19 20:04:50 +00006749 // OpenMP [2.10.3, Restrictions, p. 102]
6750 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006751 if (!hasClauses(Clauses, OMPC_map)) {
6752 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6753 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006754 return StmtError();
6755 }
6756
Alexey Bataev7828b252017-11-21 17:08:48 +00006757 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6758 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006759}
6760
Samuel Antao686c70c2016-05-26 17:30:50 +00006761StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6762 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006763 SourceLocation EndLoc,
6764 Stmt *AStmt) {
6765 if (!AStmt)
6766 return StmtError();
6767
6768 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6769 // 1.2.2 OpenMP Language Terminology
6770 // Structured block - An executable statement with a single entry at the
6771 // top and a single exit at the bottom.
6772 // The point of exit cannot be a branch out of the structured block.
6773 // longjmp() and throw() must not violate the entry/exit criteria.
6774 CS->getCapturedDecl()->setNothrow();
6775 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6776 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6777 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6778 // 1.2.2 OpenMP Language Terminology
6779 // Structured block - An executable statement with a single entry at the
6780 // top and a single exit at the bottom.
6781 // The point of exit cannot be a branch out of the structured block.
6782 // longjmp() and throw() must not violate the entry/exit criteria.
6783 CS->getCapturedDecl()->setNothrow();
6784 }
6785
Alexey Bataev95b64a92017-05-30 16:00:04 +00006786 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006787 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6788 return StmtError();
6789 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006790 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6791 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006792}
6793
Alexey Bataev13314bf2014-10-09 04:18:56 +00006794StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6795 Stmt *AStmt, SourceLocation StartLoc,
6796 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006797 if (!AStmt)
6798 return StmtError();
6799
Alexey Bataev13314bf2014-10-09 04:18:56 +00006800 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6801 // 1.2.2 OpenMP Language Terminology
6802 // Structured block - An executable statement with a single entry at the
6803 // top and a single exit at the bottom.
6804 // The point of exit cannot be a branch out of the structured block.
6805 // longjmp() and throw() must not violate the entry/exit criteria.
6806 CS->getCapturedDecl()->setNothrow();
6807
Reid Kleckner87a31802018-03-12 21:43:02 +00006808 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00006809
Alexey Bataevceabd412017-11-30 18:01:54 +00006810 DSAStack->setParentTeamsRegionLoc(StartLoc);
6811
Alexey Bataev13314bf2014-10-09 04:18:56 +00006812 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6813}
6814
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006815StmtResult
6816Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6817 SourceLocation EndLoc,
6818 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006819 if (DSAStack->isParentNowaitRegion()) {
6820 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6821 return StmtError();
6822 }
6823 if (DSAStack->isParentOrderedRegion()) {
6824 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6825 return StmtError();
6826 }
6827 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6828 CancelRegion);
6829}
6830
Alexey Bataev87933c72015-09-18 08:07:34 +00006831StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6832 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006833 SourceLocation EndLoc,
6834 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006835 if (DSAStack->isParentNowaitRegion()) {
6836 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6837 return StmtError();
6838 }
6839 if (DSAStack->isParentOrderedRegion()) {
6840 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6841 return StmtError();
6842 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006843 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006844 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6845 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006846}
6847
Alexey Bataev382967a2015-12-08 12:06:20 +00006848static bool checkGrainsizeNumTasksClauses(Sema &S,
6849 ArrayRef<OMPClause *> Clauses) {
6850 OMPClause *PrevClause = nullptr;
6851 bool ErrorFound = false;
6852 for (auto *C : Clauses) {
6853 if (C->getClauseKind() == OMPC_grainsize ||
6854 C->getClauseKind() == OMPC_num_tasks) {
6855 if (!PrevClause)
6856 PrevClause = C;
6857 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6858 S.Diag(C->getLocStart(),
6859 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6860 << getOpenMPClauseName(C->getClauseKind())
6861 << getOpenMPClauseName(PrevClause->getClauseKind());
6862 S.Diag(PrevClause->getLocStart(),
6863 diag::note_omp_previous_grainsize_num_tasks)
6864 << getOpenMPClauseName(PrevClause->getClauseKind());
6865 ErrorFound = true;
6866 }
6867 }
6868 }
6869 return ErrorFound;
6870}
6871
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006872static bool checkReductionClauseWithNogroup(Sema &S,
6873 ArrayRef<OMPClause *> Clauses) {
6874 OMPClause *ReductionClause = nullptr;
6875 OMPClause *NogroupClause = nullptr;
6876 for (auto *C : Clauses) {
6877 if (C->getClauseKind() == OMPC_reduction) {
6878 ReductionClause = C;
6879 if (NogroupClause)
6880 break;
6881 continue;
6882 }
6883 if (C->getClauseKind() == OMPC_nogroup) {
6884 NogroupClause = C;
6885 if (ReductionClause)
6886 break;
6887 continue;
6888 }
6889 }
6890 if (ReductionClause && NogroupClause) {
6891 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6892 << SourceRange(NogroupClause->getLocStart(),
6893 NogroupClause->getLocEnd());
6894 return true;
6895 }
6896 return false;
6897}
6898
Alexey Bataev49f6e782015-12-01 04:18:41 +00006899StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6900 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6901 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006902 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006903 if (!AStmt)
6904 return StmtError();
6905
6906 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6907 OMPLoopDirective::HelperExprs B;
6908 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6909 // define the nested loops number.
6910 unsigned NestedLoopCount =
6911 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006912 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006913 VarsWithImplicitDSA, B);
6914 if (NestedLoopCount == 0)
6915 return StmtError();
6916
6917 assert((CurContext->isDependentContext() || B.builtAll()) &&
6918 "omp for loop exprs were not built");
6919
Alexey Bataev382967a2015-12-08 12:06:20 +00006920 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6921 // The grainsize clause and num_tasks clause are mutually exclusive and may
6922 // not appear on the same taskloop directive.
6923 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6924 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006925 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6926 // If a reduction clause is present on the taskloop directive, the nogroup
6927 // clause must not be specified.
6928 if (checkReductionClauseWithNogroup(*this, Clauses))
6929 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006930
Reid Kleckner87a31802018-03-12 21:43:02 +00006931 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00006932 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6933 NestedLoopCount, Clauses, AStmt, B);
6934}
6935
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006936StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6937 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6938 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006939 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006940 if (!AStmt)
6941 return StmtError();
6942
6943 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6944 OMPLoopDirective::HelperExprs B;
6945 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6946 // define the nested loops number.
6947 unsigned NestedLoopCount =
6948 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6949 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6950 VarsWithImplicitDSA, B);
6951 if (NestedLoopCount == 0)
6952 return StmtError();
6953
6954 assert((CurContext->isDependentContext() || B.builtAll()) &&
6955 "omp for loop exprs were not built");
6956
Alexey Bataev5a3af132016-03-29 08:58:54 +00006957 if (!CurContext->isDependentContext()) {
6958 // Finalize the clauses that need pre-built expressions for CodeGen.
6959 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006960 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006961 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006962 B.NumIterations, *this, CurScope,
6963 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006964 return StmtError();
6965 }
6966 }
6967
Alexey Bataev382967a2015-12-08 12:06:20 +00006968 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6969 // The grainsize clause and num_tasks clause are mutually exclusive and may
6970 // not appear on the same taskloop directive.
6971 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6972 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006973 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6974 // If a reduction clause is present on the taskloop directive, the nogroup
6975 // clause must not be specified.
6976 if (checkReductionClauseWithNogroup(*this, Clauses))
6977 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006978 if (checkSimdlenSafelenSpecified(*this, Clauses))
6979 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006980
Reid Kleckner87a31802018-03-12 21:43:02 +00006981 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006982 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6983 NestedLoopCount, Clauses, AStmt, B);
6984}
6985
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006986StmtResult Sema::ActOnOpenMPDistributeDirective(
6987 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6988 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006989 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006990 if (!AStmt)
6991 return StmtError();
6992
6993 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6994 OMPLoopDirective::HelperExprs B;
6995 // In presence of clause 'collapse' with number of loops, it will
6996 // define the nested loops number.
6997 unsigned NestedLoopCount =
6998 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6999 nullptr /*ordered not a clause on distribute*/, AStmt,
7000 *this, *DSAStack, VarsWithImplicitDSA, B);
7001 if (NestedLoopCount == 0)
7002 return StmtError();
7003
7004 assert((CurContext->isDependentContext() || B.builtAll()) &&
7005 "omp for loop exprs were not built");
7006
Reid Kleckner87a31802018-03-12 21:43:02 +00007007 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007008 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7009 NestedLoopCount, Clauses, AStmt, B);
7010}
7011
Carlo Bertolli9925f152016-06-27 14:55:37 +00007012StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7014 SourceLocation EndLoc,
7015 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7016 if (!AStmt)
7017 return StmtError();
7018
7019 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7020 // 1.2.2 OpenMP Language Terminology
7021 // Structured block - An executable statement with a single entry at the
7022 // top and a single exit at the bottom.
7023 // The point of exit cannot be a branch out of the structured block.
7024 // longjmp() and throw() must not violate the entry/exit criteria.
7025 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007026 for (int ThisCaptureLevel =
7027 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7028 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7029 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7030 // 1.2.2 OpenMP Language Terminology
7031 // Structured block - An executable statement with a single entry at the
7032 // top and a single exit at the bottom.
7033 // The point of exit cannot be a branch out of the structured block.
7034 // longjmp() and throw() must not violate the entry/exit criteria.
7035 CS->getCapturedDecl()->setNothrow();
7036 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007037
7038 OMPLoopDirective::HelperExprs B;
7039 // In presence of clause 'collapse' with number of loops, it will
7040 // define the nested loops number.
7041 unsigned NestedLoopCount = CheckOpenMPLoop(
7042 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007043 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007044 VarsWithImplicitDSA, B);
7045 if (NestedLoopCount == 0)
7046 return StmtError();
7047
7048 assert((CurContext->isDependentContext() || B.builtAll()) &&
7049 "omp for loop exprs were not built");
7050
Reid Kleckner87a31802018-03-12 21:43:02 +00007051 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007052 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007053 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7054 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007055}
7056
Kelvin Li4a39add2016-07-05 05:00:15 +00007057StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7058 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7059 SourceLocation EndLoc,
7060 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7061 if (!AStmt)
7062 return StmtError();
7063
7064 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7065 // 1.2.2 OpenMP Language Terminology
7066 // Structured block - An executable statement with a single entry at the
7067 // top and a single exit at the bottom.
7068 // The point of exit cannot be a branch out of the structured block.
7069 // longjmp() and throw() must not violate the entry/exit criteria.
7070 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007071 for (int ThisCaptureLevel =
7072 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7073 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7074 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7075 // 1.2.2 OpenMP Language Terminology
7076 // Structured block - An executable statement with a single entry at the
7077 // top and a single exit at the bottom.
7078 // The point of exit cannot be a branch out of the structured block.
7079 // longjmp() and throw() must not violate the entry/exit criteria.
7080 CS->getCapturedDecl()->setNothrow();
7081 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007082
7083 OMPLoopDirective::HelperExprs B;
7084 // In presence of clause 'collapse' with number of loops, it will
7085 // define the nested loops number.
7086 unsigned NestedLoopCount = CheckOpenMPLoop(
7087 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007088 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007089 VarsWithImplicitDSA, B);
7090 if (NestedLoopCount == 0)
7091 return StmtError();
7092
7093 assert((CurContext->isDependentContext() || B.builtAll()) &&
7094 "omp for loop exprs were not built");
7095
Alexey Bataev438388c2017-11-22 18:34:02 +00007096 if (!CurContext->isDependentContext()) {
7097 // Finalize the clauses that need pre-built expressions for CodeGen.
7098 for (auto C : Clauses) {
7099 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7100 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7101 B.NumIterations, *this, CurScope,
7102 DSAStack))
7103 return StmtError();
7104 }
7105 }
7106
Kelvin Lic5609492016-07-15 04:39:07 +00007107 if (checkSimdlenSafelenSpecified(*this, Clauses))
7108 return StmtError();
7109
Reid Kleckner87a31802018-03-12 21:43:02 +00007110 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007111 return OMPDistributeParallelForSimdDirective::Create(
7112 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7113}
7114
Kelvin Li787f3fc2016-07-06 04:45:38 +00007115StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7116 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7117 SourceLocation EndLoc,
7118 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7119 if (!AStmt)
7120 return StmtError();
7121
7122 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7123 // 1.2.2 OpenMP Language Terminology
7124 // Structured block - An executable statement with a single entry at the
7125 // top and a single exit at the bottom.
7126 // The point of exit cannot be a branch out of the structured block.
7127 // longjmp() and throw() must not violate the entry/exit criteria.
7128 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007129 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7130 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7131 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7132 // 1.2.2 OpenMP Language Terminology
7133 // Structured block - An executable statement with a single entry at the
7134 // top and a single exit at the bottom.
7135 // The point of exit cannot be a branch out of the structured block.
7136 // longjmp() and throw() must not violate the entry/exit criteria.
7137 CS->getCapturedDecl()->setNothrow();
7138 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007139
7140 OMPLoopDirective::HelperExprs B;
7141 // In presence of clause 'collapse' with number of loops, it will
7142 // define the nested loops number.
7143 unsigned NestedLoopCount =
7144 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007145 nullptr /*ordered not a clause on distribute*/, CS, *this,
7146 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007147 if (NestedLoopCount == 0)
7148 return StmtError();
7149
7150 assert((CurContext->isDependentContext() || B.builtAll()) &&
7151 "omp for loop exprs were not built");
7152
Alexey Bataev438388c2017-11-22 18:34:02 +00007153 if (!CurContext->isDependentContext()) {
7154 // Finalize the clauses that need pre-built expressions for CodeGen.
7155 for (auto C : Clauses) {
7156 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7157 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7158 B.NumIterations, *this, CurScope,
7159 DSAStack))
7160 return StmtError();
7161 }
7162 }
7163
Kelvin Lic5609492016-07-15 04:39:07 +00007164 if (checkSimdlenSafelenSpecified(*this, Clauses))
7165 return StmtError();
7166
Reid Kleckner87a31802018-03-12 21:43:02 +00007167 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007168 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7169 NestedLoopCount, Clauses, AStmt, B);
7170}
7171
Kelvin Lia579b912016-07-14 02:54:56 +00007172StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7173 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7174 SourceLocation EndLoc,
7175 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7176 if (!AStmt)
7177 return StmtError();
7178
7179 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7180 // 1.2.2 OpenMP Language Terminology
7181 // Structured block - An executable statement with a single entry at the
7182 // top and a single exit at the bottom.
7183 // The point of exit cannot be a branch out of the structured block.
7184 // longjmp() and throw() must not violate the entry/exit criteria.
7185 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007186 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7187 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7188 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7189 // 1.2.2 OpenMP Language Terminology
7190 // Structured block - An executable statement with a single entry at the
7191 // top and a single exit at the bottom.
7192 // The point of exit cannot be a branch out of the structured block.
7193 // longjmp() and throw() must not violate the entry/exit criteria.
7194 CS->getCapturedDecl()->setNothrow();
7195 }
Kelvin Lia579b912016-07-14 02:54:56 +00007196
7197 OMPLoopDirective::HelperExprs B;
7198 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7199 // define the nested loops number.
7200 unsigned NestedLoopCount = CheckOpenMPLoop(
7201 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007202 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007203 VarsWithImplicitDSA, B);
7204 if (NestedLoopCount == 0)
7205 return StmtError();
7206
7207 assert((CurContext->isDependentContext() || B.builtAll()) &&
7208 "omp target parallel for simd loop exprs were not built");
7209
7210 if (!CurContext->isDependentContext()) {
7211 // Finalize the clauses that need pre-built expressions for CodeGen.
7212 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007213 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007214 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7215 B.NumIterations, *this, CurScope,
7216 DSAStack))
7217 return StmtError();
7218 }
7219 }
Kelvin Lic5609492016-07-15 04:39:07 +00007220 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007221 return StmtError();
7222
Reid Kleckner87a31802018-03-12 21:43:02 +00007223 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007224 return OMPTargetParallelForSimdDirective::Create(
7225 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7226}
7227
Kelvin Li986330c2016-07-20 22:57:10 +00007228StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7229 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7230 SourceLocation EndLoc,
7231 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7232 if (!AStmt)
7233 return StmtError();
7234
7235 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7236 // 1.2.2 OpenMP Language Terminology
7237 // Structured block - An executable statement with a single entry at the
7238 // top and a single exit at the bottom.
7239 // The point of exit cannot be a branch out of the structured block.
7240 // longjmp() and throw() must not violate the entry/exit criteria.
7241 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007242 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7243 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7244 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7245 // 1.2.2 OpenMP Language Terminology
7246 // Structured block - An executable statement with a single entry at the
7247 // top and a single exit at the bottom.
7248 // The point of exit cannot be a branch out of the structured block.
7249 // longjmp() and throw() must not violate the entry/exit criteria.
7250 CS->getCapturedDecl()->setNothrow();
7251 }
7252
Kelvin Li986330c2016-07-20 22:57:10 +00007253 OMPLoopDirective::HelperExprs B;
7254 // In presence of clause 'collapse' with number of loops, it will define the
7255 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007256 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007257 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007258 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007259 VarsWithImplicitDSA, B);
7260 if (NestedLoopCount == 0)
7261 return StmtError();
7262
7263 assert((CurContext->isDependentContext() || B.builtAll()) &&
7264 "omp target simd loop exprs were not built");
7265
7266 if (!CurContext->isDependentContext()) {
7267 // Finalize the clauses that need pre-built expressions for CodeGen.
7268 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007269 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007270 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7271 B.NumIterations, *this, CurScope,
7272 DSAStack))
7273 return StmtError();
7274 }
7275 }
7276
7277 if (checkSimdlenSafelenSpecified(*this, Clauses))
7278 return StmtError();
7279
Reid Kleckner87a31802018-03-12 21:43:02 +00007280 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007281 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7282 NestedLoopCount, Clauses, AStmt, B);
7283}
7284
Kelvin Li02532872016-08-05 14:37:37 +00007285StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7286 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7287 SourceLocation EndLoc,
7288 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7289 if (!AStmt)
7290 return StmtError();
7291
7292 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7293 // 1.2.2 OpenMP Language Terminology
7294 // Structured block - An executable statement with a single entry at the
7295 // top and a single exit at the bottom.
7296 // The point of exit cannot be a branch out of the structured block.
7297 // longjmp() and throw() must not violate the entry/exit criteria.
7298 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007299 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7300 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7301 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7302 // 1.2.2 OpenMP Language Terminology
7303 // Structured block - An executable statement with a single entry at the
7304 // top and a single exit at the bottom.
7305 // The point of exit cannot be a branch out of the structured block.
7306 // longjmp() and throw() must not violate the entry/exit criteria.
7307 CS->getCapturedDecl()->setNothrow();
7308 }
Kelvin Li02532872016-08-05 14:37:37 +00007309
7310 OMPLoopDirective::HelperExprs B;
7311 // In presence of clause 'collapse' with number of loops, it will
7312 // define the nested loops number.
7313 unsigned NestedLoopCount =
7314 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007315 nullptr /*ordered not a clause on distribute*/, CS, *this,
7316 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007317 if (NestedLoopCount == 0)
7318 return StmtError();
7319
7320 assert((CurContext->isDependentContext() || B.builtAll()) &&
7321 "omp teams distribute loop exprs were not built");
7322
Reid Kleckner87a31802018-03-12 21:43:02 +00007323 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007324
7325 DSAStack->setParentTeamsRegionLoc(StartLoc);
7326
David Majnemer9d168222016-08-05 17:44:54 +00007327 return OMPTeamsDistributeDirective::Create(
7328 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007329}
7330
Kelvin Li4e325f72016-10-25 12:50:55 +00007331StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7332 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7333 SourceLocation EndLoc,
7334 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7335 if (!AStmt)
7336 return StmtError();
7337
7338 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7339 // 1.2.2 OpenMP Language Terminology
7340 // Structured block - An executable statement with a single entry at the
7341 // top and a single exit at the bottom.
7342 // The point of exit cannot be a branch out of the structured block.
7343 // longjmp() and throw() must not violate the entry/exit criteria.
7344 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007345 for (int ThisCaptureLevel =
7346 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7347 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7348 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7349 // 1.2.2 OpenMP Language Terminology
7350 // Structured block - An executable statement with a single entry at the
7351 // top and a single exit at the bottom.
7352 // The point of exit cannot be a branch out of the structured block.
7353 // longjmp() and throw() must not violate the entry/exit criteria.
7354 CS->getCapturedDecl()->setNothrow();
7355 }
7356
Kelvin Li4e325f72016-10-25 12:50:55 +00007357
7358 OMPLoopDirective::HelperExprs B;
7359 // In presence of clause 'collapse' with number of loops, it will
7360 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007361 unsigned NestedLoopCount = CheckOpenMPLoop(
7362 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007363 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007364 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007365
7366 if (NestedLoopCount == 0)
7367 return StmtError();
7368
7369 assert((CurContext->isDependentContext() || B.builtAll()) &&
7370 "omp teams distribute simd loop exprs were not built");
7371
7372 if (!CurContext->isDependentContext()) {
7373 // Finalize the clauses that need pre-built expressions for CodeGen.
7374 for (auto C : Clauses) {
7375 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7376 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7377 B.NumIterations, *this, CurScope,
7378 DSAStack))
7379 return StmtError();
7380 }
7381 }
7382
7383 if (checkSimdlenSafelenSpecified(*this, Clauses))
7384 return StmtError();
7385
Reid Kleckner87a31802018-03-12 21:43:02 +00007386 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007387
7388 DSAStack->setParentTeamsRegionLoc(StartLoc);
7389
Kelvin Li4e325f72016-10-25 12:50:55 +00007390 return OMPTeamsDistributeSimdDirective::Create(
7391 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7392}
7393
Kelvin Li579e41c2016-11-30 23:51:03 +00007394StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7395 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7396 SourceLocation EndLoc,
7397 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7398 if (!AStmt)
7399 return StmtError();
7400
7401 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7402 // 1.2.2 OpenMP Language Terminology
7403 // Structured block - An executable statement with a single entry at the
7404 // top and a single exit at the bottom.
7405 // The point of exit cannot be a branch out of the structured block.
7406 // longjmp() and throw() must not violate the entry/exit criteria.
7407 CS->getCapturedDecl()->setNothrow();
7408
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007409 for (int ThisCaptureLevel =
7410 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7411 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7412 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7413 // 1.2.2 OpenMP Language Terminology
7414 // Structured block - An executable statement with a single entry at the
7415 // top and a single exit at the bottom.
7416 // The point of exit cannot be a branch out of the structured block.
7417 // longjmp() and throw() must not violate the entry/exit criteria.
7418 CS->getCapturedDecl()->setNothrow();
7419 }
7420
Kelvin Li579e41c2016-11-30 23:51:03 +00007421 OMPLoopDirective::HelperExprs B;
7422 // In presence of clause 'collapse' with number of loops, it will
7423 // define the nested loops number.
7424 auto NestedLoopCount = CheckOpenMPLoop(
7425 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007426 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007427 VarsWithImplicitDSA, B);
7428
7429 if (NestedLoopCount == 0)
7430 return StmtError();
7431
7432 assert((CurContext->isDependentContext() || B.builtAll()) &&
7433 "omp for loop exprs were not built");
7434
7435 if (!CurContext->isDependentContext()) {
7436 // Finalize the clauses that need pre-built expressions for CodeGen.
7437 for (auto C : Clauses) {
7438 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7439 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7440 B.NumIterations, *this, CurScope,
7441 DSAStack))
7442 return StmtError();
7443 }
7444 }
7445
7446 if (checkSimdlenSafelenSpecified(*this, Clauses))
7447 return StmtError();
7448
Reid Kleckner87a31802018-03-12 21:43:02 +00007449 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007450
7451 DSAStack->setParentTeamsRegionLoc(StartLoc);
7452
Kelvin Li579e41c2016-11-30 23:51:03 +00007453 return OMPTeamsDistributeParallelForSimdDirective::Create(
7454 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7455}
7456
Kelvin Li7ade93f2016-12-09 03:24:30 +00007457StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7458 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7459 SourceLocation EndLoc,
7460 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7461 if (!AStmt)
7462 return StmtError();
7463
7464 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7465 // 1.2.2 OpenMP Language Terminology
7466 // Structured block - An executable statement with a single entry at the
7467 // top and a single exit at the bottom.
7468 // The point of exit cannot be a branch out of the structured block.
7469 // longjmp() and throw() must not violate the entry/exit criteria.
7470 CS->getCapturedDecl()->setNothrow();
7471
Carlo Bertolli62fae152017-11-20 20:46:39 +00007472 for (int ThisCaptureLevel =
7473 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7474 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7475 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7476 // 1.2.2 OpenMP Language Terminology
7477 // Structured block - An executable statement with a single entry at the
7478 // top and a single exit at the bottom.
7479 // The point of exit cannot be a branch out of the structured block.
7480 // longjmp() and throw() must not violate the entry/exit criteria.
7481 CS->getCapturedDecl()->setNothrow();
7482 }
7483
Kelvin Li7ade93f2016-12-09 03:24:30 +00007484 OMPLoopDirective::HelperExprs B;
7485 // In presence of clause 'collapse' with number of loops, it will
7486 // define the nested loops number.
7487 unsigned NestedLoopCount = CheckOpenMPLoop(
7488 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007489 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007490 VarsWithImplicitDSA, B);
7491
7492 if (NestedLoopCount == 0)
7493 return StmtError();
7494
7495 assert((CurContext->isDependentContext() || B.builtAll()) &&
7496 "omp for loop exprs were not built");
7497
Reid Kleckner87a31802018-03-12 21:43:02 +00007498 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007499
7500 DSAStack->setParentTeamsRegionLoc(StartLoc);
7501
Kelvin Li7ade93f2016-12-09 03:24:30 +00007502 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007503 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7504 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007505}
7506
Kelvin Libf594a52016-12-17 05:48:59 +00007507StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7508 Stmt *AStmt,
7509 SourceLocation StartLoc,
7510 SourceLocation EndLoc) {
7511 if (!AStmt)
7512 return StmtError();
7513
7514 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7515 // 1.2.2 OpenMP Language Terminology
7516 // Structured block - An executable statement with a single entry at the
7517 // top and a single exit at the bottom.
7518 // The point of exit cannot be a branch out of the structured block.
7519 // longjmp() and throw() must not violate the entry/exit criteria.
7520 CS->getCapturedDecl()->setNothrow();
7521
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007522 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7523 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7524 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7525 // 1.2.2 OpenMP Language Terminology
7526 // Structured block - An executable statement with a single entry at the
7527 // top and a single exit at the bottom.
7528 // The point of exit cannot be a branch out of the structured block.
7529 // longjmp() and throw() must not violate the entry/exit criteria.
7530 CS->getCapturedDecl()->setNothrow();
7531 }
Reid Kleckner87a31802018-03-12 21:43:02 +00007532 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00007533
7534 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7535 AStmt);
7536}
7537
Kelvin Li83c451e2016-12-25 04:52:54 +00007538StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7539 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7540 SourceLocation EndLoc,
7541 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7542 if (!AStmt)
7543 return StmtError();
7544
7545 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7546 // 1.2.2 OpenMP Language Terminology
7547 // Structured block - An executable statement with a single entry at the
7548 // top and a single exit at the bottom.
7549 // The point of exit cannot be a branch out of the structured block.
7550 // longjmp() and throw() must not violate the entry/exit criteria.
7551 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007552 for (int ThisCaptureLevel =
7553 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7554 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7555 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7556 // 1.2.2 OpenMP Language Terminology
7557 // Structured block - An executable statement with a single entry at the
7558 // top and a single exit at the bottom.
7559 // The point of exit cannot be a branch out of the structured block.
7560 // longjmp() and throw() must not violate the entry/exit criteria.
7561 CS->getCapturedDecl()->setNothrow();
7562 }
Kelvin Li83c451e2016-12-25 04:52:54 +00007563
7564 OMPLoopDirective::HelperExprs B;
7565 // In presence of clause 'collapse' with number of loops, it will
7566 // define the nested loops number.
7567 auto NestedLoopCount = CheckOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007568 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7569 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00007570 VarsWithImplicitDSA, B);
7571 if (NestedLoopCount == 0)
7572 return StmtError();
7573
7574 assert((CurContext->isDependentContext() || B.builtAll()) &&
7575 "omp target teams distribute loop exprs were not built");
7576
Reid Kleckner87a31802018-03-12 21:43:02 +00007577 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00007578 return OMPTargetTeamsDistributeDirective::Create(
7579 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7580}
7581
Kelvin Li80e8f562016-12-29 22:16:30 +00007582StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7583 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7584 SourceLocation EndLoc,
7585 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7586 if (!AStmt)
7587 return StmtError();
7588
7589 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7590 // 1.2.2 OpenMP Language Terminology
7591 // Structured block - An executable statement with a single entry at the
7592 // top and a single exit at the bottom.
7593 // The point of exit cannot be a branch out of the structured block.
7594 // longjmp() and throw() must not violate the entry/exit criteria.
7595 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00007596 for (int ThisCaptureLevel =
7597 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7598 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7599 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7600 // 1.2.2 OpenMP Language Terminology
7601 // Structured block - An executable statement with a single entry at the
7602 // top and a single exit at the bottom.
7603 // The point of exit cannot be a branch out of the structured block.
7604 // longjmp() and throw() must not violate the entry/exit criteria.
7605 CS->getCapturedDecl()->setNothrow();
7606 }
7607
Kelvin Li80e8f562016-12-29 22:16:30 +00007608 OMPLoopDirective::HelperExprs B;
7609 // In presence of clause 'collapse' with number of loops, it will
7610 // define the nested loops number.
7611 auto NestedLoopCount = CheckOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00007612 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7613 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00007614 VarsWithImplicitDSA, B);
7615 if (NestedLoopCount == 0)
7616 return StmtError();
7617
7618 assert((CurContext->isDependentContext() || B.builtAll()) &&
7619 "omp target teams distribute parallel for loop exprs were not built");
7620
Alexey Bataev647dd842018-01-15 20:59:40 +00007621 if (!CurContext->isDependentContext()) {
7622 // Finalize the clauses that need pre-built expressions for CodeGen.
7623 for (auto C : Clauses) {
7624 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7625 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7626 B.NumIterations, *this, CurScope,
7627 DSAStack))
7628 return StmtError();
7629 }
7630 }
7631
Reid Kleckner87a31802018-03-12 21:43:02 +00007632 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00007633 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007634 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7635 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007636}
7637
Kelvin Li1851df52017-01-03 05:23:48 +00007638StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7640 SourceLocation EndLoc,
7641 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7642 if (!AStmt)
7643 return StmtError();
7644
7645 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7646 // 1.2.2 OpenMP Language Terminology
7647 // Structured block - An executable statement with a single entry at the
7648 // top and a single exit at the bottom.
7649 // The point of exit cannot be a branch out of the structured block.
7650 // longjmp() and throw() must not violate the entry/exit criteria.
7651 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00007652 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7653 OMPD_target_teams_distribute_parallel_for_simd);
7654 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7655 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7656 // 1.2.2 OpenMP Language Terminology
7657 // Structured block - An executable statement with a single entry at the
7658 // top and a single exit at the bottom.
7659 // The point of exit cannot be a branch out of the structured block.
7660 // longjmp() and throw() must not violate the entry/exit criteria.
7661 CS->getCapturedDecl()->setNothrow();
7662 }
Kelvin Li1851df52017-01-03 05:23:48 +00007663
7664 OMPLoopDirective::HelperExprs B;
7665 // In presence of clause 'collapse' with number of loops, it will
7666 // define the nested loops number.
Alexey Bataev647dd842018-01-15 20:59:40 +00007667 auto NestedLoopCount =
7668 CheckOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7669 getCollapseNumberExpr(Clauses),
7670 nullptr /*ordered not a clause on distribute*/, CS, *this,
7671 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00007672 if (NestedLoopCount == 0)
7673 return StmtError();
7674
7675 assert((CurContext->isDependentContext() || B.builtAll()) &&
7676 "omp target teams distribute parallel for simd loop exprs were not "
7677 "built");
7678
7679 if (!CurContext->isDependentContext()) {
7680 // Finalize the clauses that need pre-built expressions for CodeGen.
7681 for (auto C : Clauses) {
7682 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7683 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7684 B.NumIterations, *this, CurScope,
7685 DSAStack))
7686 return StmtError();
7687 }
7688 }
7689
Alexey Bataev438388c2017-11-22 18:34:02 +00007690 if (checkSimdlenSafelenSpecified(*this, Clauses))
7691 return StmtError();
7692
Reid Kleckner87a31802018-03-12 21:43:02 +00007693 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00007694 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7695 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7696}
7697
Kelvin Lida681182017-01-10 18:08:18 +00007698StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7699 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7700 SourceLocation EndLoc,
7701 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7702 if (!AStmt)
7703 return StmtError();
7704
7705 auto *CS = cast<CapturedStmt>(AStmt);
7706 // 1.2.2 OpenMP Language Terminology
7707 // Structured block - An executable statement with a single entry at the
7708 // top and a single exit at the bottom.
7709 // The point of exit cannot be a branch out of the structured block.
7710 // longjmp() and throw() must not violate the entry/exit criteria.
7711 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007712 for (int ThisCaptureLevel =
7713 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7714 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7715 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7716 // 1.2.2 OpenMP Language Terminology
7717 // Structured block - An executable statement with a single entry at the
7718 // top and a single exit at the bottom.
7719 // The point of exit cannot be a branch out of the structured block.
7720 // longjmp() and throw() must not violate the entry/exit criteria.
7721 CS->getCapturedDecl()->setNothrow();
7722 }
Kelvin Lida681182017-01-10 18:08:18 +00007723
7724 OMPLoopDirective::HelperExprs B;
7725 // In presence of clause 'collapse' with number of loops, it will
7726 // define the nested loops number.
7727 auto NestedLoopCount = CheckOpenMPLoop(
7728 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007729 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00007730 VarsWithImplicitDSA, B);
7731 if (NestedLoopCount == 0)
7732 return StmtError();
7733
7734 assert((CurContext->isDependentContext() || B.builtAll()) &&
7735 "omp target teams distribute simd loop exprs were not built");
7736
Alexey Bataev438388c2017-11-22 18:34:02 +00007737 if (!CurContext->isDependentContext()) {
7738 // Finalize the clauses that need pre-built expressions for CodeGen.
7739 for (auto C : Clauses) {
7740 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7741 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7742 B.NumIterations, *this, CurScope,
7743 DSAStack))
7744 return StmtError();
7745 }
7746 }
7747
7748 if (checkSimdlenSafelenSpecified(*this, Clauses))
7749 return StmtError();
7750
Reid Kleckner87a31802018-03-12 21:43:02 +00007751 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00007752 return OMPTargetTeamsDistributeSimdDirective::Create(
7753 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7754}
7755
Alexey Bataeved09d242014-05-28 05:53:51 +00007756OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007757 SourceLocation StartLoc,
7758 SourceLocation LParenLoc,
7759 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007760 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007761 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007762 case OMPC_final:
7763 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7764 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007765 case OMPC_num_threads:
7766 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7767 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007768 case OMPC_safelen:
7769 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7770 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007771 case OMPC_simdlen:
7772 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7773 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007774 case OMPC_collapse:
7775 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7776 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007777 case OMPC_ordered:
7778 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7779 break;
Michael Wonge710d542015-08-07 16:16:36 +00007780 case OMPC_device:
7781 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7782 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007783 case OMPC_num_teams:
7784 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7785 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007786 case OMPC_thread_limit:
7787 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7788 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007789 case OMPC_priority:
7790 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7791 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007792 case OMPC_grainsize:
7793 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7794 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007795 case OMPC_num_tasks:
7796 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7797 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007798 case OMPC_hint:
7799 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7800 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007801 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007802 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007803 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007804 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007805 case OMPC_private:
7806 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007807 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007808 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007809 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007810 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007811 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007812 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007813 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007814 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007815 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007816 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007817 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007818 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007819 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007820 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007821 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007822 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007823 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007824 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007825 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007826 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007827 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007828 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007829 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007830 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007831 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007832 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007833 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007834 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007835 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007836 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007837 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007838 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007839 llvm_unreachable("Clause is not allowed.");
7840 }
7841 return Res;
7842}
7843
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007844// An OpenMP directive such as 'target parallel' has two captured regions:
7845// for the 'target' and 'parallel' respectively. This function returns
7846// the region in which to capture expressions associated with a clause.
7847// A return value of OMPD_unknown signifies that the expression should not
7848// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007849static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7850 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7851 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007852 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007853 switch (CKind) {
7854 case OMPC_if:
7855 switch (DKind) {
7856 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007857 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007858 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007859 // If this clause applies to the nested 'parallel' region, capture within
7860 // the 'target' region, otherwise do not capture.
7861 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7862 CaptureRegion = OMPD_target;
7863 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007864 case OMPD_target_teams_distribute_parallel_for:
7865 case OMPD_target_teams_distribute_parallel_for_simd:
7866 // If this clause applies to the nested 'parallel' region, capture within
7867 // the 'teams' region, otherwise do not capture.
7868 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7869 CaptureRegion = OMPD_teams;
7870 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007871 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007872 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007873 CaptureRegion = OMPD_teams;
7874 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007875 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00007876 case OMPD_target_enter_data:
7877 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007878 CaptureRegion = OMPD_task;
7879 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007880 case OMPD_cancel:
7881 case OMPD_parallel:
7882 case OMPD_parallel_sections:
7883 case OMPD_parallel_for:
7884 case OMPD_parallel_for_simd:
7885 case OMPD_target:
7886 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007887 case OMPD_target_teams:
7888 case OMPD_target_teams_distribute:
7889 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007890 case OMPD_distribute_parallel_for:
7891 case OMPD_distribute_parallel_for_simd:
7892 case OMPD_task:
7893 case OMPD_taskloop:
7894 case OMPD_taskloop_simd:
7895 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007896 // Do not capture if-clause expressions.
7897 break;
7898 case OMPD_threadprivate:
7899 case OMPD_taskyield:
7900 case OMPD_barrier:
7901 case OMPD_taskwait:
7902 case OMPD_cancellation_point:
7903 case OMPD_flush:
7904 case OMPD_declare_reduction:
7905 case OMPD_declare_simd:
7906 case OMPD_declare_target:
7907 case OMPD_end_declare_target:
7908 case OMPD_teams:
7909 case OMPD_simd:
7910 case OMPD_for:
7911 case OMPD_for_simd:
7912 case OMPD_sections:
7913 case OMPD_section:
7914 case OMPD_single:
7915 case OMPD_master:
7916 case OMPD_critical:
7917 case OMPD_taskgroup:
7918 case OMPD_distribute:
7919 case OMPD_ordered:
7920 case OMPD_atomic:
7921 case OMPD_distribute_simd:
7922 case OMPD_teams_distribute:
7923 case OMPD_teams_distribute_simd:
7924 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7925 case OMPD_unknown:
7926 llvm_unreachable("Unknown OpenMP directive");
7927 }
7928 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007929 case OMPC_num_threads:
7930 switch (DKind) {
7931 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007932 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007933 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007934 CaptureRegion = OMPD_target;
7935 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007936 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007937 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00007938 case OMPD_target_teams_distribute_parallel_for:
7939 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007940 CaptureRegion = OMPD_teams;
7941 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007942 case OMPD_parallel:
7943 case OMPD_parallel_sections:
7944 case OMPD_parallel_for:
7945 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007946 case OMPD_distribute_parallel_for:
7947 case OMPD_distribute_parallel_for_simd:
7948 // Do not capture num_threads-clause expressions.
7949 break;
7950 case OMPD_target_data:
7951 case OMPD_target_enter_data:
7952 case OMPD_target_exit_data:
7953 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007954 case OMPD_target:
7955 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007956 case OMPD_target_teams:
7957 case OMPD_target_teams_distribute:
7958 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007959 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007960 case OMPD_task:
7961 case OMPD_taskloop:
7962 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007963 case OMPD_threadprivate:
7964 case OMPD_taskyield:
7965 case OMPD_barrier:
7966 case OMPD_taskwait:
7967 case OMPD_cancellation_point:
7968 case OMPD_flush:
7969 case OMPD_declare_reduction:
7970 case OMPD_declare_simd:
7971 case OMPD_declare_target:
7972 case OMPD_end_declare_target:
7973 case OMPD_teams:
7974 case OMPD_simd:
7975 case OMPD_for:
7976 case OMPD_for_simd:
7977 case OMPD_sections:
7978 case OMPD_section:
7979 case OMPD_single:
7980 case OMPD_master:
7981 case OMPD_critical:
7982 case OMPD_taskgroup:
7983 case OMPD_distribute:
7984 case OMPD_ordered:
7985 case OMPD_atomic:
7986 case OMPD_distribute_simd:
7987 case OMPD_teams_distribute:
7988 case OMPD_teams_distribute_simd:
7989 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7990 case OMPD_unknown:
7991 llvm_unreachable("Unknown OpenMP directive");
7992 }
7993 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007994 case OMPC_num_teams:
7995 switch (DKind) {
7996 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007997 case OMPD_target_teams_distribute:
7998 case OMPD_target_teams_distribute_simd:
7999 case OMPD_target_teams_distribute_parallel_for:
8000 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008001 CaptureRegion = OMPD_target;
8002 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008003 case OMPD_teams_distribute_parallel_for:
8004 case OMPD_teams_distribute_parallel_for_simd:
8005 case OMPD_teams:
8006 case OMPD_teams_distribute:
8007 case OMPD_teams_distribute_simd:
8008 // Do not capture num_teams-clause expressions.
8009 break;
8010 case OMPD_distribute_parallel_for:
8011 case OMPD_distribute_parallel_for_simd:
8012 case OMPD_task:
8013 case OMPD_taskloop:
8014 case OMPD_taskloop_simd:
8015 case OMPD_target_data:
8016 case OMPD_target_enter_data:
8017 case OMPD_target_exit_data:
8018 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008019 case OMPD_cancel:
8020 case OMPD_parallel:
8021 case OMPD_parallel_sections:
8022 case OMPD_parallel_for:
8023 case OMPD_parallel_for_simd:
8024 case OMPD_target:
8025 case OMPD_target_simd:
8026 case OMPD_target_parallel:
8027 case OMPD_target_parallel_for:
8028 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008029 case OMPD_threadprivate:
8030 case OMPD_taskyield:
8031 case OMPD_barrier:
8032 case OMPD_taskwait:
8033 case OMPD_cancellation_point:
8034 case OMPD_flush:
8035 case OMPD_declare_reduction:
8036 case OMPD_declare_simd:
8037 case OMPD_declare_target:
8038 case OMPD_end_declare_target:
8039 case OMPD_simd:
8040 case OMPD_for:
8041 case OMPD_for_simd:
8042 case OMPD_sections:
8043 case OMPD_section:
8044 case OMPD_single:
8045 case OMPD_master:
8046 case OMPD_critical:
8047 case OMPD_taskgroup:
8048 case OMPD_distribute:
8049 case OMPD_ordered:
8050 case OMPD_atomic:
8051 case OMPD_distribute_simd:
8052 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8053 case OMPD_unknown:
8054 llvm_unreachable("Unknown OpenMP directive");
8055 }
8056 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008057 case OMPC_thread_limit:
8058 switch (DKind) {
8059 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008060 case OMPD_target_teams_distribute:
8061 case OMPD_target_teams_distribute_simd:
8062 case OMPD_target_teams_distribute_parallel_for:
8063 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008064 CaptureRegion = OMPD_target;
8065 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008066 case OMPD_teams_distribute_parallel_for:
8067 case OMPD_teams_distribute_parallel_for_simd:
8068 case OMPD_teams:
8069 case OMPD_teams_distribute:
8070 case OMPD_teams_distribute_simd:
8071 // Do not capture thread_limit-clause expressions.
8072 break;
8073 case OMPD_distribute_parallel_for:
8074 case OMPD_distribute_parallel_for_simd:
8075 case OMPD_task:
8076 case OMPD_taskloop:
8077 case OMPD_taskloop_simd:
8078 case OMPD_target_data:
8079 case OMPD_target_enter_data:
8080 case OMPD_target_exit_data:
8081 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008082 case OMPD_cancel:
8083 case OMPD_parallel:
8084 case OMPD_parallel_sections:
8085 case OMPD_parallel_for:
8086 case OMPD_parallel_for_simd:
8087 case OMPD_target:
8088 case OMPD_target_simd:
8089 case OMPD_target_parallel:
8090 case OMPD_target_parallel_for:
8091 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008092 case OMPD_threadprivate:
8093 case OMPD_taskyield:
8094 case OMPD_barrier:
8095 case OMPD_taskwait:
8096 case OMPD_cancellation_point:
8097 case OMPD_flush:
8098 case OMPD_declare_reduction:
8099 case OMPD_declare_simd:
8100 case OMPD_declare_target:
8101 case OMPD_end_declare_target:
8102 case OMPD_simd:
8103 case OMPD_for:
8104 case OMPD_for_simd:
8105 case OMPD_sections:
8106 case OMPD_section:
8107 case OMPD_single:
8108 case OMPD_master:
8109 case OMPD_critical:
8110 case OMPD_taskgroup:
8111 case OMPD_distribute:
8112 case OMPD_ordered:
8113 case OMPD_atomic:
8114 case OMPD_distribute_simd:
8115 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8116 case OMPD_unknown:
8117 llvm_unreachable("Unknown OpenMP directive");
8118 }
8119 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008120 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008121 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008122 case OMPD_parallel_for:
8123 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008124 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008125 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008126 case OMPD_teams_distribute_parallel_for:
8127 case OMPD_teams_distribute_parallel_for_simd:
8128 case OMPD_target_parallel_for:
8129 case OMPD_target_parallel_for_simd:
8130 case OMPD_target_teams_distribute_parallel_for:
8131 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008132 CaptureRegion = OMPD_parallel;
8133 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008134 case OMPD_for:
8135 case OMPD_for_simd:
8136 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008137 break;
8138 case OMPD_task:
8139 case OMPD_taskloop:
8140 case OMPD_taskloop_simd:
8141 case OMPD_target_data:
8142 case OMPD_target_enter_data:
8143 case OMPD_target_exit_data:
8144 case OMPD_target_update:
8145 case OMPD_teams:
8146 case OMPD_teams_distribute:
8147 case OMPD_teams_distribute_simd:
8148 case OMPD_target_teams_distribute:
8149 case OMPD_target_teams_distribute_simd:
8150 case OMPD_target:
8151 case OMPD_target_simd:
8152 case OMPD_target_parallel:
8153 case OMPD_cancel:
8154 case OMPD_parallel:
8155 case OMPD_parallel_sections:
8156 case OMPD_threadprivate:
8157 case OMPD_taskyield:
8158 case OMPD_barrier:
8159 case OMPD_taskwait:
8160 case OMPD_cancellation_point:
8161 case OMPD_flush:
8162 case OMPD_declare_reduction:
8163 case OMPD_declare_simd:
8164 case OMPD_declare_target:
8165 case OMPD_end_declare_target:
8166 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008167 case OMPD_sections:
8168 case OMPD_section:
8169 case OMPD_single:
8170 case OMPD_master:
8171 case OMPD_critical:
8172 case OMPD_taskgroup:
8173 case OMPD_distribute:
8174 case OMPD_ordered:
8175 case OMPD_atomic:
8176 case OMPD_distribute_simd:
8177 case OMPD_target_teams:
8178 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8179 case OMPD_unknown:
8180 llvm_unreachable("Unknown OpenMP directive");
8181 }
8182 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008183 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008184 switch (DKind) {
8185 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008186 case OMPD_teams_distribute_parallel_for_simd:
8187 case OMPD_teams_distribute:
8188 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008189 case OMPD_target_teams_distribute_parallel_for:
8190 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008191 case OMPD_target_teams_distribute:
8192 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008193 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008194 break;
8195 case OMPD_distribute_parallel_for:
8196 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008197 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008198 case OMPD_distribute_simd:
8199 // Do not capture thread_limit-clause expressions.
8200 break;
8201 case OMPD_parallel_for:
8202 case OMPD_parallel_for_simd:
8203 case OMPD_target_parallel_for_simd:
8204 case OMPD_target_parallel_for:
8205 case OMPD_task:
8206 case OMPD_taskloop:
8207 case OMPD_taskloop_simd:
8208 case OMPD_target_data:
8209 case OMPD_target_enter_data:
8210 case OMPD_target_exit_data:
8211 case OMPD_target_update:
8212 case OMPD_teams:
8213 case OMPD_target:
8214 case OMPD_target_simd:
8215 case OMPD_target_parallel:
8216 case OMPD_cancel:
8217 case OMPD_parallel:
8218 case OMPD_parallel_sections:
8219 case OMPD_threadprivate:
8220 case OMPD_taskyield:
8221 case OMPD_barrier:
8222 case OMPD_taskwait:
8223 case OMPD_cancellation_point:
8224 case OMPD_flush:
8225 case OMPD_declare_reduction:
8226 case OMPD_declare_simd:
8227 case OMPD_declare_target:
8228 case OMPD_end_declare_target:
8229 case OMPD_simd:
8230 case OMPD_for:
8231 case OMPD_for_simd:
8232 case OMPD_sections:
8233 case OMPD_section:
8234 case OMPD_single:
8235 case OMPD_master:
8236 case OMPD_critical:
8237 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008238 case OMPD_ordered:
8239 case OMPD_atomic:
8240 case OMPD_target_teams:
8241 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8242 case OMPD_unknown:
8243 llvm_unreachable("Unknown OpenMP directive");
8244 }
8245 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008246 case OMPC_device:
8247 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008248 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008249 case OMPD_target_enter_data:
8250 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008251 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008252 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008253 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008254 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008255 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008256 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008257 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008258 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008259 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008260 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008261 CaptureRegion = OMPD_task;
8262 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008263 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008264 // Do not capture device-clause expressions.
8265 break;
8266 case OMPD_teams_distribute_parallel_for:
8267 case OMPD_teams_distribute_parallel_for_simd:
8268 case OMPD_teams:
8269 case OMPD_teams_distribute:
8270 case OMPD_teams_distribute_simd:
8271 case OMPD_distribute_parallel_for:
8272 case OMPD_distribute_parallel_for_simd:
8273 case OMPD_task:
8274 case OMPD_taskloop:
8275 case OMPD_taskloop_simd:
8276 case OMPD_cancel:
8277 case OMPD_parallel:
8278 case OMPD_parallel_sections:
8279 case OMPD_parallel_for:
8280 case OMPD_parallel_for_simd:
8281 case OMPD_threadprivate:
8282 case OMPD_taskyield:
8283 case OMPD_barrier:
8284 case OMPD_taskwait:
8285 case OMPD_cancellation_point:
8286 case OMPD_flush:
8287 case OMPD_declare_reduction:
8288 case OMPD_declare_simd:
8289 case OMPD_declare_target:
8290 case OMPD_end_declare_target:
8291 case OMPD_simd:
8292 case OMPD_for:
8293 case OMPD_for_simd:
8294 case OMPD_sections:
8295 case OMPD_section:
8296 case OMPD_single:
8297 case OMPD_master:
8298 case OMPD_critical:
8299 case OMPD_taskgroup:
8300 case OMPD_distribute:
8301 case OMPD_ordered:
8302 case OMPD_atomic:
8303 case OMPD_distribute_simd:
8304 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8305 case OMPD_unknown:
8306 llvm_unreachable("Unknown OpenMP directive");
8307 }
8308 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008309 case OMPC_firstprivate:
8310 case OMPC_lastprivate:
8311 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008312 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008313 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008314 case OMPC_linear:
8315 case OMPC_default:
8316 case OMPC_proc_bind:
8317 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008318 case OMPC_safelen:
8319 case OMPC_simdlen:
8320 case OMPC_collapse:
8321 case OMPC_private:
8322 case OMPC_shared:
8323 case OMPC_aligned:
8324 case OMPC_copyin:
8325 case OMPC_copyprivate:
8326 case OMPC_ordered:
8327 case OMPC_nowait:
8328 case OMPC_untied:
8329 case OMPC_mergeable:
8330 case OMPC_threadprivate:
8331 case OMPC_flush:
8332 case OMPC_read:
8333 case OMPC_write:
8334 case OMPC_update:
8335 case OMPC_capture:
8336 case OMPC_seq_cst:
8337 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008338 case OMPC_threads:
8339 case OMPC_simd:
8340 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008341 case OMPC_priority:
8342 case OMPC_grainsize:
8343 case OMPC_nogroup:
8344 case OMPC_num_tasks:
8345 case OMPC_hint:
8346 case OMPC_defaultmap:
8347 case OMPC_unknown:
8348 case OMPC_uniform:
8349 case OMPC_to:
8350 case OMPC_from:
8351 case OMPC_use_device_ptr:
8352 case OMPC_is_device_ptr:
8353 llvm_unreachable("Unexpected OpenMP clause.");
8354 }
8355 return CaptureRegion;
8356}
8357
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008358OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8359 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008360 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008361 SourceLocation NameModifierLoc,
8362 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008363 SourceLocation EndLoc) {
8364 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008365 Stmt *HelperValStmt = nullptr;
8366 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008367 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8368 !Condition->isInstantiationDependent() &&
8369 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008370 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008371 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008372 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008373
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008374 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008375
8376 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8377 CaptureRegion =
8378 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008379 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008380 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008381 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8382 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8383 HelperValStmt = buildPreInits(Context, Captures);
8384 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008385 }
8386
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008387 return new (Context)
8388 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8389 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008390}
8391
Alexey Bataev3778b602014-07-17 07:32:53 +00008392OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8393 SourceLocation StartLoc,
8394 SourceLocation LParenLoc,
8395 SourceLocation EndLoc) {
8396 Expr *ValExpr = Condition;
8397 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8398 !Condition->isInstantiationDependent() &&
8399 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008400 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008401 if (Val.isInvalid())
8402 return nullptr;
8403
Richard Smith03a4aa32016-06-23 19:02:52 +00008404 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008405 }
8406
8407 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8408}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008409ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8410 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008411 if (!Op)
8412 return ExprError();
8413
8414 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8415 public:
8416 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008417 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008418 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8419 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008420 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8421 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008422 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8423 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008424 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8425 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008426 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8427 QualType T,
8428 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008429 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8430 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008431 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8432 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008433 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008434 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008435 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008436 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8437 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008438 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8439 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008440 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8441 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008442 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008443 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008444 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008445 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8446 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008447 llvm_unreachable("conversion functions are permitted");
8448 }
8449 } ConvertDiagnoser;
8450 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8451}
8452
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008453static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008454 OpenMPClauseKind CKind,
8455 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008456 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8457 !ValExpr->isInstantiationDependent()) {
8458 SourceLocation Loc = ValExpr->getExprLoc();
8459 ExprResult Value =
8460 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8461 if (Value.isInvalid())
8462 return false;
8463
8464 ValExpr = Value.get();
8465 // The expression must evaluate to a non-negative integer value.
8466 llvm::APSInt Result;
8467 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008468 Result.isSigned() &&
8469 !((!StrictlyPositive && Result.isNonNegative()) ||
8470 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008471 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008472 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8473 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008474 return false;
8475 }
8476 }
8477 return true;
8478}
8479
Alexey Bataev568a8332014-03-06 06:15:19 +00008480OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8481 SourceLocation StartLoc,
8482 SourceLocation LParenLoc,
8483 SourceLocation EndLoc) {
8484 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008485 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008486
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008487 // OpenMP [2.5, Restrictions]
8488 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008489 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8490 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008491 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008492
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008493 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008494 OpenMPDirectiveKind CaptureRegion =
8495 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8496 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008497 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008498 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8499 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8500 HelperValStmt = buildPreInits(Context, Captures);
8501 }
8502
8503 return new (Context) OMPNumThreadsClause(
8504 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008505}
8506
Alexey Bataev62c87d22014-03-21 04:51:18 +00008507ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008508 OpenMPClauseKind CKind,
8509 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008510 if (!E)
8511 return ExprError();
8512 if (E->isValueDependent() || E->isTypeDependent() ||
8513 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008514 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008515 llvm::APSInt Result;
8516 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8517 if (ICE.isInvalid())
8518 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008519 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8520 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008521 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008522 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8523 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008524 return ExprError();
8525 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008526 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8527 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8528 << E->getSourceRange();
8529 return ExprError();
8530 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008531 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8532 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008533 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008534 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008535 return ICE;
8536}
8537
8538OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8539 SourceLocation LParenLoc,
8540 SourceLocation EndLoc) {
8541 // OpenMP [2.8.1, simd construct, Description]
8542 // The parameter of the safelen clause must be a constant
8543 // positive integer expression.
8544 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8545 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008546 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008547 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008548 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008549}
8550
Alexey Bataev66b15b52015-08-21 11:14:16 +00008551OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8552 SourceLocation LParenLoc,
8553 SourceLocation EndLoc) {
8554 // OpenMP [2.8.1, simd construct, Description]
8555 // The parameter of the simdlen clause must be a constant
8556 // positive integer expression.
8557 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8558 if (Simdlen.isInvalid())
8559 return nullptr;
8560 return new (Context)
8561 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8562}
8563
Alexander Musman64d33f12014-06-04 07:53:32 +00008564OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8565 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008566 SourceLocation LParenLoc,
8567 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008568 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008569 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008570 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008571 // The parameter of the collapse clause must be a constant
8572 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008573 ExprResult NumForLoopsResult =
8574 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8575 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008576 return nullptr;
8577 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008578 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008579}
8580
Alexey Bataev10e775f2015-07-30 11:36:16 +00008581OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8582 SourceLocation EndLoc,
8583 SourceLocation LParenLoc,
8584 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008585 // OpenMP [2.7.1, loop construct, Description]
8586 // OpenMP [2.8.1, simd construct, Description]
8587 // OpenMP [2.9.6, distribute construct, Description]
8588 // The parameter of the ordered clause must be a constant
8589 // positive integer expression if any.
8590 if (NumForLoops && LParenLoc.isValid()) {
8591 ExprResult NumForLoopsResult =
8592 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8593 if (NumForLoopsResult.isInvalid())
8594 return nullptr;
8595 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008596 } else
8597 NumForLoops = nullptr;
8598 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008599 return new (Context)
8600 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8601}
8602
Alexey Bataeved09d242014-05-28 05:53:51 +00008603OMPClause *Sema::ActOnOpenMPSimpleClause(
8604 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8605 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008606 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008607 switch (Kind) {
8608 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008609 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008610 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8611 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008612 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008613 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008614 Res = ActOnOpenMPProcBindClause(
8615 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8616 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008617 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008618 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008619 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008620 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008621 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008622 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008623 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008624 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008625 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008626 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008627 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008628 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008629 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008630 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008631 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008632 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008633 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008634 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008635 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008636 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008637 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008638 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008639 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008640 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008641 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008642 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008643 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008644 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008645 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008646 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008647 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008648 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008649 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008650 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008651 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008652 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008653 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008654 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008655 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008656 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008657 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008658 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008659 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008660 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008661 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008662 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008663 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008664 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008665 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008666 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008667 llvm_unreachable("Clause is not allowed.");
8668 }
8669 return Res;
8670}
8671
Alexey Bataev6402bca2015-12-28 07:25:51 +00008672static std::string
8673getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8674 ArrayRef<unsigned> Exclude = llvm::None) {
8675 std::string Values;
8676 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8677 unsigned Skipped = Exclude.size();
8678 auto S = Exclude.begin(), E = Exclude.end();
8679 for (unsigned i = First; i < Last; ++i) {
8680 if (std::find(S, E, i) != E) {
8681 --Skipped;
8682 continue;
8683 }
8684 Values += "'";
8685 Values += getOpenMPSimpleClauseTypeName(K, i);
8686 Values += "'";
8687 if (i == Bound - Skipped)
8688 Values += " or ";
8689 else if (i != Bound + 1 - Skipped)
8690 Values += ", ";
8691 }
8692 return Values;
8693}
8694
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008695OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8696 SourceLocation KindKwLoc,
8697 SourceLocation StartLoc,
8698 SourceLocation LParenLoc,
8699 SourceLocation EndLoc) {
8700 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008701 static_assert(OMPC_DEFAULT_unknown > 0,
8702 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008703 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008704 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8705 /*Last=*/OMPC_DEFAULT_unknown)
8706 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008707 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008708 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008709 switch (Kind) {
8710 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008711 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008712 break;
8713 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008714 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008715 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008716 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008717 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008718 break;
8719 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008720 return new (Context)
8721 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008722}
8723
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008724OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8725 SourceLocation KindKwLoc,
8726 SourceLocation StartLoc,
8727 SourceLocation LParenLoc,
8728 SourceLocation EndLoc) {
8729 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008730 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008731 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8732 /*Last=*/OMPC_PROC_BIND_unknown)
8733 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008734 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008735 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008736 return new (Context)
8737 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008738}
8739
Alexey Bataev56dafe82014-06-20 07:16:17 +00008740OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008741 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008742 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008743 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008744 SourceLocation EndLoc) {
8745 OMPClause *Res = nullptr;
8746 switch (Kind) {
8747 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008748 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8749 assert(Argument.size() == NumberOfElements &&
8750 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008751 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008752 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8753 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8754 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8755 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8756 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008757 break;
8758 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008759 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8760 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8761 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8762 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008763 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008764 case OMPC_dist_schedule:
8765 Res = ActOnOpenMPDistScheduleClause(
8766 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8767 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8768 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008769 case OMPC_defaultmap:
8770 enum { Modifier, DefaultmapKind };
8771 Res = ActOnOpenMPDefaultmapClause(
8772 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8773 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008774 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8775 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008776 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008777 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008778 case OMPC_num_threads:
8779 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008780 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008781 case OMPC_collapse:
8782 case OMPC_default:
8783 case OMPC_proc_bind:
8784 case OMPC_private:
8785 case OMPC_firstprivate:
8786 case OMPC_lastprivate:
8787 case OMPC_shared:
8788 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008789 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008790 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008791 case OMPC_linear:
8792 case OMPC_aligned:
8793 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008794 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008795 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008796 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008797 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008798 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008799 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008800 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008801 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008802 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008803 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008804 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008805 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008806 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008807 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008808 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008809 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008810 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008811 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008812 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008813 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008814 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008815 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008816 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008817 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008818 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008819 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008820 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008821 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008822 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008823 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008824 llvm_unreachable("Clause is not allowed.");
8825 }
8826 return Res;
8827}
8828
Alexey Bataev6402bca2015-12-28 07:25:51 +00008829static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8830 OpenMPScheduleClauseModifier M2,
8831 SourceLocation M1Loc, SourceLocation M2Loc) {
8832 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8833 SmallVector<unsigned, 2> Excluded;
8834 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8835 Excluded.push_back(M2);
8836 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8837 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8838 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8839 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8840 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8841 << getListOfPossibleValues(OMPC_schedule,
8842 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8843 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8844 Excluded)
8845 << getOpenMPClauseName(OMPC_schedule);
8846 return true;
8847 }
8848 return false;
8849}
8850
Alexey Bataev56dafe82014-06-20 07:16:17 +00008851OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008852 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008853 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008854 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8855 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8856 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8857 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8858 return nullptr;
8859 // OpenMP, 2.7.1, Loop Construct, Restrictions
8860 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8861 // but not both.
8862 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8863 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8864 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8865 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8866 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8867 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8868 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8869 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8870 return nullptr;
8871 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008872 if (Kind == OMPC_SCHEDULE_unknown) {
8873 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008874 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8875 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8876 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8877 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8878 Exclude);
8879 } else {
8880 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8881 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008882 }
8883 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8884 << Values << getOpenMPClauseName(OMPC_schedule);
8885 return nullptr;
8886 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008887 // OpenMP, 2.7.1, Loop Construct, Restrictions
8888 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8889 // schedule(guided).
8890 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8891 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8892 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8893 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8894 diag::err_omp_schedule_nonmonotonic_static);
8895 return nullptr;
8896 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008897 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008898 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008899 if (ChunkSize) {
8900 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8901 !ChunkSize->isInstantiationDependent() &&
8902 !ChunkSize->containsUnexpandedParameterPack()) {
8903 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8904 ExprResult Val =
8905 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8906 if (Val.isInvalid())
8907 return nullptr;
8908
8909 ValExpr = Val.get();
8910
8911 // OpenMP [2.7.1, Restrictions]
8912 // chunk_size must be a loop invariant integer expression with a positive
8913 // value.
8914 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008915 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8916 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8917 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008918 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008919 return nullptr;
8920 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008921 } else if (getOpenMPCaptureRegionForClause(
8922 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8923 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008924 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008925 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008926 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8927 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8928 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008929 }
8930 }
8931 }
8932
Alexey Bataev6402bca2015-12-28 07:25:51 +00008933 return new (Context)
8934 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008935 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008936}
8937
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008938OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8939 SourceLocation StartLoc,
8940 SourceLocation EndLoc) {
8941 OMPClause *Res = nullptr;
8942 switch (Kind) {
8943 case OMPC_ordered:
8944 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8945 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008946 case OMPC_nowait:
8947 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8948 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008949 case OMPC_untied:
8950 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8951 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008952 case OMPC_mergeable:
8953 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8954 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008955 case OMPC_read:
8956 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8957 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008958 case OMPC_write:
8959 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8960 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008961 case OMPC_update:
8962 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8963 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008964 case OMPC_capture:
8965 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8966 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008967 case OMPC_seq_cst:
8968 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8969 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008970 case OMPC_threads:
8971 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8972 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008973 case OMPC_simd:
8974 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8975 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008976 case OMPC_nogroup:
8977 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8978 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008979 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008980 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008981 case OMPC_num_threads:
8982 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008983 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008984 case OMPC_collapse:
8985 case OMPC_schedule:
8986 case OMPC_private:
8987 case OMPC_firstprivate:
8988 case OMPC_lastprivate:
8989 case OMPC_shared:
8990 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008991 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008992 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008993 case OMPC_linear:
8994 case OMPC_aligned:
8995 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008996 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008997 case OMPC_default:
8998 case OMPC_proc_bind:
8999 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009000 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009001 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009002 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009003 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009004 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009005 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009006 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009007 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009008 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009009 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009010 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009011 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009012 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009013 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009014 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009015 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009016 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009017 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009018 llvm_unreachable("Clause is not allowed.");
9019 }
9020 return Res;
9021}
9022
Alexey Bataev236070f2014-06-20 11:19:47 +00009023OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9024 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009025 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009026 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9027}
9028
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009029OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9030 SourceLocation EndLoc) {
9031 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9032}
9033
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009034OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9035 SourceLocation EndLoc) {
9036 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9037}
9038
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009039OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9040 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009041 return new (Context) OMPReadClause(StartLoc, EndLoc);
9042}
9043
Alexey Bataevdea47612014-07-23 07:46:59 +00009044OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9045 SourceLocation EndLoc) {
9046 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9047}
9048
Alexey Bataev67a4f222014-07-23 10:25:33 +00009049OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9050 SourceLocation EndLoc) {
9051 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9052}
9053
Alexey Bataev459dec02014-07-24 06:46:57 +00009054OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9055 SourceLocation EndLoc) {
9056 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9057}
9058
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009059OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9060 SourceLocation EndLoc) {
9061 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9062}
9063
Alexey Bataev346265e2015-09-25 10:37:12 +00009064OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9065 SourceLocation EndLoc) {
9066 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9067}
9068
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009069OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9070 SourceLocation EndLoc) {
9071 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9072}
9073
Alexey Bataevb825de12015-12-07 10:51:44 +00009074OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9075 SourceLocation EndLoc) {
9076 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9077}
9078
Alexey Bataevc5e02582014-06-16 07:08:35 +00009079OMPClause *Sema::ActOnOpenMPVarListClause(
9080 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9081 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9082 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009083 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00009084 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9085 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9086 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009087 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009088 switch (Kind) {
9089 case OMPC_private:
9090 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9091 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009092 case OMPC_firstprivate:
9093 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9094 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009095 case OMPC_lastprivate:
9096 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9097 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009098 case OMPC_shared:
9099 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9100 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009101 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009102 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9103 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009104 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009105 case OMPC_task_reduction:
9106 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9107 EndLoc, ReductionIdScopeSpec,
9108 ReductionId);
9109 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009110 case OMPC_in_reduction:
9111 Res =
9112 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9113 EndLoc, ReductionIdScopeSpec, ReductionId);
9114 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009115 case OMPC_linear:
9116 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009117 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009118 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009119 case OMPC_aligned:
9120 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9121 ColonLoc, EndLoc);
9122 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009123 case OMPC_copyin:
9124 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9125 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009126 case OMPC_copyprivate:
9127 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9128 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009129 case OMPC_flush:
9130 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9131 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009132 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009133 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009134 StartLoc, LParenLoc, EndLoc);
9135 break;
9136 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00009137 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9138 DepLinMapLoc, ColonLoc, VarList, StartLoc,
9139 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009140 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009141 case OMPC_to:
9142 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9143 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009144 case OMPC_from:
9145 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9146 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009147 case OMPC_use_device_ptr:
9148 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9149 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009150 case OMPC_is_device_ptr:
9151 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9152 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009153 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009154 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009155 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009156 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009157 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009158 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009159 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009160 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009161 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009162 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009163 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009164 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009165 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009166 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009167 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009168 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009169 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009170 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009171 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009172 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009173 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009174 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009175 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009176 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009177 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009178 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009179 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009180 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009181 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009182 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009183 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009184 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009185 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009186 llvm_unreachable("Clause is not allowed.");
9187 }
9188 return Res;
9189}
9190
Alexey Bataev90c228f2016-02-08 09:29:13 +00009191ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009192 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009193 ExprResult Res = BuildDeclRefExpr(
9194 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9195 if (!Res.isUsable())
9196 return ExprError();
9197 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9198 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9199 if (!Res.isUsable())
9200 return ExprError();
9201 }
9202 if (VK != VK_LValue && Res.get()->isGLValue()) {
9203 Res = DefaultLvalueConversion(Res.get());
9204 if (!Res.isUsable())
9205 return ExprError();
9206 }
9207 return Res;
9208}
9209
Alexey Bataev60da77e2016-02-29 05:54:20 +00009210static std::pair<ValueDecl *, bool>
9211getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9212 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009213 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9214 RefExpr->containsUnexpandedParameterPack())
9215 return std::make_pair(nullptr, true);
9216
Alexey Bataevd985eda2016-02-10 11:29:16 +00009217 // OpenMP [3.1, C/C++]
9218 // A list item is a variable name.
9219 // OpenMP [2.9.3.3, Restrictions, p.1]
9220 // A variable that is part of another variable (as an array or
9221 // structure element) cannot appear in a private clause.
9222 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009223 enum {
9224 NoArrayExpr = -1,
9225 ArraySubscript = 0,
9226 OMPArraySection = 1
9227 } IsArrayExpr = NoArrayExpr;
9228 if (AllowArraySection) {
9229 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9230 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
9231 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9232 Base = TempASE->getBase()->IgnoreParenImpCasts();
9233 RefExpr = Base;
9234 IsArrayExpr = ArraySubscript;
9235 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9236 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
9237 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9238 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9239 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9240 Base = TempASE->getBase()->IgnoreParenImpCasts();
9241 RefExpr = Base;
9242 IsArrayExpr = OMPArraySection;
9243 }
9244 }
9245 ELoc = RefExpr->getExprLoc();
9246 ERange = RefExpr->getSourceRange();
9247 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009248 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9249 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9250 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9251 (S.getCurrentThisType().isNull() || !ME ||
9252 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9253 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009254 if (IsArrayExpr != NoArrayExpr)
9255 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9256 << ERange;
9257 else {
9258 S.Diag(ELoc,
9259 AllowArraySection
9260 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9261 : diag::err_omp_expected_var_name_member_expr)
9262 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9263 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009264 return std::make_pair(nullptr, false);
9265 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009266 return std::make_pair(
9267 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009268}
9269
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009270OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9271 SourceLocation StartLoc,
9272 SourceLocation LParenLoc,
9273 SourceLocation EndLoc) {
9274 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009275 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00009276 for (auto &RefExpr : VarList) {
9277 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009278 SourceLocation ELoc;
9279 SourceRange ERange;
9280 Expr *SimpleRefExpr = RefExpr;
9281 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009282 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009283 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009284 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009285 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009286 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009287 ValueDecl *D = Res.first;
9288 if (!D)
9289 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009290
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009291 QualType Type = D->getType();
9292 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009293
9294 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9295 // A variable that appears in a private clause must not have an incomplete
9296 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009297 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009298 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009299 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009300
Alexey Bataev758e55e2013-09-06 18:03:48 +00009301 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9302 // in a Construct]
9303 // Variables with the predetermined data-sharing attributes may not be
9304 // listed in data-sharing attributes clauses, except for the cases
9305 // listed below. For these exceptions only, listing a predetermined
9306 // variable in a data-sharing attribute clause is allowed and overrides
9307 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009308 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009309 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009310 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9311 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009312 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009313 continue;
9314 }
9315
Kelvin Libf594a52016-12-17 05:48:59 +00009316 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009317 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009318 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009319 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009320 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9321 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009322 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009323 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009324 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009325 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009326 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009327 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009328 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009329 continue;
9330 }
9331
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009332 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9333 // A list item cannot appear in both a map clause and a data-sharing
9334 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009335 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Alexey Bataev647dd842018-01-15 20:59:40 +00009336 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009337 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009338 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009339 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009340 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009341 CurrDir == OMPD_target_parallel_for_simd ||
9342 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009343 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009344 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009345 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009346 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9347 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9348 ConflictKind = WhereFoundClauseKind;
9349 return true;
9350 })) {
9351 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009352 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009353 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009354 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009355 ReportOriginalDSA(*this, DSAStack, D, DVar);
9356 continue;
9357 }
9358 }
9359
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009360 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9361 // A variable of class type (or array thereof) that appears in a private
9362 // clause requires an accessible, unambiguous default constructor for the
9363 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009364 // Generate helper private variable and initialize it with the default
9365 // value. The address of the original variable is replaced by the address of
9366 // the new private variable in CodeGen. This new variable is not added to
9367 // IdResolver, so the code in the OpenMP region uses original variable for
9368 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009369 Type = Type.getUnqualifiedType();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00009370 auto VDPrivate =
9371 buildVarDecl(*this, ELoc, Type, D->getName(),
9372 D->hasAttrs() ? &D->getAttrs() : nullptr,
9373 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009374 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009375 if (VDPrivate->isInvalidDecl())
9376 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009377 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009378 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009379
Alexey Bataev90c228f2016-02-08 09:29:13 +00009380 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009381 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009382 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009383 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009384 Vars.push_back((VD || CurContext->isDependentContext())
9385 ? RefExpr->IgnoreParens()
9386 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009387 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009388 }
9389
Alexey Bataeved09d242014-05-28 05:53:51 +00009390 if (Vars.empty())
9391 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009392
Alexey Bataev03b340a2014-10-21 03:16:40 +00009393 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9394 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009395}
9396
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009397namespace {
9398class DiagsUninitializedSeveretyRAII {
9399private:
9400 DiagnosticsEngine &Diags;
9401 SourceLocation SavedLoc;
9402 bool IsIgnored;
9403
9404public:
9405 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9406 bool IsIgnored)
9407 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9408 if (!IsIgnored) {
9409 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9410 /*Map*/ diag::Severity::Ignored, Loc);
9411 }
9412 }
9413 ~DiagsUninitializedSeveretyRAII() {
9414 if (!IsIgnored)
9415 Diags.popMappings(SavedLoc);
9416 }
9417};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009418}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009419
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009420OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9421 SourceLocation StartLoc,
9422 SourceLocation LParenLoc,
9423 SourceLocation EndLoc) {
9424 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009425 SmallVector<Expr *, 8> PrivateCopies;
9426 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009427 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009428 bool IsImplicitClause =
9429 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9430 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9431
Alexey Bataeved09d242014-05-28 05:53:51 +00009432 for (auto &RefExpr : VarList) {
9433 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009434 SourceLocation ELoc;
9435 SourceRange ERange;
9436 Expr *SimpleRefExpr = RefExpr;
9437 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009438 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009439 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009440 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009441 PrivateCopies.push_back(nullptr);
9442 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009443 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009444 ValueDecl *D = Res.first;
9445 if (!D)
9446 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009447
Alexey Bataev60da77e2016-02-29 05:54:20 +00009448 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009449 QualType Type = D->getType();
9450 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009451
9452 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9453 // A variable that appears in a private clause must not have an incomplete
9454 // type or a reference type.
9455 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009456 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009457 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009458 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009459
9460 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9461 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009462 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009463 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009464 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009465
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009466 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009467 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009468 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009469 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009470 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009471 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009472 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009473 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9474 // A list item that specifies a given variable may not appear in more
9475 // than one clause on the same directive, except that a variable may be
9476 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009477 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9478 // A list item may appear in a firstprivate or lastprivate clause but not
9479 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009480 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009481 (isOpenMPDistributeDirective(CurrDir) ||
9482 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009483 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009484 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009485 << getOpenMPClauseName(DVar.CKind)
9486 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009487 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009488 continue;
9489 }
9490
9491 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9492 // in a Construct]
9493 // Variables with the predetermined data-sharing attributes may not be
9494 // listed in data-sharing attributes clauses, except for the cases
9495 // listed below. For these exceptions only, listing a predetermined
9496 // variable in a data-sharing attribute clause is allowed and overrides
9497 // the variable's predetermined data-sharing attributes.
9498 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9499 // in a Construct, C/C++, p.2]
9500 // Variables with const-qualified type having no mutable member may be
9501 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009502 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009503 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9504 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009505 << getOpenMPClauseName(DVar.CKind)
9506 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009507 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009508 continue;
9509 }
9510
9511 // OpenMP [2.9.3.4, Restrictions, p.2]
9512 // A list item that is private within a parallel region must not appear
9513 // in a firstprivate clause on a worksharing construct if any of the
9514 // worksharing regions arising from the worksharing construct ever bind
9515 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009516 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9517 // A list item that is private within a teams region must not appear in a
9518 // firstprivate clause on a distribute construct if any of the distribute
9519 // regions arising from the distribute construct ever bind to any of the
9520 // teams regions arising from the teams construct.
9521 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9522 // A list item that appears in a reduction clause of a teams construct
9523 // must not appear in a firstprivate clause on a distribute construct if
9524 // any of the distribute regions arising from the distribute construct
9525 // ever bind to any of the teams regions arising from the teams construct.
9526 if ((isOpenMPWorksharingDirective(CurrDir) ||
9527 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009528 !isOpenMPParallelDirective(CurrDir) &&
9529 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009530 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009531 if (DVar.CKind != OMPC_shared &&
9532 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009533 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009534 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009535 Diag(ELoc, diag::err_omp_required_access)
9536 << getOpenMPClauseName(OMPC_firstprivate)
9537 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009538 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009539 continue;
9540 }
9541 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009542 // OpenMP [2.9.3.4, Restrictions, p.3]
9543 // A list item that appears in a reduction clause of a parallel construct
9544 // must not appear in a firstprivate clause on a worksharing or task
9545 // construct if any of the worksharing or task regions arising from the
9546 // worksharing or task construct ever bind to any of the parallel regions
9547 // arising from the parallel construct.
9548 // OpenMP [2.9.3.4, Restrictions, p.4]
9549 // A list item that appears in a reduction clause in worksharing
9550 // construct must not appear in a firstprivate clause in a task construct
9551 // encountered during execution of any of the worksharing regions arising
9552 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009553 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009554 DVar = DSAStack->hasInnermostDSA(
9555 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9556 [](OpenMPDirectiveKind K) -> bool {
9557 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009558 isOpenMPWorksharingDirective(K) ||
9559 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009560 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009561 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009562 if (DVar.CKind == OMPC_reduction &&
9563 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009564 isOpenMPWorksharingDirective(DVar.DKind) ||
9565 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009566 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9567 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009568 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009569 continue;
9570 }
9571 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009572
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009573 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9574 // A list item cannot appear in both a map clause and a data-sharing
9575 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +00009576 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009577 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009578 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009579 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009580 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9581 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9582 ConflictKind = WhereFoundClauseKind;
9583 return true;
9584 })) {
9585 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009586 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009587 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009588 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9589 ReportOriginalDSA(*this, DSAStack, D, DVar);
9590 continue;
9591 }
9592 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009593 }
9594
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009595 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009596 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009597 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009598 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9599 << getOpenMPClauseName(OMPC_firstprivate) << Type
9600 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9601 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009602 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009603 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009604 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009605 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009606 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009607 continue;
9608 }
9609
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009610 Type = Type.getUnqualifiedType();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00009611 auto VDPrivate =
9612 buildVarDecl(*this, ELoc, Type, D->getName(),
9613 D->hasAttrs() ? &D->getAttrs() : nullptr,
9614 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009615 // Generate helper private variable and initialize it with the value of the
9616 // original variable. The address of the original variable is replaced by
9617 // the address of the new private variable in the CodeGen. This new variable
9618 // is not added to IdResolver, so the code in the OpenMP region uses
9619 // original variable for proper diagnostics and variable capturing.
9620 Expr *VDInitRefExpr = nullptr;
9621 // For arrays generate initializer for single element and replace it by the
9622 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009623 if (Type->isArrayType()) {
9624 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009625 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009626 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009627 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009628 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009629 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009630 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009631 InitializedEntity Entity =
9632 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009633 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9634
9635 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9636 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9637 if (Result.isInvalid())
9638 VDPrivate->setInvalidDecl();
9639 else
9640 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009641 // Remove temp variable declaration.
9642 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009643 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009644 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9645 ".firstprivate.temp");
9646 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9647 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009648 AddInitializerToDecl(VDPrivate,
9649 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009650 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009651 }
9652 if (VDPrivate->isInvalidDecl()) {
9653 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009654 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009655 diag::note_omp_task_predetermined_firstprivate_here);
9656 }
9657 continue;
9658 }
9659 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009660 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009661 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9662 RefExpr->getExprLoc());
9663 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009664 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009665 if (TopDVar.CKind == OMPC_lastprivate)
9666 Ref = TopDVar.PrivateCopy;
9667 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009668 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009669 if (!IsOpenMPCapturedDecl(D))
9670 ExprCaptures.push_back(Ref->getDecl());
9671 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009672 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009673 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009674 Vars.push_back((VD || CurContext->isDependentContext())
9675 ? RefExpr->IgnoreParens()
9676 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009677 PrivateCopies.push_back(VDPrivateRefExpr);
9678 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009679 }
9680
Alexey Bataeved09d242014-05-28 05:53:51 +00009681 if (Vars.empty())
9682 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009683
9684 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009685 Vars, PrivateCopies, Inits,
9686 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009687}
9688
Alexander Musman1bb328c2014-06-04 13:06:39 +00009689OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9690 SourceLocation StartLoc,
9691 SourceLocation LParenLoc,
9692 SourceLocation EndLoc) {
9693 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009694 SmallVector<Expr *, 8> SrcExprs;
9695 SmallVector<Expr *, 8> DstExprs;
9696 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009697 SmallVector<Decl *, 4> ExprCaptures;
9698 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009699 for (auto &RefExpr : VarList) {
9700 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009701 SourceLocation ELoc;
9702 SourceRange ERange;
9703 Expr *SimpleRefExpr = RefExpr;
9704 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009705 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009706 // It will be analyzed later.
9707 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009708 SrcExprs.push_back(nullptr);
9709 DstExprs.push_back(nullptr);
9710 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009711 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009712 ValueDecl *D = Res.first;
9713 if (!D)
9714 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009715
Alexey Bataev74caaf22016-02-20 04:09:36 +00009716 QualType Type = D->getType();
9717 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009718
9719 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9720 // A variable that appears in a lastprivate clause must not have an
9721 // incomplete type or a reference type.
9722 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009723 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009724 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009725 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009726
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009727 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009728 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9729 // in a Construct]
9730 // Variables with the predetermined data-sharing attributes may not be
9731 // listed in data-sharing attributes clauses, except for the cases
9732 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009733 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9734 // A list item may appear in a firstprivate or lastprivate clause but not
9735 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009736 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009737 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009738 (isOpenMPDistributeDirective(CurrDir) ||
9739 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009740 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9741 Diag(ELoc, diag::err_omp_wrong_dsa)
9742 << getOpenMPClauseName(DVar.CKind)
9743 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009744 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009745 continue;
9746 }
9747
Alexey Bataevf29276e2014-06-18 04:14:57 +00009748 // OpenMP [2.14.3.5, Restrictions, p.2]
9749 // A list item that is private within a parallel region, or that appears in
9750 // the reduction clause of a parallel construct, must not appear in a
9751 // lastprivate clause on a worksharing construct if any of the corresponding
9752 // worksharing regions ever binds to any of the corresponding parallel
9753 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009754 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009755 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009756 !isOpenMPParallelDirective(CurrDir) &&
9757 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009758 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009759 if (DVar.CKind != OMPC_shared) {
9760 Diag(ELoc, diag::err_omp_required_access)
9761 << getOpenMPClauseName(OMPC_lastprivate)
9762 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009763 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009764 continue;
9765 }
9766 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009767
Alexander Musman1bb328c2014-06-04 13:06:39 +00009768 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009769 // A variable of class type (or array thereof) that appears in a
9770 // lastprivate clause requires an accessible, unambiguous default
9771 // constructor for the class type, unless the list item is also specified
9772 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009773 // A variable of class type (or array thereof) that appears in a
9774 // lastprivate clause requires an accessible, unambiguous copy assignment
9775 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009776 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009777 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009778 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009779 D->hasAttrs() ? &D->getAttrs() : nullptr);
9780 auto *PseudoSrcExpr =
9781 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009782 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009783 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009784 D->hasAttrs() ? &D->getAttrs() : nullptr);
9785 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009786 // For arrays generate assignment operation for single element and replace
9787 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009788 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009789 PseudoDstExpr, PseudoSrcExpr);
9790 if (AssignmentOp.isInvalid())
9791 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009792 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009793 /*DiscardedValue=*/true);
9794 if (AssignmentOp.isInvalid())
9795 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009796
Alexey Bataev74caaf22016-02-20 04:09:36 +00009797 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009798 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009799 if (TopDVar.CKind == OMPC_firstprivate)
9800 Ref = TopDVar.PrivateCopy;
9801 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009802 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009803 if (!IsOpenMPCapturedDecl(D))
9804 ExprCaptures.push_back(Ref->getDecl());
9805 }
9806 if (TopDVar.CKind == OMPC_firstprivate ||
9807 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009808 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009809 ExprResult RefRes = DefaultLvalueConversion(Ref);
9810 if (!RefRes.isUsable())
9811 continue;
9812 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009813 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9814 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009815 if (!PostUpdateRes.isUsable())
9816 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009817 ExprPostUpdates.push_back(
9818 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009819 }
9820 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009821 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009822 Vars.push_back((VD || CurContext->isDependentContext())
9823 ? RefExpr->IgnoreParens()
9824 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009825 SrcExprs.push_back(PseudoSrcExpr);
9826 DstExprs.push_back(PseudoDstExpr);
9827 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009828 }
9829
9830 if (Vars.empty())
9831 return nullptr;
9832
9833 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009834 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009835 buildPreInits(Context, ExprCaptures),
9836 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009837}
9838
Alexey Bataev758e55e2013-09-06 18:03:48 +00009839OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9840 SourceLocation StartLoc,
9841 SourceLocation LParenLoc,
9842 SourceLocation EndLoc) {
9843 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009844 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009845 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009846 SourceLocation ELoc;
9847 SourceRange ERange;
9848 Expr *SimpleRefExpr = RefExpr;
9849 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009850 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009851 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009852 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009853 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009854 ValueDecl *D = Res.first;
9855 if (!D)
9856 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009857
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009858 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009859 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9860 // in a Construct]
9861 // Variables with the predetermined data-sharing attributes may not be
9862 // listed in data-sharing attributes clauses, except for the cases
9863 // listed below. For these exceptions only, listing a predetermined
9864 // variable in a data-sharing attribute clause is allowed and overrides
9865 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009866 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009867 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9868 DVar.RefExpr) {
9869 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9870 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009871 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009872 continue;
9873 }
9874
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009875 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009876 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009877 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009878 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009879 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9880 ? RefExpr->IgnoreParens()
9881 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009882 }
9883
Alexey Bataeved09d242014-05-28 05:53:51 +00009884 if (Vars.empty())
9885 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009886
9887 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9888}
9889
Alexey Bataevc5e02582014-06-16 07:08:35 +00009890namespace {
9891class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9892 DSAStackTy *Stack;
9893
9894public:
9895 bool VisitDeclRefExpr(DeclRefExpr *E) {
9896 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009897 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009898 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9899 return false;
9900 if (DVar.CKind != OMPC_unknown)
9901 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009902 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9903 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009904 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009905 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009906 return true;
9907 return false;
9908 }
9909 return false;
9910 }
9911 bool VisitStmt(Stmt *S) {
9912 for (auto Child : S->children()) {
9913 if (Child && Visit(Child))
9914 return true;
9915 }
9916 return false;
9917 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009918 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009919};
Alexey Bataev23b69422014-06-18 07:08:49 +00009920} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009921
Alexey Bataev60da77e2016-02-29 05:54:20 +00009922namespace {
9923// Transform MemberExpression for specified FieldDecl of current class to
9924// DeclRefExpr to specified OMPCapturedExprDecl.
9925class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9926 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9927 ValueDecl *Field;
9928 DeclRefExpr *CapturedExpr;
9929
9930public:
9931 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9932 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9933
9934 ExprResult TransformMemberExpr(MemberExpr *E) {
9935 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9936 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009937 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009938 return CapturedExpr;
9939 }
9940 return BaseTransform::TransformMemberExpr(E);
9941 }
9942 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9943};
9944} // namespace
9945
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009946template <typename T>
9947static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9948 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9949 for (auto &Set : Lookups) {
9950 for (auto *D : Set) {
9951 if (auto Res = Gen(cast<ValueDecl>(D)))
9952 return Res;
9953 }
9954 }
9955 return T();
9956}
9957
9958static ExprResult
9959buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9960 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9961 const DeclarationNameInfo &ReductionId, QualType Ty,
9962 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9963 if (ReductionIdScopeSpec.isInvalid())
9964 return ExprError();
9965 SmallVector<UnresolvedSet<8>, 4> Lookups;
9966 if (S) {
9967 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9968 Lookup.suppressDiagnostics();
9969 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9970 auto *D = Lookup.getRepresentativeDecl();
9971 do {
9972 S = S->getParent();
9973 } while (S && !S->isDeclScope(D));
9974 if (S)
9975 S = S->getParent();
9976 Lookups.push_back(UnresolvedSet<8>());
9977 Lookups.back().append(Lookup.begin(), Lookup.end());
9978 Lookup.clear();
9979 }
9980 } else if (auto *ULE =
9981 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9982 Lookups.push_back(UnresolvedSet<8>());
9983 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009984 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009985 if (D == PrevD)
9986 Lookups.push_back(UnresolvedSet<8>());
9987 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9988 Lookups.back().addDecl(DRD);
9989 PrevD = D;
9990 }
9991 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009992 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9993 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009994 Ty->containsUnexpandedParameterPack() ||
9995 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9996 return !D->isInvalidDecl() &&
9997 (D->getType()->isDependentType() ||
9998 D->getType()->isInstantiationDependentType() ||
9999 D->getType()->containsUnexpandedParameterPack());
10000 })) {
10001 UnresolvedSet<8> ResSet;
10002 for (auto &Set : Lookups) {
10003 ResSet.append(Set.begin(), Set.end());
10004 // The last item marks the end of all declarations at the specified scope.
10005 ResSet.addDecl(Set[Set.size() - 1]);
10006 }
10007 return UnresolvedLookupExpr::Create(
10008 SemaRef.Context, /*NamingClass=*/nullptr,
10009 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10010 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10011 }
10012 if (auto *VD = filterLookupForUDR<ValueDecl *>(
10013 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10014 if (!D->isInvalidDecl() &&
10015 SemaRef.Context.hasSameType(D->getType(), Ty))
10016 return D;
10017 return nullptr;
10018 }))
10019 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10020 if (auto *VD = filterLookupForUDR<ValueDecl *>(
10021 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10022 if (!D->isInvalidDecl() &&
10023 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10024 !Ty.isMoreQualifiedThan(D->getType()))
10025 return D;
10026 return nullptr;
10027 })) {
10028 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10029 /*DetectVirtual=*/false);
10030 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10031 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10032 VD->getType().getUnqualifiedType()))) {
10033 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10034 /*DiagID=*/0) !=
10035 Sema::AR_inaccessible) {
10036 SemaRef.BuildBasePathArray(Paths, BasePath);
10037 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10038 }
10039 }
10040 }
10041 }
10042 if (ReductionIdScopeSpec.isSet()) {
10043 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10044 return ExprError();
10045 }
10046 return ExprEmpty();
10047}
10048
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010049namespace {
10050/// Data for the reduction-based clauses.
10051struct ReductionData {
10052 /// List of original reduction items.
10053 SmallVector<Expr *, 8> Vars;
10054 /// List of private copies of the reduction items.
10055 SmallVector<Expr *, 8> Privates;
10056 /// LHS expressions for the reduction_op expressions.
10057 SmallVector<Expr *, 8> LHSs;
10058 /// RHS expressions for the reduction_op expressions.
10059 SmallVector<Expr *, 8> RHSs;
10060 /// Reduction operation expression.
10061 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010062 /// Taskgroup descriptors for the corresponding reduction items in
10063 /// in_reduction clauses.
10064 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010065 /// List of captures for clause.
10066 SmallVector<Decl *, 4> ExprCaptures;
10067 /// List of postupdate expressions.
10068 SmallVector<Expr *, 4> ExprPostUpdates;
10069 ReductionData() = delete;
10070 /// Reserves required memory for the reduction data.
10071 ReductionData(unsigned Size) {
10072 Vars.reserve(Size);
10073 Privates.reserve(Size);
10074 LHSs.reserve(Size);
10075 RHSs.reserve(Size);
10076 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010077 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010078 ExprCaptures.reserve(Size);
10079 ExprPostUpdates.reserve(Size);
10080 }
10081 /// Stores reduction item and reduction operation only (required for dependent
10082 /// reduction item).
10083 void push(Expr *Item, Expr *ReductionOp) {
10084 Vars.emplace_back(Item);
10085 Privates.emplace_back(nullptr);
10086 LHSs.emplace_back(nullptr);
10087 RHSs.emplace_back(nullptr);
10088 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010089 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010090 }
10091 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010092 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10093 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010094 Vars.emplace_back(Item);
10095 Privates.emplace_back(Private);
10096 LHSs.emplace_back(LHS);
10097 RHSs.emplace_back(RHS);
10098 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010099 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010100 }
10101};
10102} // namespace
10103
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010104static bool CheckOMPArraySectionConstantForReduction(
10105 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10106 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10107 const Expr *Length = OASE->getLength();
10108 if (Length == nullptr) {
10109 // For array sections of the form [1:] or [:], we would need to analyze
10110 // the lower bound...
10111 if (OASE->getColonLoc().isValid())
10112 return false;
10113
10114 // This is an array subscript which has implicit length 1!
10115 SingleElement = true;
10116 ArraySizes.push_back(llvm::APSInt::get(1));
10117 } else {
10118 llvm::APSInt ConstantLengthValue;
10119 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10120 return false;
10121
10122 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10123 ArraySizes.push_back(ConstantLengthValue);
10124 }
10125
10126 // Get the base of this array section and walk up from there.
10127 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10128
10129 // We require length = 1 for all array sections except the right-most to
10130 // guarantee that the memory region is contiguous and has no holes in it.
10131 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10132 Length = TempOASE->getLength();
10133 if (Length == nullptr) {
10134 // For array sections of the form [1:] or [:], we would need to analyze
10135 // the lower bound...
10136 if (OASE->getColonLoc().isValid())
10137 return false;
10138
10139 // This is an array subscript which has implicit length 1!
10140 ArraySizes.push_back(llvm::APSInt::get(1));
10141 } else {
10142 llvm::APSInt ConstantLengthValue;
10143 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10144 ConstantLengthValue.getSExtValue() != 1)
10145 return false;
10146
10147 ArraySizes.push_back(ConstantLengthValue);
10148 }
10149 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10150 }
10151
10152 // If we have a single element, we don't need to add the implicit lengths.
10153 if (!SingleElement) {
10154 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10155 // Has implicit length 1!
10156 ArraySizes.push_back(llvm::APSInt::get(1));
10157 Base = TempASE->getBase()->IgnoreParenImpCasts();
10158 }
10159 }
10160
10161 // This array section can be privatized as a single value or as a constant
10162 // sized array.
10163 return true;
10164}
10165
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010166static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010167 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10168 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10169 SourceLocation ColonLoc, SourceLocation EndLoc,
10170 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010171 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010172 auto DN = ReductionId.getName();
10173 auto OOK = DN.getCXXOverloadedOperator();
10174 BinaryOperatorKind BOK = BO_Comma;
10175
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010176 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010177 // OpenMP [2.14.3.6, reduction clause]
10178 // C
10179 // reduction-identifier is either an identifier or one of the following
10180 // operators: +, -, *, &, |, ^, && and ||
10181 // C++
10182 // reduction-identifier is either an id-expression or one of the following
10183 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010184 switch (OOK) {
10185 case OO_Plus:
10186 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010187 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010188 break;
10189 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010190 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010191 break;
10192 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010193 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010194 break;
10195 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010196 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010197 break;
10198 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010199 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010200 break;
10201 case OO_AmpAmp:
10202 BOK = BO_LAnd;
10203 break;
10204 case OO_PipePipe:
10205 BOK = BO_LOr;
10206 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010207 case OO_New:
10208 case OO_Delete:
10209 case OO_Array_New:
10210 case OO_Array_Delete:
10211 case OO_Slash:
10212 case OO_Percent:
10213 case OO_Tilde:
10214 case OO_Exclaim:
10215 case OO_Equal:
10216 case OO_Less:
10217 case OO_Greater:
10218 case OO_LessEqual:
10219 case OO_GreaterEqual:
10220 case OO_PlusEqual:
10221 case OO_MinusEqual:
10222 case OO_StarEqual:
10223 case OO_SlashEqual:
10224 case OO_PercentEqual:
10225 case OO_CaretEqual:
10226 case OO_AmpEqual:
10227 case OO_PipeEqual:
10228 case OO_LessLess:
10229 case OO_GreaterGreater:
10230 case OO_LessLessEqual:
10231 case OO_GreaterGreaterEqual:
10232 case OO_EqualEqual:
10233 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000010234 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010235 case OO_PlusPlus:
10236 case OO_MinusMinus:
10237 case OO_Comma:
10238 case OO_ArrowStar:
10239 case OO_Arrow:
10240 case OO_Call:
10241 case OO_Subscript:
10242 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000010243 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010244 case NUM_OVERLOADED_OPERATORS:
10245 llvm_unreachable("Unexpected reduction identifier");
10246 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010247 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010248 if (II->isStr("max"))
10249 BOK = BO_GT;
10250 else if (II->isStr("min"))
10251 BOK = BO_LT;
10252 }
10253 break;
10254 }
10255 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010256 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000010257 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010258 else
10259 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010260 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010261
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010262 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10263 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010264 for (auto RefExpr : VarList) {
10265 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000010266 // OpenMP [2.1, C/C++]
10267 // A list item is a variable or array section, subject to the restrictions
10268 // specified in Section 2.4 on page 42 and in each of the sections
10269 // describing clauses and directives for which a list appears.
10270 // OpenMP [2.14.3.3, Restrictions, p.1]
10271 // A variable that is part of another variable (as an array or
10272 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010273 if (!FirstIter && IR != ER)
10274 ++IR;
10275 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010276 SourceLocation ELoc;
10277 SourceRange ERange;
10278 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010279 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000010280 /*AllowArraySection=*/true);
10281 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010282 // Try to find 'declare reduction' corresponding construct before using
10283 // builtin/overloaded operators.
10284 QualType Type = Context.DependentTy;
10285 CXXCastPath BasePath;
10286 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010287 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010288 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010289 Expr *ReductionOp = nullptr;
10290 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010291 (DeclareReductionRef.isUnset() ||
10292 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010293 ReductionOp = DeclareReductionRef.get();
10294 // It will be analyzed later.
10295 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010296 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010297 ValueDecl *D = Res.first;
10298 if (!D)
10299 continue;
10300
Alexey Bataev88202be2017-07-27 13:20:36 +000010301 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010302 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010303 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10304 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10305 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +000010306 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010307 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010308 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10309 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10310 Type = ATy->getElementType();
10311 else
10312 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010313 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010314 } else
10315 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10316 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010317
Alexey Bataevc5e02582014-06-16 07:08:35 +000010318 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10319 // A variable that appears in a private clause must not have an incomplete
10320 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010321 if (S.RequireCompleteType(ELoc, Type,
10322 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010323 continue;
10324 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010325 // A list item that appears in a reduction clause must not be
10326 // const-qualified.
10327 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010328 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010329 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010330 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10331 VarDecl::DeclarationOnly;
10332 S.Diag(D->getLocation(),
10333 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010334 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010335 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010336 continue;
10337 }
10338 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10339 // If a list-item is a reference type then it must bind to the same object
10340 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010341 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010342 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010343 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010344 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010345 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010346 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10347 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010348 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010349 continue;
10350 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010351 }
10352 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010353
Alexey Bataevc5e02582014-06-16 07:08:35 +000010354 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10355 // in a Construct]
10356 // Variables with the predetermined data-sharing attributes may not be
10357 // listed in data-sharing attributes clauses, except for the cases
10358 // listed below. For these exceptions only, listing a predetermined
10359 // variable in a data-sharing attribute clause is allowed and overrides
10360 // the variable's predetermined data-sharing attributes.
10361 // OpenMP [2.14.3.6, Restrictions, p.3]
10362 // Any number of reduction clauses can be specified on the directive,
10363 // but a list item can appear only once in the reduction clauses for that
10364 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010365 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010366 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010367 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010368 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010369 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010370 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010371 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010372 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010373 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010374 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010375 << getOpenMPClauseName(DVar.CKind)
10376 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010377 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010378 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010379 }
10380
10381 // OpenMP [2.14.3.6, Restrictions, p.1]
10382 // A list item that appears in a reduction clause of a worksharing
10383 // construct must be shared in the parallel regions to which any of the
10384 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010385 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010386 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010387 !isOpenMPParallelDirective(CurrDir) &&
10388 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010389 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010390 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010391 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010392 << getOpenMPClauseName(OMPC_reduction)
10393 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010394 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010395 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010396 }
10397 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010398
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010399 // Try to find 'declare reduction' corresponding construct before using
10400 // builtin/overloaded operators.
10401 CXXCastPath BasePath;
10402 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010403 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010404 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10405 if (DeclareReductionRef.isInvalid())
10406 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010407 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010408 (DeclareReductionRef.isUnset() ||
10409 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010410 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010411 continue;
10412 }
10413 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10414 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010415 S.Diag(ReductionId.getLocStart(),
10416 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010417 << Type << ReductionIdRange;
10418 continue;
10419 }
10420
10421 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10422 // The type of a list item that appears in a reduction clause must be valid
10423 // for the reduction-identifier. For a max or min reduction in C, the type
10424 // of the list item must be an allowed arithmetic data type: char, int,
10425 // float, double, or _Bool, possibly modified with long, short, signed, or
10426 // unsigned. For a max or min reduction in C++, the type of the list item
10427 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10428 // double, or bool, possibly modified with long, short, signed, or unsigned.
10429 if (DeclareReductionRef.isUnset()) {
10430 if ((BOK == BO_GT || BOK == BO_LT) &&
10431 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010432 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10433 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010434 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010435 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010436 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10437 VarDecl::DeclarationOnly;
10438 S.Diag(D->getLocation(),
10439 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010440 << D;
10441 }
10442 continue;
10443 }
10444 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010445 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010446 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10447 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010448 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010449 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10450 VarDecl::DeclarationOnly;
10451 S.Diag(D->getLocation(),
10452 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010453 << D;
10454 }
10455 continue;
10456 }
10457 }
10458
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010459 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010460 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010461 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010462 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010463 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010464 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010465
10466 // Try if we can determine constant lengths for all array sections and avoid
10467 // the VLA.
10468 bool ConstantLengthOASE = false;
10469 if (OASE) {
10470 bool SingleElement;
10471 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10472 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10473 Context, OASE, SingleElement, ArraySizes);
10474
10475 // If we don't have a single element, we must emit a constant array type.
10476 if (ConstantLengthOASE && !SingleElement) {
10477 for (auto &Size : ArraySizes) {
10478 PrivateTy = Context.getConstantArrayType(
10479 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10480 }
10481 }
10482 }
10483
10484 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010485 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010486 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010487 if (!Context.getTargetInfo().isVLASupported() &&
10488 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10489 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10490 S.Diag(ELoc, diag::note_vla_unsupported);
10491 continue;
10492 }
David Majnemer9d168222016-08-05 17:44:54 +000010493 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010494 // Create pseudo array type for private copy. The size for this array will
10495 // be generated during codegen.
10496 // For array subscripts or single variables Private Ty is the same as Type
10497 // (type of the variable or single array element).
10498 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010499 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010500 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010501 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010502 } else if (!ASE && !OASE &&
10503 Context.getAsArrayType(D->getType().getNonReferenceType()))
10504 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010505 // Private copy.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010506 auto *PrivateVD =
10507 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
10508 D->hasAttrs() ? &D->getAttrs() : nullptr,
10509 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010510 // Add initializer for private variable.
10511 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010512 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10513 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010514 if (DeclareReductionRef.isUsable()) {
10515 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10516 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10517 if (DRD->getInitializer()) {
10518 Init = DRDRef;
10519 RHSVD->setInit(DRDRef);
10520 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010521 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010522 } else {
10523 switch (BOK) {
10524 case BO_Add:
10525 case BO_Xor:
10526 case BO_Or:
10527 case BO_LOr:
10528 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10529 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010530 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010531 break;
10532 case BO_Mul:
10533 case BO_LAnd:
10534 if (Type->isScalarType() || Type->isAnyComplexType()) {
10535 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010536 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010537 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010538 break;
10539 case BO_And: {
10540 // '&' reduction op - initializer is '~0'.
10541 QualType OrigType = Type;
10542 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10543 Type = ComplexTy->getElementType();
10544 if (Type->isRealFloatingType()) {
10545 llvm::APFloat InitValue =
10546 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10547 /*isIEEE=*/true);
10548 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10549 Type, ELoc);
10550 } else if (Type->isScalarType()) {
10551 auto Size = Context.getTypeSize(Type);
10552 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10553 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10554 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10555 }
10556 if (Init && OrigType->isAnyComplexType()) {
10557 // Init = 0xFFFF + 0xFFFFi;
10558 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010559 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010560 }
10561 Type = OrigType;
10562 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010563 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010564 case BO_LT:
10565 case BO_GT: {
10566 // 'min' reduction op - initializer is 'Largest representable number in
10567 // the reduction list item type'.
10568 // 'max' reduction op - initializer is 'Least representable number in
10569 // the reduction list item type'.
10570 if (Type->isIntegerType() || Type->isPointerType()) {
10571 bool IsSigned = Type->hasSignedIntegerRepresentation();
10572 auto Size = Context.getTypeSize(Type);
10573 QualType IntTy =
10574 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10575 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010576 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10577 : llvm::APInt::getMinValue(Size)
10578 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10579 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010580 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10581 if (Type->isPointerType()) {
10582 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010583 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010584 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010585 if (CastExpr.isInvalid())
10586 continue;
10587 Init = CastExpr.get();
10588 }
10589 } else if (Type->isRealFloatingType()) {
10590 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10591 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10592 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10593 Type, ELoc);
10594 }
10595 break;
10596 }
10597 case BO_PtrMemD:
10598 case BO_PtrMemI:
10599 case BO_MulAssign:
10600 case BO_Div:
10601 case BO_Rem:
10602 case BO_Sub:
10603 case BO_Shl:
10604 case BO_Shr:
10605 case BO_LE:
10606 case BO_GE:
10607 case BO_EQ:
10608 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000010609 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010610 case BO_AndAssign:
10611 case BO_XorAssign:
10612 case BO_OrAssign:
10613 case BO_Assign:
10614 case BO_AddAssign:
10615 case BO_SubAssign:
10616 case BO_DivAssign:
10617 case BO_RemAssign:
10618 case BO_ShlAssign:
10619 case BO_ShrAssign:
10620 case BO_Comma:
10621 llvm_unreachable("Unexpected reduction operation");
10622 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010623 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010624 if (Init && DeclareReductionRef.isUnset())
10625 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10626 else if (!Init)
10627 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010628 if (RHSVD->isInvalidDecl())
10629 continue;
10630 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010631 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10632 << Type << ReductionIdRange;
10633 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10634 VarDecl::DeclarationOnly;
10635 S.Diag(D->getLocation(),
10636 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010637 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010638 continue;
10639 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010640 // Store initializer for single element in private copy. Will be used during
10641 // codegen.
10642 PrivateVD->setInit(RHSVD->getInit());
10643 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010644 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010645 ExprResult ReductionOp;
10646 if (DeclareReductionRef.isUsable()) {
10647 QualType RedTy = DeclareReductionRef.get()->getType();
10648 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010649 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10650 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010651 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010652 LHS = S.DefaultLvalueConversion(LHS.get());
10653 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010654 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10655 CK_UncheckedDerivedToBase, LHS.get(),
10656 &BasePath, LHS.get()->getValueKind());
10657 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10658 CK_UncheckedDerivedToBase, RHS.get(),
10659 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010660 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010661 FunctionProtoType::ExtProtoInfo EPI;
10662 QualType Params[] = {PtrRedTy, PtrRedTy};
10663 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10664 auto *OVE = new (Context) OpaqueValueExpr(
10665 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010666 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010667 Expr *Args[] = {LHS.get(), RHS.get()};
10668 ReductionOp = new (Context)
10669 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10670 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010671 ReductionOp = S.BuildBinOp(
10672 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010673 if (ReductionOp.isUsable()) {
10674 if (BOK != BO_LT && BOK != BO_GT) {
10675 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010676 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10677 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010678 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010679 auto *ConditionalOp = new (Context)
10680 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10681 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010682 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010683 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10684 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010685 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010686 if (ReductionOp.isUsable())
10687 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010688 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010689 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010690 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010691 }
10692
Alexey Bataevfa312f32017-07-21 18:48:21 +000010693 // OpenMP [2.15.4.6, Restrictions, p.2]
10694 // A list item that appears in an in_reduction clause of a task construct
10695 // must appear in a task_reduction clause of a construct associated with a
10696 // taskgroup region that includes the participating task in its taskgroup
10697 // set. The construct associated with the innermost region that meets this
10698 // condition must specify the same reduction-identifier as the in_reduction
10699 // clause.
10700 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010701 SourceRange ParentSR;
10702 BinaryOperatorKind ParentBOK;
10703 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010704 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010705 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010706 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10707 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010708 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010709 Stack->getTopMostTaskgroupReductionData(
10710 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010711 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10712 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10713 if (!IsParentBOK && !IsParentReductionOp) {
10714 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10715 continue;
10716 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010717 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10718 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10719 IsParentReductionOp) {
10720 bool EmitError = true;
10721 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10722 llvm::FoldingSetNodeID RedId, ParentRedId;
10723 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10724 DeclareReductionRef.get()->Profile(RedId, Context,
10725 /*Canonical=*/true);
10726 EmitError = RedId != ParentRedId;
10727 }
10728 if (EmitError) {
10729 S.Diag(ReductionId.getLocStart(),
10730 diag::err_omp_reduction_identifier_mismatch)
10731 << ReductionIdRange << RefExpr->getSourceRange();
10732 S.Diag(ParentSR.getBegin(),
10733 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010734 << ParentSR
10735 << (IsParentBOK ? ParentBOKDSA.RefExpr
10736 : ParentReductionOpDSA.RefExpr)
10737 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010738 continue;
10739 }
10740 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010741 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10742 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010743 }
10744
Alexey Bataev60da77e2016-02-29 05:54:20 +000010745 DeclRefExpr *Ref = nullptr;
10746 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010747 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010748 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010749 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010750 VarsExpr =
10751 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10752 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010753 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010754 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010755 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010756 if (!S.IsOpenMPCapturedDecl(D)) {
10757 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010758 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010759 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010760 if (!RefRes.isUsable())
10761 continue;
10762 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010763 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10764 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010765 if (!PostUpdateRes.isUsable())
10766 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010767 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10768 Stack->getCurrentDirective() == OMPD_taskgroup) {
10769 S.Diag(RefExpr->getExprLoc(),
10770 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010771 << RefExpr->getSourceRange();
10772 continue;
10773 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010774 RD.ExprPostUpdates.emplace_back(
10775 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010776 }
10777 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010778 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010779 // All reduction items are still marked as reduction (to do not increase
10780 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010781 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010782 if (CurrDir == OMPD_taskgroup) {
10783 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010784 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10785 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010786 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010787 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010788 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010789 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10790 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010791 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010792 return RD.Vars.empty();
10793}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010794
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010795OMPClause *Sema::ActOnOpenMPReductionClause(
10796 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10797 SourceLocation ColonLoc, SourceLocation EndLoc,
10798 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10799 ArrayRef<Expr *> UnresolvedReductions) {
10800 ReductionData RD(VarList.size());
10801
Alexey Bataev169d96a2017-07-18 20:17:46 +000010802 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10803 StartLoc, LParenLoc, ColonLoc, EndLoc,
10804 ReductionIdScopeSpec, ReductionId,
10805 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010806 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010807
Alexey Bataevc5e02582014-06-16 07:08:35 +000010808 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010809 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10810 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10811 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10812 buildPreInits(Context, RD.ExprCaptures),
10813 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010814}
10815
Alexey Bataev169d96a2017-07-18 20:17:46 +000010816OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10817 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10818 SourceLocation ColonLoc, SourceLocation EndLoc,
10819 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10820 ArrayRef<Expr *> UnresolvedReductions) {
10821 ReductionData RD(VarList.size());
10822
10823 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10824 VarList, StartLoc, LParenLoc, ColonLoc,
10825 EndLoc, ReductionIdScopeSpec, ReductionId,
10826 UnresolvedReductions, RD))
10827 return nullptr;
10828
10829 return OMPTaskReductionClause::Create(
10830 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10831 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10832 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10833 buildPreInits(Context, RD.ExprCaptures),
10834 buildPostUpdate(*this, RD.ExprPostUpdates));
10835}
10836
Alexey Bataevfa312f32017-07-21 18:48:21 +000010837OMPClause *Sema::ActOnOpenMPInReductionClause(
10838 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10839 SourceLocation ColonLoc, SourceLocation EndLoc,
10840 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10841 ArrayRef<Expr *> UnresolvedReductions) {
10842 ReductionData RD(VarList.size());
10843
10844 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10845 StartLoc, LParenLoc, ColonLoc, EndLoc,
10846 ReductionIdScopeSpec, ReductionId,
10847 UnresolvedReductions, RD))
10848 return nullptr;
10849
10850 return OMPInReductionClause::Create(
10851 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10852 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010853 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010854 buildPreInits(Context, RD.ExprCaptures),
10855 buildPostUpdate(*this, RD.ExprPostUpdates));
10856}
10857
Alexey Bataevecba70f2016-04-12 11:02:11 +000010858bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10859 SourceLocation LinLoc) {
10860 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10861 LinKind == OMPC_LINEAR_unknown) {
10862 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10863 return true;
10864 }
10865 return false;
10866}
10867
10868bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10869 OpenMPLinearClauseKind LinKind,
10870 QualType Type) {
10871 auto *VD = dyn_cast_or_null<VarDecl>(D);
10872 // A variable must not have an incomplete type or a reference type.
10873 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10874 return true;
10875 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10876 !Type->isReferenceType()) {
10877 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10878 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10879 return true;
10880 }
10881 Type = Type.getNonReferenceType();
10882
10883 // A list item must not be const-qualified.
10884 if (Type.isConstant(Context)) {
10885 Diag(ELoc, diag::err_omp_const_variable)
10886 << getOpenMPClauseName(OMPC_linear);
10887 if (D) {
10888 bool IsDecl =
10889 !VD ||
10890 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10891 Diag(D->getLocation(),
10892 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10893 << D;
10894 }
10895 return true;
10896 }
10897
10898 // A list item must be of integral or pointer type.
10899 Type = Type.getUnqualifiedType().getCanonicalType();
10900 const auto *Ty = Type.getTypePtrOrNull();
10901 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10902 !Ty->isPointerType())) {
10903 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10904 if (D) {
10905 bool IsDecl =
10906 !VD ||
10907 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10908 Diag(D->getLocation(),
10909 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10910 << D;
10911 }
10912 return true;
10913 }
10914 return false;
10915}
10916
Alexey Bataev182227b2015-08-20 10:54:39 +000010917OMPClause *Sema::ActOnOpenMPLinearClause(
10918 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10919 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10920 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010921 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010922 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010923 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010924 SmallVector<Decl *, 4> ExprCaptures;
10925 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010926 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010927 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010928 for (auto &RefExpr : VarList) {
10929 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010930 SourceLocation ELoc;
10931 SourceRange ERange;
10932 Expr *SimpleRefExpr = RefExpr;
10933 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10934 /*AllowArraySection=*/false);
10935 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010936 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010937 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010938 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010939 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010940 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010941 ValueDecl *D = Res.first;
10942 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010943 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010944
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010945 QualType Type = D->getType();
10946 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010947
10948 // OpenMP [2.14.3.7, linear clause]
10949 // A list-item cannot appear in more than one linear clause.
10950 // A list-item that appears in a linear clause cannot appear in any
10951 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010952 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010953 if (DVar.RefExpr) {
10954 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10955 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010956 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010957 continue;
10958 }
10959
Alexey Bataevecba70f2016-04-12 11:02:11 +000010960 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010961 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010962 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010963
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010964 // Build private copy of original var.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010965 auto *Private =
10966 buildVarDecl(*this, ELoc, Type, D->getName(),
10967 D->hasAttrs() ? &D->getAttrs() : nullptr,
10968 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010969 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010970 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010971 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010972 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010973 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010974 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010975 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10976 if (!IsOpenMPCapturedDecl(D)) {
10977 ExprCaptures.push_back(Ref->getDecl());
10978 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10979 ExprResult RefRes = DefaultLvalueConversion(Ref);
10980 if (!RefRes.isUsable())
10981 continue;
10982 ExprResult PostUpdateRes =
10983 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10984 SimpleRefExpr, RefRes.get());
10985 if (!PostUpdateRes.isUsable())
10986 continue;
10987 ExprPostUpdates.push_back(
10988 IgnoredValueConversions(PostUpdateRes.get()).get());
10989 }
10990 }
10991 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010992 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010993 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010994 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010995 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010996 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010997 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010998 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10999
11000 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011001 Vars.push_back((VD || CurContext->isDependentContext())
11002 ? RefExpr->IgnoreParens()
11003 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011004 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000011005 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000011006 }
11007
11008 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011009 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011010
11011 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000011012 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011013 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11014 !Step->isInstantiationDependent() &&
11015 !Step->containsUnexpandedParameterPack()) {
11016 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011017 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000011018 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011019 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011020 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000011021
Alexander Musman3276a272015-03-21 10:12:56 +000011022 // Build var to save the step value.
11023 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011024 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000011025 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011026 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011027 ExprResult CalcStep =
11028 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011029 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000011030
Alexander Musman8dba6642014-04-22 13:09:42 +000011031 // Warn about zero linear step (it would be probably better specified as
11032 // making corresponding variables 'const').
11033 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000011034 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11035 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000011036 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11037 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000011038 if (!IsConstant && CalcStep.isUsable()) {
11039 // Calculate the step beforehand instead of doing this on each iteration.
11040 // (This is not used if the number of iterations may be kfold-ed).
11041 CalcStepExpr = CalcStep.get();
11042 }
Alexander Musman8dba6642014-04-22 13:09:42 +000011043 }
11044
Alexey Bataev182227b2015-08-20 10:54:39 +000011045 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11046 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011047 StepExpr, CalcStepExpr,
11048 buildPreInits(Context, ExprCaptures),
11049 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000011050}
11051
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011052static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11053 Expr *NumIterations, Sema &SemaRef,
11054 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011055 // Walk the vars and build update/final expressions for the CodeGen.
11056 SmallVector<Expr *, 8> Updates;
11057 SmallVector<Expr *, 8> Finals;
11058 Expr *Step = Clause.getStep();
11059 Expr *CalcStep = Clause.getCalcStep();
11060 // OpenMP [2.14.3.7, linear clause]
11061 // If linear-step is not specified it is assumed to be 1.
11062 if (Step == nullptr)
11063 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000011064 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000011065 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000011066 }
Alexander Musman3276a272015-03-21 10:12:56 +000011067 bool HasErrors = false;
11068 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011069 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011070 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000011071 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011072 SourceLocation ELoc;
11073 SourceRange ERange;
11074 Expr *SimpleRefExpr = RefExpr;
11075 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
11076 /*AllowArraySection=*/false);
11077 ValueDecl *D = Res.first;
11078 if (Res.second || !D) {
11079 Updates.push_back(nullptr);
11080 Finals.push_back(nullptr);
11081 HasErrors = true;
11082 continue;
11083 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011084 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011085 // OpenMP [2.15.11, distribute simd Construct]
11086 // A list item may not appear in a linear clause, unless it is the loop
11087 // iteration variable.
11088 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11089 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11090 SemaRef.Diag(ELoc,
11091 diag::err_omp_linear_distribute_var_non_loop_iteration);
11092 Updates.push_back(nullptr);
11093 Finals.push_back(nullptr);
11094 HasErrors = true;
11095 continue;
11096 }
Alexander Musman3276a272015-03-21 10:12:56 +000011097 Expr *InitExpr = *CurInit;
11098
11099 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011100 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011101 Expr *CapturedRef;
11102 if (LinKind == OMPC_LINEAR_uval)
11103 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11104 else
11105 CapturedRef =
11106 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11107 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11108 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011109
11110 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011111 ExprResult Update;
11112 if (!Info.first) {
11113 Update =
11114 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11115 InitExpr, IV, Step, /* Subtract */ false);
11116 } else
11117 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011118 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11119 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011120
11121 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011122 ExprResult Final;
11123 if (!Info.first) {
11124 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11125 InitExpr, NumIterations, Step,
11126 /* Subtract */ false);
11127 } else
11128 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011129 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11130 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011131
Alexander Musman3276a272015-03-21 10:12:56 +000011132 if (!Update.isUsable() || !Final.isUsable()) {
11133 Updates.push_back(nullptr);
11134 Finals.push_back(nullptr);
11135 HasErrors = true;
11136 } else {
11137 Updates.push_back(Update.get());
11138 Finals.push_back(Final.get());
11139 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011140 ++CurInit;
11141 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011142 }
11143 Clause.setUpdates(Updates);
11144 Clause.setFinals(Finals);
11145 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011146}
11147
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011148OMPClause *Sema::ActOnOpenMPAlignedClause(
11149 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11150 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11151
11152 SmallVector<Expr *, 8> Vars;
11153 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011154 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11155 SourceLocation ELoc;
11156 SourceRange ERange;
11157 Expr *SimpleRefExpr = RefExpr;
11158 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11159 /*AllowArraySection=*/false);
11160 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011161 // It will be analyzed later.
11162 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011163 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011164 ValueDecl *D = Res.first;
11165 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011166 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011167
Alexey Bataev1efd1662016-03-29 10:59:56 +000011168 QualType QType = D->getType();
11169 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011170
11171 // OpenMP [2.8.1, simd construct, Restrictions]
11172 // The type of list items appearing in the aligned clause must be
11173 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011174 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011175 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011176 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011177 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011178 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011179 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011180 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011181 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011182 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011183 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011184 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011185 continue;
11186 }
11187
11188 // OpenMP [2.8.1, simd construct, Restrictions]
11189 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000011190 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011191 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011192 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11193 << getOpenMPClauseName(OMPC_aligned);
11194 continue;
11195 }
11196
Alexey Bataev1efd1662016-03-29 10:59:56 +000011197 DeclRefExpr *Ref = nullptr;
11198 if (!VD && IsOpenMPCapturedDecl(D))
11199 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11200 Vars.push_back(DefaultFunctionArrayConversion(
11201 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11202 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011203 }
11204
11205 // OpenMP [2.8.1, simd construct, Description]
11206 // The parameter of the aligned clause, alignment, must be a constant
11207 // positive integer expression.
11208 // If no optional parameter is specified, implementation-defined default
11209 // alignments for SIMD instructions on the target platforms are assumed.
11210 if (Alignment != nullptr) {
11211 ExprResult AlignResult =
11212 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11213 if (AlignResult.isInvalid())
11214 return nullptr;
11215 Alignment = AlignResult.get();
11216 }
11217 if (Vars.empty())
11218 return nullptr;
11219
11220 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11221 EndLoc, Vars, Alignment);
11222}
11223
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011224OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11225 SourceLocation StartLoc,
11226 SourceLocation LParenLoc,
11227 SourceLocation EndLoc) {
11228 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011229 SmallVector<Expr *, 8> SrcExprs;
11230 SmallVector<Expr *, 8> DstExprs;
11231 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000011232 for (auto &RefExpr : VarList) {
11233 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11234 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011235 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011236 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011237 SrcExprs.push_back(nullptr);
11238 DstExprs.push_back(nullptr);
11239 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011240 continue;
11241 }
11242
Alexey Bataeved09d242014-05-28 05:53:51 +000011243 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011244 // OpenMP [2.1, C/C++]
11245 // A list item is a variable name.
11246 // OpenMP [2.14.4.1, Restrictions, p.1]
11247 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000011248 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011249 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011250 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11251 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011252 continue;
11253 }
11254
11255 Decl *D = DE->getDecl();
11256 VarDecl *VD = cast<VarDecl>(D);
11257
11258 QualType Type = VD->getType();
11259 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11260 // It will be analyzed later.
11261 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011262 SrcExprs.push_back(nullptr);
11263 DstExprs.push_back(nullptr);
11264 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011265 continue;
11266 }
11267
11268 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11269 // A list item that appears in a copyin clause must be threadprivate.
11270 if (!DSAStack->isThreadPrivate(VD)) {
11271 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000011272 << getOpenMPClauseName(OMPC_copyin)
11273 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011274 continue;
11275 }
11276
11277 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11278 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000011279 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011280 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011281 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011282 auto *SrcVD =
11283 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11284 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000011285 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011286 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11287 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011288 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11289 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011290 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011291 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011292 // For arrays generate assignment operation for single element and replace
11293 // it by the original array element in CodeGen.
11294 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11295 PseudoDstExpr, PseudoSrcExpr);
11296 if (AssignmentOp.isInvalid())
11297 continue;
11298 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11299 /*DiscardedValue=*/true);
11300 if (AssignmentOp.isInvalid())
11301 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011302
11303 DSAStack->addDSA(VD, DE, OMPC_copyin);
11304 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011305 SrcExprs.push_back(PseudoSrcExpr);
11306 DstExprs.push_back(PseudoDstExpr);
11307 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011308 }
11309
Alexey Bataeved09d242014-05-28 05:53:51 +000011310 if (Vars.empty())
11311 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011312
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011313 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11314 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011315}
11316
Alexey Bataevbae9a792014-06-27 10:37:06 +000011317OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11318 SourceLocation StartLoc,
11319 SourceLocation LParenLoc,
11320 SourceLocation EndLoc) {
11321 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011322 SmallVector<Expr *, 8> SrcExprs;
11323 SmallVector<Expr *, 8> DstExprs;
11324 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011325 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011326 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11327 SourceLocation ELoc;
11328 SourceRange ERange;
11329 Expr *SimpleRefExpr = RefExpr;
11330 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11331 /*AllowArraySection=*/false);
11332 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011333 // It will be analyzed later.
11334 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011335 SrcExprs.push_back(nullptr);
11336 DstExprs.push_back(nullptr);
11337 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011338 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011339 ValueDecl *D = Res.first;
11340 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011341 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011342
Alexey Bataeve122da12016-03-17 10:50:17 +000011343 QualType Type = D->getType();
11344 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011345
11346 // OpenMP [2.14.4.2, Restrictions, p.2]
11347 // A list item that appears in a copyprivate clause may not appear in a
11348 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011349 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11350 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011351 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11352 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011353 Diag(ELoc, diag::err_omp_wrong_dsa)
11354 << getOpenMPClauseName(DVar.CKind)
11355 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011356 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011357 continue;
11358 }
11359
11360 // OpenMP [2.11.4.2, Restrictions, p.1]
11361 // All list items that appear in a copyprivate clause must be either
11362 // threadprivate or private in the enclosing context.
11363 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011364 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011365 if (DVar.CKind == OMPC_shared) {
11366 Diag(ELoc, diag::err_omp_required_access)
11367 << getOpenMPClauseName(OMPC_copyprivate)
11368 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011369 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011370 continue;
11371 }
11372 }
11373 }
11374
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011375 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011376 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011377 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011378 << getOpenMPClauseName(OMPC_copyprivate) << Type
11379 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011380 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011381 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011382 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011383 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011384 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011385 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011386 continue;
11387 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011388
Alexey Bataevbae9a792014-06-27 10:37:06 +000011389 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11390 // A variable of class type (or array thereof) that appears in a
11391 // copyin clause requires an accessible, unambiguous copy assignment
11392 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011393 Type = Context.getBaseElementType(Type.getNonReferenceType())
11394 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011395 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011396 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11397 D->hasAttrs() ? &D->getAttrs() : nullptr);
11398 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011399 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011400 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11401 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011402 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011403 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011404 PseudoDstExpr, PseudoSrcExpr);
11405 if (AssignmentOp.isInvalid())
11406 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011407 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011408 /*DiscardedValue=*/true);
11409 if (AssignmentOp.isInvalid())
11410 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011411
11412 // No need to mark vars as copyprivate, they are already threadprivate or
11413 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011414 assert(VD || IsOpenMPCapturedDecl(D));
11415 Vars.push_back(
11416 VD ? RefExpr->IgnoreParens()
11417 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011418 SrcExprs.push_back(PseudoSrcExpr);
11419 DstExprs.push_back(PseudoDstExpr);
11420 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011421 }
11422
11423 if (Vars.empty())
11424 return nullptr;
11425
Alexey Bataeva63048e2015-03-23 06:18:07 +000011426 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11427 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011428}
11429
Alexey Bataev6125da92014-07-21 11:26:11 +000011430OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11431 SourceLocation StartLoc,
11432 SourceLocation LParenLoc,
11433 SourceLocation EndLoc) {
11434 if (VarList.empty())
11435 return nullptr;
11436
11437 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11438}
Alexey Bataevdea47612014-07-23 07:46:59 +000011439
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011440OMPClause *
11441Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11442 SourceLocation DepLoc, SourceLocation ColonLoc,
11443 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11444 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011445 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011446 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011447 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011448 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011449 return nullptr;
11450 }
11451 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011452 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11453 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011454 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011455 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011456 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11457 /*Last=*/OMPC_DEPEND_unknown, Except)
11458 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011459 return nullptr;
11460 }
11461 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011462 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011463 llvm::APSInt DepCounter(/*BitWidth=*/32);
11464 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11465 if (DepKind == OMPC_DEPEND_sink) {
11466 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11467 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11468 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011469 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011470 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011471 for (auto &RefExpr : VarList) {
11472 assert(RefExpr && "NULL expr in OpenMP shared clause.");
11473 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11474 // It will be analyzed later.
11475 Vars.push_back(RefExpr);
11476 continue;
11477 }
11478
11479 SourceLocation ELoc = RefExpr->getExprLoc();
11480 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11481 if (DepKind == OMPC_DEPEND_sink) {
11482 if (DSAStack->getParentOrderedRegionParam() &&
11483 DepCounter >= TotalDepCount) {
11484 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11485 continue;
11486 }
11487 ++DepCounter;
11488 // OpenMP [2.13.9, Summary]
11489 // depend(dependence-type : vec), where dependence-type is:
11490 // 'sink' and where vec is the iteration vector, which has the form:
11491 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11492 // where n is the value specified by the ordered clause in the loop
11493 // directive, xi denotes the loop iteration variable of the i-th nested
11494 // loop associated with the loop directive, and di is a constant
11495 // non-negative integer.
11496 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011497 // It will be analyzed later.
11498 Vars.push_back(RefExpr);
11499 continue;
11500 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011501 SimpleExpr = SimpleExpr->IgnoreImplicit();
11502 OverloadedOperatorKind OOK = OO_None;
11503 SourceLocation OOLoc;
11504 Expr *LHS = SimpleExpr;
11505 Expr *RHS = nullptr;
11506 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11507 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11508 OOLoc = BO->getOperatorLoc();
11509 LHS = BO->getLHS()->IgnoreParenImpCasts();
11510 RHS = BO->getRHS()->IgnoreParenImpCasts();
11511 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11512 OOK = OCE->getOperator();
11513 OOLoc = OCE->getOperatorLoc();
11514 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11515 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11516 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11517 OOK = MCE->getMethodDecl()
11518 ->getNameInfo()
11519 .getName()
11520 .getCXXOverloadedOperator();
11521 OOLoc = MCE->getCallee()->getExprLoc();
11522 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11523 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011524 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011525 SourceLocation ELoc;
11526 SourceRange ERange;
11527 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11528 /*AllowArraySection=*/false);
11529 if (Res.second) {
11530 // It will be analyzed later.
11531 Vars.push_back(RefExpr);
11532 }
11533 ValueDecl *D = Res.first;
11534 if (!D)
11535 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011536
Alexey Bataev17daedf2018-02-15 22:42:57 +000011537 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11538 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11539 continue;
11540 }
11541 if (RHS) {
11542 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11543 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11544 if (RHSRes.isInvalid())
11545 continue;
11546 }
11547 if (!CurContext->isDependentContext() &&
11548 DSAStack->getParentOrderedRegionParam() &&
11549 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11550 ValueDecl *VD =
11551 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
11552 if (VD) {
11553 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11554 << 1 << VD;
11555 } else {
11556 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11557 }
11558 continue;
11559 }
11560 OpsOffs.push_back({RHS, OOK});
11561 } else {
11562 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11563 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11564 (ASE &&
11565 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
11566 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11567 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11568 << RefExpr->getSourceRange();
11569 continue;
11570 }
11571 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11572 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11573 ExprResult Res =
11574 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
11575 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11576 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11577 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11578 << RefExpr->getSourceRange();
11579 continue;
11580 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011581 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011582 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011583 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011584
11585 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11586 TotalDepCount > VarList.size() &&
11587 DSAStack->getParentOrderedRegionParam() &&
11588 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11589 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
11590 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11591 }
11592 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11593 Vars.empty())
11594 return nullptr;
11595
Alexey Bataev8b427062016-05-25 12:36:08 +000011596 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11597 DepKind, DepLoc, ColonLoc, Vars);
Alexey Bataev17daedf2018-02-15 22:42:57 +000011598 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
11599 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000011600 DSAStack->addDoacrossDependClause(C, OpsOffs);
11601 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011602}
Michael Wonge710d542015-08-07 16:16:36 +000011603
11604OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11605 SourceLocation LParenLoc,
11606 SourceLocation EndLoc) {
11607 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011608 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011609
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011610 // OpenMP [2.9.1, Restrictions]
11611 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011612 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11613 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011614 return nullptr;
11615
Alexey Bataev931e19b2017-10-02 16:32:39 +000011616 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011617 OpenMPDirectiveKind CaptureRegion =
11618 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11619 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011620 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev931e19b2017-10-02 16:32:39 +000011621 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11622 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11623 HelperValStmt = buildPreInits(Context, Captures);
11624 }
11625
Alexey Bataev8451efa2018-01-15 19:06:12 +000011626 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11627 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011628}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011629
Kelvin Li0bff7af2015-11-23 05:32:03 +000011630static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000011631 DSAStackTy *Stack, QualType QTy,
11632 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000011633 NamedDecl *ND;
11634 if (QTy->isIncompleteType(&ND)) {
11635 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11636 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011637 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000011638 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
11639 !QTy.isTrivialType(SemaRef.Context))
11640 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011641 return true;
11642}
11643
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011644/// \brief Return true if it can be proven that the provided array expression
11645/// (array section or array subscript) does NOT specify the whole size of the
11646/// array whose base type is \a BaseQTy.
11647static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11648 const Expr *E,
11649 QualType BaseQTy) {
11650 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11651
11652 // If this is an array subscript, it refers to the whole size if the size of
11653 // the dimension is constant and equals 1. Also, an array section assumes the
11654 // format of an array subscript if no colon is used.
11655 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11656 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11657 return ATy->getSize().getSExtValue() != 1;
11658 // Size can't be evaluated statically.
11659 return false;
11660 }
11661
11662 assert(OASE && "Expecting array section if not an array subscript.");
11663 auto *LowerBound = OASE->getLowerBound();
11664 auto *Length = OASE->getLength();
11665
11666 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011667 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011668 if (LowerBound) {
11669 llvm::APSInt ConstLowerBound;
11670 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11671 return false; // Can't get the integer value as a constant.
11672 if (ConstLowerBound.getSExtValue())
11673 return true;
11674 }
11675
11676 // If we don't have a length we covering the whole dimension.
11677 if (!Length)
11678 return false;
11679
11680 // If the base is a pointer, we don't have a way to get the size of the
11681 // pointee.
11682 if (BaseQTy->isPointerType())
11683 return false;
11684
11685 // We can only check if the length is the same as the size of the dimension
11686 // if we have a constant array.
11687 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11688 if (!CATy)
11689 return false;
11690
11691 llvm::APSInt ConstLength;
11692 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11693 return false; // Can't get the integer value as a constant.
11694
11695 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11696}
11697
11698// Return true if it can be proven that the provided array expression (array
11699// section or array subscript) does NOT specify a single element of the array
11700// whose base type is \a BaseQTy.
11701static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011702 const Expr *E,
11703 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011704 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11705
11706 // An array subscript always refer to a single element. Also, an array section
11707 // assumes the format of an array subscript if no colon is used.
11708 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11709 return false;
11710
11711 assert(OASE && "Expecting array section if not an array subscript.");
11712 auto *Length = OASE->getLength();
11713
11714 // If we don't have a length we have to check if the array has unitary size
11715 // for this dimension. Also, we should always expect a length if the base type
11716 // is pointer.
11717 if (!Length) {
11718 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11719 return ATy->getSize().getSExtValue() != 1;
11720 // We cannot assume anything.
11721 return false;
11722 }
11723
11724 // Check if the length evaluates to 1.
11725 llvm::APSInt ConstLength;
11726 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11727 return false; // Can't get the integer value as a constant.
11728
11729 return ConstLength.getSExtValue() != 1;
11730}
11731
Samuel Antao661c0902016-05-26 17:39:58 +000011732// Return the expression of the base of the mappable expression or null if it
11733// cannot be determined and do all the necessary checks to see if the expression
11734// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011735// components of the expression.
11736static Expr *CheckMapClauseExpressionBase(
11737 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011738 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011739 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011740 SourceLocation ELoc = E->getExprLoc();
11741 SourceRange ERange = E->getSourceRange();
11742
11743 // The base of elements of list in a map clause have to be either:
11744 // - a reference to variable or field.
11745 // - a member expression.
11746 // - an array expression.
11747 //
11748 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11749 // reference to 'r'.
11750 //
11751 // If we have:
11752 //
11753 // struct SS {
11754 // Bla S;
11755 // foo() {
11756 // #pragma omp target map (S.Arr[:12]);
11757 // }
11758 // }
11759 //
11760 // We want to retrieve the member expression 'this->S';
11761
11762 Expr *RelevantExpr = nullptr;
11763
Samuel Antao5de996e2016-01-22 20:21:36 +000011764 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11765 // If a list item is an array section, it must specify contiguous storage.
11766 //
11767 // For this restriction it is sufficient that we make sure only references
11768 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011769 // exist except in the rightmost expression (unless they cover the whole
11770 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011771 //
11772 // r.ArrS[3:5].Arr[6:7]
11773 //
11774 // r.ArrS[3:5].x
11775 //
11776 // but these would be valid:
11777 // r.ArrS[3].Arr[6:7]
11778 //
11779 // r.ArrS[3].x
11780
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011781 bool AllowUnitySizeArraySection = true;
11782 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011783
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011784 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011785 E = E->IgnoreParenImpCasts();
11786
11787 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11788 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000011789 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011790
11791 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011792
11793 // If we got a reference to a declaration, we should not expect any array
11794 // section before that.
11795 AllowUnitySizeArraySection = false;
11796 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011797
11798 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011799 CurComponents.emplace_back(CurE, CurE->getDecl());
11800 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011801 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11802
11803 if (isa<CXXThisExpr>(BaseE))
11804 // We found a base expression: this->Val.
11805 RelevantExpr = CurE;
11806 else
11807 E = BaseE;
11808
11809 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011810 if (!NoDiagnose) {
11811 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11812 << CurE->getSourceRange();
11813 return nullptr;
11814 }
11815 if (RelevantExpr)
11816 return nullptr;
11817 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011818 }
11819
11820 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11821
11822 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11823 // A bit-field cannot appear in a map clause.
11824 //
11825 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011826 if (!NoDiagnose) {
11827 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11828 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11829 return nullptr;
11830 }
11831 if (RelevantExpr)
11832 return nullptr;
11833 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011834 }
11835
11836 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11837 // If the type of a list item is a reference to a type T then the type
11838 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011839 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011840
11841 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11842 // A list item cannot be a variable that is a member of a structure with
11843 // a union type.
11844 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011845 if (auto *RT = CurType->getAs<RecordType>()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011846 if (RT->isUnionType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011847 if (!NoDiagnose) {
11848 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11849 << CurE->getSourceRange();
11850 return nullptr;
11851 }
11852 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011853 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011854 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011855
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011856 // If we got a member expression, we should not expect any array section
11857 // before that:
11858 //
11859 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11860 // If a list item is an element of a structure, only the rightmost symbol
11861 // of the variable reference can be an array section.
11862 //
11863 AllowUnitySizeArraySection = false;
11864 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011865
11866 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011867 CurComponents.emplace_back(CurE, FD);
11868 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011869 E = CurE->getBase()->IgnoreParenImpCasts();
11870
11871 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011872 if (!NoDiagnose) {
11873 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11874 << 0 << CurE->getSourceRange();
11875 return nullptr;
11876 }
11877 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011878 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011879
11880 // If we got an array subscript that express the whole dimension we
11881 // can have any array expressions before. If it only expressing part of
11882 // the dimension, we can only have unitary-size array expressions.
11883 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11884 E->getType()))
11885 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011886
11887 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011888 CurComponents.emplace_back(CurE, nullptr);
11889 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011890 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000011891 E = CurE->getBase()->IgnoreParenImpCasts();
11892
Alexey Bataev27041fa2017-12-05 15:22:49 +000011893 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011894 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11895
Samuel Antao5de996e2016-01-22 20:21:36 +000011896 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11897 // If the type of a list item is a reference to a type T then the type
11898 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011899 if (CurType->isReferenceType())
11900 CurType = CurType->getPointeeType();
11901
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011902 bool IsPointer = CurType->isAnyPointerType();
11903
11904 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011905 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11906 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011907 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011908 }
11909
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011910 bool NotWhole =
11911 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11912 bool NotUnity =
11913 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11914
Samuel Antaodab51bb2016-07-18 23:22:11 +000011915 if (AllowWholeSizeArraySection) {
11916 // Any array section is currently allowed. Allowing a whole size array
11917 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011918 //
11919 // If this array section refers to the whole dimension we can still
11920 // accept other array sections before this one, except if the base is a
11921 // pointer. Otherwise, only unitary sections are accepted.
11922 if (NotWhole || IsPointer)
11923 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011924 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011925 // A unity or whole array section is not allowed and that is not
11926 // compatible with the properties of the current array section.
11927 SemaRef.Diag(
11928 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11929 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011930 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011931 }
Samuel Antao90927002016-04-26 14:54:23 +000011932
11933 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011934 CurComponents.emplace_back(CurE, nullptr);
11935 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011936 if (!NoDiagnose) {
11937 // If nothing else worked, this is not a valid map clause expression.
11938 SemaRef.Diag(
11939 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11940 << ERange;
11941 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000011942 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011943 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011944 }
11945
11946 return RelevantExpr;
11947}
11948
11949// Return true if expression E associated with value VD has conflicts with other
11950// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011951static bool CheckMapConflicts(
11952 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11953 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011954 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11955 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011956 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011957 SourceLocation ELoc = E->getExprLoc();
11958 SourceRange ERange = E->getSourceRange();
11959
11960 // In order to easily check the conflicts we need to match each component of
11961 // the expression under test with the components of the expressions that are
11962 // already in the stack.
11963
Samuel Antao5de996e2016-01-22 20:21:36 +000011964 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011965 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011966 "Map clause expression with unexpected base!");
11967
11968 // Variables to help detecting enclosing problems in data environment nests.
11969 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011970 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011971
Samuel Antao90927002016-04-26 14:54:23 +000011972 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11973 VD, CurrentRegionOnly,
11974 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011975 StackComponents,
11976 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011977
Samuel Antao5de996e2016-01-22 20:21:36 +000011978 assert(!StackComponents.empty() &&
11979 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011980 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011981 "Map clause expression with unexpected base!");
11982
Samuel Antao90927002016-04-26 14:54:23 +000011983 // The whole expression in the stack.
11984 auto *RE = StackComponents.front().getAssociatedExpression();
11985
Samuel Antao5de996e2016-01-22 20:21:36 +000011986 // Expressions must start from the same base. Here we detect at which
11987 // point both expressions diverge from each other and see if we can
11988 // detect if the memory referred to both expressions is contiguous and
11989 // do not overlap.
11990 auto CI = CurComponents.rbegin();
11991 auto CE = CurComponents.rend();
11992 auto SI = StackComponents.rbegin();
11993 auto SE = StackComponents.rend();
11994 for (; CI != CE && SI != SE; ++CI, ++SI) {
11995
11996 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11997 // At most one list item can be an array item derived from a given
11998 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011999 if (CurrentRegionOnly &&
12000 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12001 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12002 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12003 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12004 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000012005 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000012006 << CI->getAssociatedExpression()->getSourceRange();
12007 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12008 diag::note_used_here)
12009 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000012010 return true;
12011 }
12012
12013 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000012014 if (CI->getAssociatedExpression()->getStmtClass() !=
12015 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000012016 break;
12017
12018 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000012019 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000012020 break;
12021 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000012022 // Check if the extra components of the expressions in the enclosing
12023 // data environment are redundant for the current base declaration.
12024 // If they are, the maps completely overlap, which is legal.
12025 for (; SI != SE; ++SI) {
12026 QualType Type;
12027 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000012028 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000012029 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000012030 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
12031 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000012032 auto *E = OASE->getBase()->IgnoreParenImpCasts();
12033 Type =
12034 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12035 }
12036 if (Type.isNull() || Type->isAnyPointerType() ||
12037 CheckArrayExpressionDoesNotReferToWholeSize(
12038 SemaRef, SI->getAssociatedExpression(), Type))
12039 break;
12040 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012041
12042 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12043 // List items of map clauses in the same construct must not share
12044 // original storage.
12045 //
12046 // If the expressions are exactly the same or one is a subset of the
12047 // other, it means they are sharing storage.
12048 if (CI == CE && SI == SE) {
12049 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000012050 if (CKind == OMPC_map)
12051 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12052 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012053 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012054 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12055 << ERange;
12056 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012057 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12058 << RE->getSourceRange();
12059 return true;
12060 } else {
12061 // If we find the same expression in the enclosing data environment,
12062 // that is legal.
12063 IsEnclosedByDataEnvironmentExpr = true;
12064 return false;
12065 }
12066 }
12067
Samuel Antao90927002016-04-26 14:54:23 +000012068 QualType DerivedType =
12069 std::prev(CI)->getAssociatedDeclaration()->getType();
12070 SourceLocation DerivedLoc =
12071 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012072
12073 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12074 // If the type of a list item is a reference to a type T then the type
12075 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012076 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012077
12078 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12079 // A variable for which the type is pointer and an array section
12080 // derived from that variable must not appear as list items of map
12081 // clauses of the same construct.
12082 //
12083 // Also, cover one of the cases in:
12084 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12085 // If any part of the original storage of a list item has corresponding
12086 // storage in the device data environment, all of the original storage
12087 // must have corresponding storage in the device data environment.
12088 //
12089 if (DerivedType->isAnyPointerType()) {
12090 if (CI == CE || SI == SE) {
12091 SemaRef.Diag(
12092 DerivedLoc,
12093 diag::err_omp_pointer_mapped_along_with_derived_section)
12094 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012095 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12096 << RE->getSourceRange();
12097 return true;
12098 } else if (CI->getAssociatedExpression()->getStmtClass() !=
12099 SI->getAssociatedExpression()->getStmtClass() ||
12100 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12101 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012102 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012103 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012104 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012105 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12106 << RE->getSourceRange();
12107 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012108 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012109 }
12110
12111 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12112 // List items of map clauses in the same construct must not share
12113 // original storage.
12114 //
12115 // An expression is a subset of the other.
12116 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000012117 if (CKind == OMPC_map)
12118 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12119 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012120 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012121 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12122 << ERange;
12123 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012124 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12125 << RE->getSourceRange();
12126 return true;
12127 }
12128
12129 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012130 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012131 if (!CurrentRegionOnly && SI != SE)
12132 EnclosingExpr = RE;
12133
12134 // The current expression is a subset of the expression in the data
12135 // environment.
12136 IsEnclosedByDataEnvironmentExpr |=
12137 (!CurrentRegionOnly && CI != CE && SI == SE);
12138
12139 return false;
12140 });
12141
12142 if (CurrentRegionOnly)
12143 return FoundError;
12144
12145 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12146 // If any part of the original storage of a list item has corresponding
12147 // storage in the device data environment, all of the original storage must
12148 // have corresponding storage in the device data environment.
12149 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12150 // If a list item is an element of a structure, and a different element of
12151 // the structure has a corresponding list item in the device data environment
12152 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012153 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012154 // data environment prior to the task encountering the construct.
12155 //
12156 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12157 SemaRef.Diag(ELoc,
12158 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12159 << ERange;
12160 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12161 << EnclosingExpr->getSourceRange();
12162 return true;
12163 }
12164
12165 return FoundError;
12166}
12167
Samuel Antao661c0902016-05-26 17:39:58 +000012168namespace {
12169// Utility struct that gathers all the related lists associated with a mappable
12170// expression.
12171struct MappableVarListInfo final {
12172 // The list of expressions.
12173 ArrayRef<Expr *> VarList;
12174 // The list of processed expressions.
12175 SmallVector<Expr *, 16> ProcessedVarList;
12176 // The mappble components for each expression.
12177 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12178 // The base declaration of the variable.
12179 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12180
12181 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12182 // We have a list of components and base declarations for each entry in the
12183 // variable list.
12184 VarComponents.reserve(VarList.size());
12185 VarBaseDeclarations.reserve(VarList.size());
12186 }
12187};
12188}
12189
12190// Check the validity of the provided variable list for the provided clause kind
12191// \a CKind. In the check process the valid expressions, and mappable expression
12192// components and variables are extracted and used to fill \a Vars,
12193// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12194// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12195static void
12196checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12197 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12198 SourceLocation StartLoc,
12199 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12200 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012201 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12202 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000012203 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012204
Samuel Antao90927002016-04-26 14:54:23 +000012205 // Keep track of the mappable components and base declarations in this clause.
12206 // Each entry in the list is going to have a list of components associated. We
12207 // record each set of the components so that we can build the clause later on.
12208 // In the end we should have the same amount of declarations and component
12209 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000012210
Samuel Antao661c0902016-05-26 17:39:58 +000012211 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012212 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012213 SourceLocation ELoc = RE->getExprLoc();
12214
Kelvin Li0bff7af2015-11-23 05:32:03 +000012215 auto *VE = RE->IgnoreParenLValueCasts();
12216
12217 if (VE->isValueDependent() || VE->isTypeDependent() ||
12218 VE->isInstantiationDependent() ||
12219 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012220 // We can only analyze this information once the missing information is
12221 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000012222 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012223 continue;
12224 }
12225
12226 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012227
Samuel Antao5de996e2016-01-22 20:21:36 +000012228 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000012229 SemaRef.Diag(ELoc,
12230 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000012231 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012232 continue;
12233 }
12234
Samuel Antao90927002016-04-26 14:54:23 +000012235 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12236 ValueDecl *CurDeclaration = nullptr;
12237
12238 // Obtain the array or member expression bases if required. Also, fill the
12239 // components array with all the components identified in the process.
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012240 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
12241 CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000012242 if (!BE)
12243 continue;
12244
Samuel Antao90927002016-04-26 14:54:23 +000012245 assert(!CurComponents.empty() &&
12246 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012247
Samuel Antao90927002016-04-26 14:54:23 +000012248 // For the following checks, we rely on the base declaration which is
12249 // expected to be associated with the last component. The declaration is
12250 // expected to be a variable or a field (if 'this' is being mapped).
12251 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12252 assert(CurDeclaration && "Null decl on map clause.");
12253 assert(
12254 CurDeclaration->isCanonicalDecl() &&
12255 "Expecting components to have associated only canonical declarations.");
12256
12257 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12258 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000012259
12260 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000012261 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012262
12263 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000012264 // threadprivate variables cannot appear in a map clause.
12265 // OpenMP 4.5 [2.10.5, target update Construct]
12266 // threadprivate variables cannot appear in a from clause.
12267 if (VD && DSAS->isThreadPrivate(VD)) {
12268 auto DVar = DSAS->getTopDSA(VD, false);
12269 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12270 << getOpenMPClauseName(CKind);
12271 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012272 continue;
12273 }
12274
Samuel Antao5de996e2016-01-22 20:21:36 +000012275 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12276 // A list item cannot appear in both a map clause and a data-sharing
12277 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000012278
Samuel Antao5de996e2016-01-22 20:21:36 +000012279 // Check conflicts with other map clause expressions. We check the conflicts
12280 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000012281 // environment, because the restrictions are different. We only have to
12282 // check conflicts across regions for the map clauses.
12283 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12284 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012285 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012286 if (CKind == OMPC_map &&
12287 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12288 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012289 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012290
Samuel Antao661c0902016-05-26 17:39:58 +000012291 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000012292 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12293 // If the type of a list item is a reference to a type T then the type will
12294 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012295 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012296
Samuel Antao661c0902016-05-26 17:39:58 +000012297 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12298 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000012299 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000012300 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000012301 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12302 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000012303 continue;
12304
Samuel Antao661c0902016-05-26 17:39:58 +000012305 if (CKind == OMPC_map) {
12306 // target enter data
12307 // OpenMP [2.10.2, Restrictions, p. 99]
12308 // A map-type must be specified in all map clauses and must be either
12309 // to or alloc.
12310 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12311 if (DKind == OMPD_target_enter_data &&
12312 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12313 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12314 << (IsMapTypeImplicit ? 1 : 0)
12315 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12316 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012317 continue;
12318 }
Samuel Antao661c0902016-05-26 17:39:58 +000012319
12320 // target exit_data
12321 // OpenMP [2.10.3, Restrictions, p. 102]
12322 // A map-type must be specified in all map clauses and must be either
12323 // from, release, or delete.
12324 if (DKind == OMPD_target_exit_data &&
12325 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12326 MapType == OMPC_MAP_delete)) {
12327 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12328 << (IsMapTypeImplicit ? 1 : 0)
12329 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12330 << getOpenMPDirectiveName(DKind);
12331 continue;
12332 }
12333
12334 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12335 // A list item cannot appear in both a map clause and a data-sharing
12336 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000012337 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000012338 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000012339 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000012340 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12341 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000012342 auto DVar = DSAS->getTopDSA(VD, false);
12343 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000012344 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000012345 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000012346 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000012347 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12348 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12349 continue;
12350 }
12351 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012352 }
12353
Samuel Antao90927002016-04-26 14:54:23 +000012354 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012355 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012356
12357 // Store the components in the stack so that they can be used to check
12358 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012359 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12360 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012361
12362 // Save the components and declaration to create the clause. For purposes of
12363 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012364 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012365 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12366 MVLI.VarComponents.back().append(CurComponents.begin(),
12367 CurComponents.end());
12368 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12369 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012370 }
Samuel Antao661c0902016-05-26 17:39:58 +000012371}
12372
12373OMPClause *
12374Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12375 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12376 SourceLocation MapLoc, SourceLocation ColonLoc,
12377 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12378 SourceLocation LParenLoc, SourceLocation EndLoc) {
12379 MappableVarListInfo MVLI(VarList);
12380 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12381 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012382
Samuel Antao5de996e2016-01-22 20:21:36 +000012383 // We need to produce a map clause even if we don't have variables so that
12384 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012385 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12386 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12387 MVLI.VarComponents, MapTypeModifier, MapType,
12388 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012389}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012390
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012391QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12392 TypeResult ParsedType) {
12393 assert(ParsedType.isUsable());
12394
12395 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12396 if (ReductionType.isNull())
12397 return QualType();
12398
12399 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12400 // A type name in a declare reduction directive cannot be a function type, an
12401 // array type, a reference type, or a type qualified with const, volatile or
12402 // restrict.
12403 if (ReductionType.hasQualifiers()) {
12404 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12405 return QualType();
12406 }
12407
12408 if (ReductionType->isFunctionType()) {
12409 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12410 return QualType();
12411 }
12412 if (ReductionType->isReferenceType()) {
12413 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12414 return QualType();
12415 }
12416 if (ReductionType->isArrayType()) {
12417 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12418 return QualType();
12419 }
12420 return ReductionType;
12421}
12422
12423Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12424 Scope *S, DeclContext *DC, DeclarationName Name,
12425 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12426 AccessSpecifier AS, Decl *PrevDeclInScope) {
12427 SmallVector<Decl *, 8> Decls;
12428 Decls.reserve(ReductionTypes.size());
12429
12430 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012431 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012432 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12433 // A reduction-identifier may not be re-declared in the current scope for the
12434 // same type or for a type that is compatible according to the base language
12435 // rules.
12436 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12437 OMPDeclareReductionDecl *PrevDRD = nullptr;
12438 bool InCompoundScope = true;
12439 if (S != nullptr) {
12440 // Find previous declaration with the same name not referenced in other
12441 // declarations.
12442 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12443 InCompoundScope =
12444 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12445 LookupName(Lookup, S);
12446 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12447 /*AllowInlineNamespace=*/false);
12448 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12449 auto Filter = Lookup.makeFilter();
12450 while (Filter.hasNext()) {
12451 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12452 if (InCompoundScope) {
12453 auto I = UsedAsPrevious.find(PrevDecl);
12454 if (I == UsedAsPrevious.end())
12455 UsedAsPrevious[PrevDecl] = false;
12456 if (auto *D = PrevDecl->getPrevDeclInScope())
12457 UsedAsPrevious[D] = true;
12458 }
12459 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12460 PrevDecl->getLocation();
12461 }
12462 Filter.done();
12463 if (InCompoundScope) {
12464 for (auto &PrevData : UsedAsPrevious) {
12465 if (!PrevData.second) {
12466 PrevDRD = PrevData.first;
12467 break;
12468 }
12469 }
12470 }
12471 } else if (PrevDeclInScope != nullptr) {
12472 auto *PrevDRDInScope = PrevDRD =
12473 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12474 do {
12475 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12476 PrevDRDInScope->getLocation();
12477 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12478 } while (PrevDRDInScope != nullptr);
12479 }
12480 for (auto &TyData : ReductionTypes) {
12481 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12482 bool Invalid = false;
12483 if (I != PreviousRedeclTypes.end()) {
12484 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12485 << TyData.first;
12486 Diag(I->second, diag::note_previous_definition);
12487 Invalid = true;
12488 }
12489 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12490 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12491 Name, TyData.first, PrevDRD);
12492 DC->addDecl(DRD);
12493 DRD->setAccess(AS);
12494 Decls.push_back(DRD);
12495 if (Invalid)
12496 DRD->setInvalidDecl();
12497 else
12498 PrevDRD = DRD;
12499 }
12500
12501 return DeclGroupPtrTy::make(
12502 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12503}
12504
12505void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12506 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12507
12508 // Enter new function scope.
12509 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000012510 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012511 getCurFunction()->setHasOMPDeclareReductionCombiner();
12512
12513 if (S != nullptr)
12514 PushDeclContext(S, DRD);
12515 else
12516 CurContext = DRD;
12517
Faisal Valid143a0c2017-04-01 21:30:49 +000012518 PushExpressionEvaluationContext(
12519 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012520
12521 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012522 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12523 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12524 // uses semantics of argument handles by value, but it should be passed by
12525 // reference. C lang does not support references, so pass all parameters as
12526 // pointers.
12527 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012528 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012529 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012530 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12531 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12532 // uses semantics of argument handles by value, but it should be passed by
12533 // reference. C lang does not support references, so pass all parameters as
12534 // pointers.
12535 // Create 'T omp_out;' variable.
12536 auto *OmpOutParm =
12537 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12538 if (S != nullptr) {
12539 PushOnScopeChains(OmpInParm, S);
12540 PushOnScopeChains(OmpOutParm, S);
12541 } else {
12542 DRD->addDecl(OmpInParm);
12543 DRD->addDecl(OmpOutParm);
12544 }
12545}
12546
12547void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12548 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12549 DiscardCleanupsInEvaluationContext();
12550 PopExpressionEvaluationContext();
12551
12552 PopDeclContext();
12553 PopFunctionScopeInfo();
12554
12555 if (Combiner != nullptr)
12556 DRD->setCombiner(Combiner);
12557 else
12558 DRD->setInvalidDecl();
12559}
12560
Alexey Bataev070f43a2017-09-06 14:49:58 +000012561VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012562 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12563
12564 // Enter new function scope.
12565 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000012566 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012567
12568 if (S != nullptr)
12569 PushDeclContext(S, DRD);
12570 else
12571 CurContext = DRD;
12572
Faisal Valid143a0c2017-04-01 21:30:49 +000012573 PushExpressionEvaluationContext(
12574 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012575
12576 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012577 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12578 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12579 // uses semantics of argument handles by value, but it should be passed by
12580 // reference. C lang does not support references, so pass all parameters as
12581 // pointers.
12582 // Create 'T omp_priv;' variable.
12583 auto *OmpPrivParm =
12584 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012585 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12586 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12587 // uses semantics of argument handles by value, but it should be passed by
12588 // reference. C lang does not support references, so pass all parameters as
12589 // pointers.
12590 // Create 'T omp_orig;' variable.
12591 auto *OmpOrigParm =
12592 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012593 if (S != nullptr) {
12594 PushOnScopeChains(OmpPrivParm, S);
12595 PushOnScopeChains(OmpOrigParm, S);
12596 } else {
12597 DRD->addDecl(OmpPrivParm);
12598 DRD->addDecl(OmpOrigParm);
12599 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012600 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012601}
12602
Alexey Bataev070f43a2017-09-06 14:49:58 +000012603void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12604 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012605 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12606 DiscardCleanupsInEvaluationContext();
12607 PopExpressionEvaluationContext();
12608
12609 PopDeclContext();
12610 PopFunctionScopeInfo();
12611
Alexey Bataev070f43a2017-09-06 14:49:58 +000012612 if (Initializer != nullptr) {
12613 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12614 } else if (OmpPrivParm->hasInit()) {
12615 DRD->setInitializer(OmpPrivParm->getInit(),
12616 OmpPrivParm->isDirectInit()
12617 ? OMPDeclareReductionDecl::DirectInit
12618 : OMPDeclareReductionDecl::CopyInit);
12619 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012620 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012621 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012622}
12623
12624Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12625 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12626 for (auto *D : DeclReductions.get()) {
12627 if (IsValid) {
12628 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12629 if (S != nullptr)
12630 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12631 } else
12632 D->setInvalidDecl();
12633 }
12634 return DeclReductions;
12635}
12636
David Majnemer9d168222016-08-05 17:44:54 +000012637OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012638 SourceLocation StartLoc,
12639 SourceLocation LParenLoc,
12640 SourceLocation EndLoc) {
12641 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012642 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012643
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012644 // OpenMP [teams Constrcut, Restrictions]
12645 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012646 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12647 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012648 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012649
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012650 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012651 OpenMPDirectiveKind CaptureRegion =
12652 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12653 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012654 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012655 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12656 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12657 HelperValStmt = buildPreInits(Context, Captures);
12658 }
12659
12660 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12661 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012662}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012663
12664OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12665 SourceLocation StartLoc,
12666 SourceLocation LParenLoc,
12667 SourceLocation EndLoc) {
12668 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012669 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012670
12671 // OpenMP [teams Constrcut, Restrictions]
12672 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012673 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12674 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012675 return nullptr;
12676
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012677 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012678 OpenMPDirectiveKind CaptureRegion =
12679 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12680 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012681 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012682 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12683 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12684 HelperValStmt = buildPreInits(Context, Captures);
12685 }
12686
12687 return new (Context) OMPThreadLimitClause(
12688 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012689}
Alexey Bataeva0569352015-12-01 10:17:31 +000012690
12691OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12692 SourceLocation StartLoc,
12693 SourceLocation LParenLoc,
12694 SourceLocation EndLoc) {
12695 Expr *ValExpr = Priority;
12696
12697 // OpenMP [2.9.1, task Constrcut]
12698 // The priority-value is a non-negative numerical scalar expression.
12699 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12700 /*StrictlyPositive=*/false))
12701 return nullptr;
12702
12703 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12704}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012705
12706OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12707 SourceLocation StartLoc,
12708 SourceLocation LParenLoc,
12709 SourceLocation EndLoc) {
12710 Expr *ValExpr = Grainsize;
12711
12712 // OpenMP [2.9.2, taskloop Constrcut]
12713 // The parameter of the grainsize clause must be a positive integer
12714 // expression.
12715 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12716 /*StrictlyPositive=*/true))
12717 return nullptr;
12718
12719 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12720}
Alexey Bataev382967a2015-12-08 12:06:20 +000012721
12722OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12723 SourceLocation StartLoc,
12724 SourceLocation LParenLoc,
12725 SourceLocation EndLoc) {
12726 Expr *ValExpr = NumTasks;
12727
12728 // OpenMP [2.9.2, taskloop Constrcut]
12729 // The parameter of the num_tasks clause must be a positive integer
12730 // expression.
12731 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12732 /*StrictlyPositive=*/true))
12733 return nullptr;
12734
12735 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12736}
12737
Alexey Bataev28c75412015-12-15 08:19:24 +000012738OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12739 SourceLocation LParenLoc,
12740 SourceLocation EndLoc) {
12741 // OpenMP [2.13.2, critical construct, Description]
12742 // ... where hint-expression is an integer constant expression that evaluates
12743 // to a valid lock hint.
12744 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12745 if (HintExpr.isInvalid())
12746 return nullptr;
12747 return new (Context)
12748 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12749}
12750
Carlo Bertollib4adf552016-01-15 18:50:31 +000012751OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12752 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12753 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12754 SourceLocation EndLoc) {
12755 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12756 std::string Values;
12757 Values += "'";
12758 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12759 Values += "'";
12760 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12761 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12762 return nullptr;
12763 }
12764 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012765 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012766 if (ChunkSize) {
12767 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12768 !ChunkSize->isInstantiationDependent() &&
12769 !ChunkSize->containsUnexpandedParameterPack()) {
12770 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12771 ExprResult Val =
12772 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12773 if (Val.isInvalid())
12774 return nullptr;
12775
12776 ValExpr = Val.get();
12777
12778 // OpenMP [2.7.1, Restrictions]
12779 // chunk_size must be a loop invariant integer expression with a positive
12780 // value.
12781 llvm::APSInt Result;
12782 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12783 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12784 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12785 << "dist_schedule" << ChunkSize->getSourceRange();
12786 return nullptr;
12787 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012788 } else if (getOpenMPCaptureRegionForClause(
12789 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12790 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012791 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012792 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000012793 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12794 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12795 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012796 }
12797 }
12798 }
12799
12800 return new (Context)
12801 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012802 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012803}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012804
12805OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12806 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12807 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12808 SourceLocation KindLoc, SourceLocation EndLoc) {
12809 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012810 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012811 std::string Value;
12812 SourceLocation Loc;
12813 Value += "'";
12814 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12815 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012816 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012817 Loc = MLoc;
12818 } else {
12819 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012820 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012821 Loc = KindLoc;
12822 }
12823 Value += "'";
12824 Diag(Loc, diag::err_omp_unexpected_clause_value)
12825 << Value << getOpenMPClauseName(OMPC_defaultmap);
12826 return nullptr;
12827 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012828 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012829
12830 return new (Context)
12831 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12832}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012833
12834bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12835 DeclContext *CurLexicalContext = getCurLexicalContext();
12836 if (!CurLexicalContext->isFileContext() &&
12837 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012838 !CurLexicalContext->isExternCXXContext() &&
12839 !isa<CXXRecordDecl>(CurLexicalContext) &&
12840 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12841 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12842 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012843 Diag(Loc, diag::err_omp_region_not_file_context);
12844 return false;
12845 }
12846 if (IsInOpenMPDeclareTargetContext) {
12847 Diag(Loc, diag::err_omp_enclosed_declare_target);
12848 return false;
12849 }
12850
12851 IsInOpenMPDeclareTargetContext = true;
12852 return true;
12853}
12854
12855void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12856 assert(IsInOpenMPDeclareTargetContext &&
12857 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12858
12859 IsInOpenMPDeclareTargetContext = false;
12860}
12861
David Majnemer9d168222016-08-05 17:44:54 +000012862void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12863 CXXScopeSpec &ScopeSpec,
12864 const DeclarationNameInfo &Id,
12865 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12866 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012867 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12868 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12869
12870 if (Lookup.isAmbiguous())
12871 return;
12872 Lookup.suppressDiagnostics();
12873
12874 if (!Lookup.isSingleResult()) {
12875 if (TypoCorrection Corrected =
12876 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12877 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12878 CTK_ErrorRecovery)) {
12879 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12880 << Id.getName());
12881 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12882 return;
12883 }
12884
12885 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12886 return;
12887 }
12888
12889 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12890 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12891 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12892 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12893
12894 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12895 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12896 ND->addAttr(A);
12897 if (ASTMutationListener *ML = Context.getASTMutationListener())
12898 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000012899 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012900 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12901 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12902 << Id.getName();
12903 }
12904 } else
12905 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12906}
12907
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012908static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12909 Sema &SemaRef, Decl *D) {
12910 if (!D)
12911 return;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012912 const Decl *LD = nullptr;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012913 if (isa<TagDecl>(D)) {
12914 LD = cast<TagDecl>(D)->getDefinition();
12915 } else if (isa<VarDecl>(D)) {
12916 LD = cast<VarDecl>(D)->getDefinition();
12917
12918 // If this is an implicit variable that is legal and we do not need to do
12919 // anything.
12920 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012921 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12922 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12923 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012924 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012925 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012926 return;
12927 }
Alexey Bataev8e39c342018-02-16 21:23:23 +000012928 } else if (auto *F = dyn_cast<FunctionDecl>(D)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012929 const FunctionDecl *FD = nullptr;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012930 if (cast<FunctionDecl>(D)->hasBody(FD)) {
12931 LD = FD;
12932 // If the definition is associated with the current declaration in the
12933 // target region (it can be e.g. a lambda) that is legal and we do not
12934 // need to do anything else.
12935 if (LD == D) {
12936 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12937 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12938 D->addAttr(A);
12939 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12940 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12941 return;
12942 }
12943 } else if (F->isFunctionTemplateSpecialization() &&
12944 F->getTemplateSpecializationKind() ==
12945 TSK_ImplicitInstantiation) {
12946 // Check if the function is implicitly instantiated from the template
12947 // defined in the declare target region.
12948 const FunctionTemplateDecl *FTD = F->getPrimaryTemplate();
12949 if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>())
12950 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012951 }
12952 }
12953 if (!LD)
12954 LD = D;
12955 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12956 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12957 // Outlined declaration is not declared target.
12958 if (LD->isOutOfLine()) {
12959 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12960 SemaRef.Diag(SL, diag::note_used_here) << SR;
12961 } else {
Alexey Bataev8e39c342018-02-16 21:23:23 +000012962 const DeclContext *DC = LD->getDeclContext();
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012963 while (DC) {
12964 if (isa<FunctionDecl>(DC) &&
12965 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12966 break;
12967 DC = DC->getParent();
12968 }
12969 if (DC)
12970 return;
12971
12972 // Is not declared in target context.
12973 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12974 SemaRef.Diag(SL, diag::note_used_here) << SR;
12975 }
12976 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012977 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12978 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12979 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012980 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012981 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012982 }
12983}
12984
12985static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12986 Sema &SemaRef, DSAStackTy *Stack,
12987 ValueDecl *VD) {
12988 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12989 return true;
Alexey Bataev95c23e72018-02-27 21:31:11 +000012990 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
12991 /*FullCheck=*/false))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012992 return false;
12993 return true;
12994}
12995
Kelvin Li1ce87c72017-12-12 20:08:12 +000012996void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
12997 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012998 if (!D || D->isInvalidDecl())
12999 return;
13000 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
13001 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
13002 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
13003 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
13004 if (DSAStack->isThreadPrivate(VD)) {
13005 Diag(SL, diag::err_omp_threadprivate_in_target);
13006 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
13007 return;
13008 }
13009 }
13010 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
13011 // Problem if any with var declared with incomplete type will be reported
13012 // as normal, so no need to check it here.
13013 if ((E || !VD->getType()->isIncompleteType()) &&
13014 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
13015 // Mark decl as declared target to prevent further diagnostic.
Alexey Bataev8e39c342018-02-16 21:23:23 +000013016 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) ||
13017 isa<FunctionTemplateDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013018 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13019 Context, OMPDeclareTargetDeclAttr::MT_To);
13020 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013021 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013022 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013023 }
13024 return;
13025 }
13026 }
Kelvin Li1ce87c72017-12-12 20:08:12 +000013027 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
13028 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
13029 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
13030 OMPDeclareTargetDeclAttr::MT_Link)) {
13031 assert(IdLoc.isValid() && "Source location is expected");
13032 Diag(IdLoc, diag::err_omp_function_in_link_clause);
13033 Diag(FD->getLocation(), diag::note_defined_here) << FD;
13034 return;
13035 }
13036 }
Alexey Bataev8e39c342018-02-16 21:23:23 +000013037 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
13038 if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() &&
13039 (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
13040 OMPDeclareTargetDeclAttr::MT_Link)) {
13041 assert(IdLoc.isValid() && "Source location is expected");
13042 Diag(IdLoc, diag::err_omp_function_in_link_clause);
13043 Diag(FTD->getLocation(), diag::note_defined_here) << FTD;
13044 return;
13045 }
13046 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013047 if (!E) {
13048 // Checking declaration inside declare target region.
13049 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
Alexey Bataev8e39c342018-02-16 21:23:23 +000013050 (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13051 isa<FunctionTemplateDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013052 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13053 Context, OMPDeclareTargetDeclAttr::MT_To);
13054 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013055 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013056 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013057 }
13058 return;
13059 }
13060 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13061}
Samuel Antao661c0902016-05-26 17:39:58 +000013062
13063OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13064 SourceLocation StartLoc,
13065 SourceLocation LParenLoc,
13066 SourceLocation EndLoc) {
13067 MappableVarListInfo MVLI(VarList);
13068 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13069 if (MVLI.ProcessedVarList.empty())
13070 return nullptr;
13071
13072 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13073 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13074 MVLI.VarComponents);
13075}
Samuel Antaoec172c62016-05-26 17:49:04 +000013076
13077OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13078 SourceLocation StartLoc,
13079 SourceLocation LParenLoc,
13080 SourceLocation EndLoc) {
13081 MappableVarListInfo MVLI(VarList);
13082 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13083 if (MVLI.ProcessedVarList.empty())
13084 return nullptr;
13085
13086 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13087 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13088 MVLI.VarComponents);
13089}
Carlo Bertolli2404b172016-07-13 15:37:16 +000013090
13091OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13092 SourceLocation StartLoc,
13093 SourceLocation LParenLoc,
13094 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000013095 MappableVarListInfo MVLI(VarList);
13096 SmallVector<Expr *, 8> PrivateCopies;
13097 SmallVector<Expr *, 8> Inits;
13098
Carlo Bertolli2404b172016-07-13 15:37:16 +000013099 for (auto &RefExpr : VarList) {
13100 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13101 SourceLocation ELoc;
13102 SourceRange ERange;
13103 Expr *SimpleRefExpr = RefExpr;
13104 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13105 if (Res.second) {
13106 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000013107 MVLI.ProcessedVarList.push_back(RefExpr);
13108 PrivateCopies.push_back(nullptr);
13109 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013110 }
13111 ValueDecl *D = Res.first;
13112 if (!D)
13113 continue;
13114
13115 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000013116 Type = Type.getNonReferenceType().getUnqualifiedType();
13117
13118 auto *VD = dyn_cast<VarDecl>(D);
13119
13120 // Item should be a pointer or reference to pointer.
13121 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000013122 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13123 << 0 << RefExpr->getSourceRange();
13124 continue;
13125 }
Samuel Antaocc10b852016-07-28 14:23:26 +000013126
13127 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013128 auto VDPrivate =
13129 buildVarDecl(*this, ELoc, Type, D->getName(),
13130 D->hasAttrs() ? &D->getAttrs() : nullptr,
13131 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000013132 if (VDPrivate->isInvalidDecl())
13133 continue;
13134
13135 CurContext->addDecl(VDPrivate);
13136 auto VDPrivateRefExpr = buildDeclRefExpr(
13137 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13138
13139 // Add temporary variable to initialize the private copy of the pointer.
13140 auto *VDInit =
13141 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13142 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13143 RefExpr->getExprLoc());
13144 AddInitializerToDecl(VDPrivate,
13145 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013146 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000013147
13148 // If required, build a capture to implement the privatization initialized
13149 // with the current list item value.
13150 DeclRefExpr *Ref = nullptr;
13151 if (!VD)
13152 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13153 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13154 PrivateCopies.push_back(VDPrivateRefExpr);
13155 Inits.push_back(VDInitRefExpr);
13156
13157 // We need to add a data sharing attribute for this variable to make sure it
13158 // is correctly captured. A variable that shows up in a use_device_ptr has
13159 // similar properties of a first private variable.
13160 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13161
13162 // Create a mappable component for the list item. List items in this clause
13163 // only need a component.
13164 MVLI.VarBaseDeclarations.push_back(D);
13165 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13166 MVLI.VarComponents.back().push_back(
13167 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000013168 }
13169
Samuel Antaocc10b852016-07-28 14:23:26 +000013170 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000013171 return nullptr;
13172
Samuel Antaocc10b852016-07-28 14:23:26 +000013173 return OMPUseDevicePtrClause::Create(
13174 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13175 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013176}
Carlo Bertolli70594e92016-07-13 17:16:49 +000013177
13178OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13179 SourceLocation StartLoc,
13180 SourceLocation LParenLoc,
13181 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000013182 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013183 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000013184 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000013185 SourceLocation ELoc;
13186 SourceRange ERange;
13187 Expr *SimpleRefExpr = RefExpr;
13188 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13189 if (Res.second) {
13190 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000013191 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013192 }
13193 ValueDecl *D = Res.first;
13194 if (!D)
13195 continue;
13196
13197 QualType Type = D->getType();
13198 // item should be a pointer or array or reference to pointer or array
13199 if (!Type.getNonReferenceType()->isPointerType() &&
13200 !Type.getNonReferenceType()->isArrayType()) {
13201 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13202 << 0 << RefExpr->getSourceRange();
13203 continue;
13204 }
Samuel Antao6890b092016-07-28 14:25:09 +000013205
13206 // Check if the declaration in the clause does not show up in any data
13207 // sharing attribute.
13208 auto DVar = DSAStack->getTopDSA(D, false);
13209 if (isOpenMPPrivate(DVar.CKind)) {
13210 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13211 << getOpenMPClauseName(DVar.CKind)
13212 << getOpenMPClauseName(OMPC_is_device_ptr)
13213 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13214 ReportOriginalDSA(*this, DSAStack, D, DVar);
13215 continue;
13216 }
13217
13218 Expr *ConflictExpr;
13219 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013220 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000013221 [&ConflictExpr](
13222 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13223 OpenMPClauseKind) -> bool {
13224 ConflictExpr = R.front().getAssociatedExpression();
13225 return true;
13226 })) {
13227 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13228 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13229 << ConflictExpr->getSourceRange();
13230 continue;
13231 }
13232
13233 // Store the components in the stack so that they can be used to check
13234 // against other clauses later on.
13235 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13236 DSAStack->addMappableExpressionComponents(
13237 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13238
13239 // Record the expression we've just processed.
13240 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13241
13242 // Create a mappable component for the list item. List items in this clause
13243 // only need a component. We use a null declaration to signal fields in
13244 // 'this'.
13245 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13246 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13247 "Unexpected device pointer expression!");
13248 MVLI.VarBaseDeclarations.push_back(
13249 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13250 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13251 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013252 }
13253
Samuel Antao6890b092016-07-28 14:25:09 +000013254 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000013255 return nullptr;
13256
Samuel Antao6890b092016-07-28 14:25:09 +000013257 return OMPIsDevicePtrClause::Create(
13258 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13259 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013260}