blob: 320fcbcb45579a6b5a104e57305475bd0bf792c0 [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,
41 OpenMPClauseKind CKind);
42
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; }
181 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000182
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000183 bool isForceVarCapturing() const { return ForceCapturing; }
184 void setForceVarCapturing(bool V) { ForceCapturing = V; }
185
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000187 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000188 if (Stack.empty() ||
189 Stack.back().second != CurrentNonCapturingFunctionScope)
190 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
191 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
192 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000193 }
194
195 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000196 assert(!Stack.back().first.empty() &&
197 "Data-sharing attributes stack is empty!");
198 Stack.back().first.pop_back();
199 }
200
201 /// Start new OpenMP region stack in new non-capturing function.
202 void pushFunction() {
203 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
204 assert(!isa<CapturingScopeInfo>(CurFnScope));
205 CurrentNonCapturingFunctionScope = CurFnScope;
206 }
207 /// Pop region stack for non-capturing function.
208 void popFunction(const FunctionScopeInfo *OldFSI) {
209 if (!Stack.empty() && Stack.back().second == OldFSI) {
210 assert(Stack.back().first.empty());
211 Stack.pop_back();
212 }
213 CurrentNonCapturingFunctionScope = nullptr;
214 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
215 if (!isa<CapturingScopeInfo>(FSI)) {
216 CurrentNonCapturingFunctionScope = FSI;
217 break;
218 }
219 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220 }
221
Alexey Bataev28c75412015-12-15 08:19:24 +0000222 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
223 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
224 }
225 const std::pair<OMPCriticalDirective *, llvm::APSInt>
226 getCriticalWithHint(const DeclarationNameInfo &Name) const {
227 auto I = Criticals.find(Name.getAsString());
228 if (I != Criticals.end())
229 return I->second;
230 return std::make_pair(nullptr, llvm::APSInt());
231 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000232 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000233 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000234 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000235 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000236
Alexey Bataev9c821032015-04-30 04:23:23 +0000237 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000238 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000239 /// \brief Check if the specified variable is a loop control variable for
240 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000241 /// \return The index of the loop control variable in the list of associated
242 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000243 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000244 /// \brief Check if the specified variable is a loop control variable for
245 /// parent region.
246 /// \return The index of the loop control variable in the list of associated
247 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000248 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000249 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
250 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000251 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000252
Alexey Bataev758e55e2013-09-06 18:03:48 +0000253 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000254 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
255 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256
Alexey Bataevfa312f32017-07-21 18:48:21 +0000257 /// Adds additional information for the reduction items with the reduction id
258 /// represented as an operator.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000259 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
260 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000261 /// Adds additional information for the reduction items with the reduction id
262 /// represented as reduction identifier.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000265 /// Returns the location and reduction operation from the innermost parent
266 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000267 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000268 BinaryOperatorKind &BOK,
269 Expr *&TaskgroupDescriptor);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000270 /// Returns the location and reduction operation from the innermost parent
271 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000272 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000273 const Expr *&ReductionRef,
274 Expr *&TaskgroupDescriptor);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000275 /// Return reduction reference expression for the current taskgroup.
276 Expr *getTaskgroupReductionRef() const {
277 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
278 "taskgroup reference expression requested for non taskgroup "
279 "directive.");
280 return Stack.back().first.back().TaskgroupReductionRef;
281 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000282 /// Checks if the given \p VD declaration is actually a taskgroup reduction
283 /// descriptor variable at the \p Level of OpenMP regions.
284 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
285 return Stack.back().first[Level].TaskgroupReductionRef &&
286 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
287 ->getDecl() == VD;
288 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000289
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 /// \brief Returns data sharing attributes from top of the stack for the
291 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000292 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000293 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000294 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000295 /// \brief Checks if the specified variables has data-sharing attributes which
296 /// match specified \a CPred predicate in any directive which matches \a DPred
297 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000298 DSAVarData hasDSA(ValueDecl *D,
299 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
300 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
301 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000302 /// \brief Checks if the specified variables has data-sharing attributes which
303 /// match specified \a CPred predicate in any innermost directive which
304 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000305 DSAVarData
306 hasInnermostDSA(ValueDecl *D,
307 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
308 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
309 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000310 /// \brief Checks if the specified variables has explicit data-sharing
311 /// attributes which match specified \a CPred predicate at the specified
312 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000313 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000314 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000315 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000316
317 /// \brief Returns true if the directive at level \Level matches in the
318 /// specified \a DPred predicate.
319 bool hasExplicitDirective(
320 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
321 unsigned Level);
322
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000323 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000324 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
325 const DeclarationNameInfo &,
326 SourceLocation)> &DPred,
327 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000328
Alexey Bataev758e55e2013-09-06 18:03:48 +0000329 /// \brief Returns currently analyzed directive.
330 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000331 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000332 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000333 /// \brief Returns parent directive.
334 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 if (isStackEmpty() || Stack.back().first.size() == 1)
336 return OMPD_unknown;
337 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000338 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000339
340 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000341 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000342 assert(!isStackEmpty());
343 Stack.back().first.back().DefaultAttr = DSA_none;
344 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000345 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000346 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000347 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000348 assert(!isStackEmpty());
349 Stack.back().first.back().DefaultAttr = DSA_shared;
350 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000351 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000352 /// Set default data mapping attribute to 'tofrom:scalar'.
353 void setDefaultDMAToFromScalar(SourceLocation Loc) {
354 assert(!isStackEmpty());
355 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
356 Stack.back().first.back().DefaultMapAttrLoc = Loc;
357 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000358
359 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000360 return isStackEmpty() ? DSA_unspecified
361 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000362 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000363 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000364 return isStackEmpty() ? SourceLocation()
365 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000366 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000367 DefaultMapAttributes getDefaultDMA() const {
368 return isStackEmpty() ? DMA_unspecified
369 : Stack.back().first.back().DefaultMapAttr;
370 }
371 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
372 return Stack.back().first[Level].DefaultMapAttr;
373 }
374 SourceLocation getDefaultDMALocation() const {
375 return isStackEmpty() ? SourceLocation()
376 : Stack.back().first.back().DefaultMapAttrLoc;
377 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000378
Alexey Bataevf29276e2014-06-18 04:14:57 +0000379 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000380 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000381 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000382 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000383 }
384
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000385 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000386 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000387 assert(!isStackEmpty());
388 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
389 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000390 }
391 /// \brief Returns true, if parent region is ordered (has associated
392 /// 'ordered' clause), false - otherwise.
393 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000394 if (isStackEmpty() || Stack.back().first.size() == 1)
395 return false;
396 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000397 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000398 /// \brief Returns optional parameter for the ordered region.
399 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000400 if (isStackEmpty() || Stack.back().first.size() == 1)
401 return nullptr;
402 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000403 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000404 /// \brief Marks current region as nowait (it has a 'nowait' clause).
405 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000406 assert(!isStackEmpty());
407 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000408 }
409 /// \brief Returns true, if parent region is nowait (has associated
410 /// 'nowait' clause), false - otherwise.
411 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000412 if (isStackEmpty() || Stack.back().first.size() == 1)
413 return false;
414 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000415 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000416 /// \brief Marks parent region as cancel region.
417 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000418 if (!isStackEmpty() && Stack.back().first.size() > 1) {
419 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
420 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
421 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000422 }
423 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000424 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000425 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000426 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000427
Alexey Bataev9c821032015-04-30 04:23:23 +0000428 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000429 void setAssociatedLoops(unsigned Val) {
430 assert(!isStackEmpty());
431 Stack.back().first.back().AssociatedLoops = Val;
432 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000433 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000434 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000435 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000436 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000437
Alexey Bataev13314bf2014-10-09 04:18:56 +0000438 /// \brief Marks current target region as one with closely nested teams
439 /// region.
440 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000441 if (!isStackEmpty() && Stack.back().first.size() > 1) {
442 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
443 TeamsRegionLoc;
444 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000445 }
446 /// \brief Returns true, if current region has closely nested teams region.
447 bool hasInnerTeamsRegion() const {
448 return getInnerTeamsRegionLoc().isValid();
449 }
450 /// \brief Returns location of the nested teams region (if any).
451 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000452 return isStackEmpty() ? SourceLocation()
453 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000454 }
455
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000456 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000457 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000458 }
459 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000460 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000461 }
462 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000463 return isStackEmpty() ? SourceLocation()
464 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000465 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000466
Samuel Antao4c8035b2016-12-12 18:00:20 +0000467 /// Do the check specified in \a Check to all component lists and return true
468 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000469 bool checkMappableExprComponentListsForDecl(
470 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000471 const llvm::function_ref<
472 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
473 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000474 if (isStackEmpty())
475 return false;
476 auto SI = Stack.back().first.rbegin();
477 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000478
479 if (SI == SE)
480 return false;
481
482 if (CurrentRegionOnly) {
483 SE = std::next(SI);
484 } else {
485 ++SI;
486 }
487
488 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000489 auto MI = SI->MappedExprComponents.find(VD);
490 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000491 for (auto &L : MI->second.Components)
492 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000493 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000494 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000495 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000496 }
497
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000498 /// Do the check specified in \a Check to all component lists at a given level
499 /// and return true if any issue is found.
500 bool checkMappableExprComponentListsForDeclAtLevel(
501 ValueDecl *VD, unsigned Level,
502 const llvm::function_ref<
503 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
504 OpenMPClauseKind)> &Check) {
505 if (isStackEmpty())
506 return false;
507
508 auto StartI = Stack.back().first.begin();
509 auto EndI = Stack.back().first.end();
510 if (std::distance(StartI, EndI) <= (int)Level)
511 return false;
512 std::advance(StartI, Level);
513
514 auto MI = StartI->MappedExprComponents.find(VD);
515 if (MI != StartI->MappedExprComponents.end())
516 for (auto &L : MI->second.Components)
517 if (Check(L, MI->second.Kind))
518 return true;
519 return false;
520 }
521
Samuel Antao4c8035b2016-12-12 18:00:20 +0000522 /// Create a new mappable expression component list associated with a given
523 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000524 void addMappableExpressionComponents(
525 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000526 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
527 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000528 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000529 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000530 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000531 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000532 MEC.Components.resize(MEC.Components.size() + 1);
533 MEC.Components.back().append(Components.begin(), Components.end());
534 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000535 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000536
537 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000538 assert(!isStackEmpty());
539 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000540 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000541 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000542 assert(!isStackEmpty() && Stack.back().first.size() > 1);
543 auto &StackElem = *std::next(Stack.back().first.rbegin());
544 assert(isOpenMPWorksharingDirective(StackElem.Directive));
545 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000546 }
547 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
548 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000549 assert(!isStackEmpty());
550 auto &StackElem = Stack.back().first.back();
551 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
552 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000553 return llvm::make_range(Ref.begin(), Ref.end());
554 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000555 return llvm::make_range(StackElem.DoacrossDepends.end(),
556 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000557 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000558};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000559bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000560 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
561 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000562}
Alexey Bataeved09d242014-05-28 05:53:51 +0000563} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000564
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000565static Expr *getExprAsWritten(Expr *E) {
566 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
567 E = ExprTemp->getSubExpr();
568
569 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
570 E = MTE->GetTemporaryExpr();
571
572 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
573 E = Binder->getSubExpr();
574
575 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
576 E = ICE->getSubExprAsWritten();
577 return E->IgnoreParens();
578}
579
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000580static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000581 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
582 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
583 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000584 auto *VD = dyn_cast<VarDecl>(D);
585 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000586 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000587 VD = VD->getCanonicalDecl();
588 D = VD;
589 } else {
590 assert(FD);
591 FD = FD->getCanonicalDecl();
592 D = FD;
593 }
594 return D;
595}
596
David Majnemer9d168222016-08-05 17:44:54 +0000597DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000598 ValueDecl *D) {
599 D = getCanonicalDecl(D);
600 auto *VD = dyn_cast<VarDecl>(D);
601 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000602 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000603 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000604 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
605 // in a region but not in construct]
606 // File-scope or namespace-scope variables referenced in called routines
607 // in the region are shared unless they appear in a threadprivate
608 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000609 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000610 DVar.CKind = OMPC_shared;
611
612 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
613 // in a region but not in construct]
614 // Variables with static storage duration that are declared in called
615 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000616 if (VD && VD->hasGlobalStorage())
617 DVar.CKind = OMPC_shared;
618
619 // Non-static data members are shared by default.
620 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000621 DVar.CKind = OMPC_shared;
622
Alexey Bataev758e55e2013-09-06 18:03:48 +0000623 return DVar;
624 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000625
Alexey Bataevec3da872014-01-31 05:15:34 +0000626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
627 // in a Construct, C/C++, predetermined, p.1]
628 // Variables with automatic storage duration that are declared in a scope
629 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000630 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
631 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000632 DVar.CKind = OMPC_private;
633 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000634 }
635
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000636 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000637 // Explicitly specified attributes and local variables with predetermined
638 // attributes.
639 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000640 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000641 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000642 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000643 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000644 return DVar;
645 }
646
647 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
648 // in a Construct, C/C++, implicitly determined, p.1]
649 // In a parallel or task construct, the data-sharing attributes of these
650 // variables are determined by the default clause, if present.
651 switch (Iter->DefaultAttr) {
652 case DSA_shared:
653 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000654 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000655 return DVar;
656 case DSA_none:
657 return DVar;
658 case DSA_unspecified:
659 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
660 // in a Construct, implicitly determined, p.2]
661 // In a parallel construct, if no default clause is present, these
662 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000664 if (isOpenMPParallelDirective(DVar.DKind) ||
665 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000666 DVar.CKind = OMPC_shared;
667 return DVar;
668 }
669
670 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
671 // in a Construct, implicitly determined, p.4]
672 // In a task construct, if no default clause is present, a variable that in
673 // the enclosing context is determined to be shared by all implicit tasks
674 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000675 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000676 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000677 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000678 do {
679 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000680 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000681 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000682 // In a task construct, if no default clause is present, a variable
683 // whose data-sharing attribute is not determined by the rules above is
684 // firstprivate.
685 DVarTemp = getDSA(I, D);
686 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000687 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000688 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000689 return DVar;
690 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000691 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000692 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000693 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 return DVar;
695 }
696 }
697 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
698 // in a Construct, implicitly determined, p.3]
699 // For constructs other than task, if no default clause is present, these
700 // variables inherit their data-sharing attributes from the enclosing
701 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000702 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000703}
704
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000705Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000706 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000707 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000708 auto &StackElem = Stack.back().first.back();
709 auto It = StackElem.AlignedMap.find(D);
710 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000711 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000712 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000713 return nullptr;
714 } else {
715 assert(It->second && "Unexpected nullptr expr in the aligned map");
716 return It->second;
717 }
718 return nullptr;
719}
720
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000721void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000722 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000723 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000724 auto &StackElem = Stack.back().first.back();
725 StackElem.LCVMap.insert(
726 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000727}
728
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000729DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000730 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000731 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000732 auto &StackElem = Stack.back().first.back();
733 auto It = StackElem.LCVMap.find(D);
734 if (It != StackElem.LCVMap.end())
735 return It->second;
736 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000737}
738
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000739DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000740 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
741 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000742 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000743 auto &StackElem = *std::next(Stack.back().first.rbegin());
744 auto It = StackElem.LCVMap.find(D);
745 if (It != StackElem.LCVMap.end())
746 return It->second;
747 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000748}
749
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000750ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000751 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
752 "Data-sharing attributes stack is empty");
753 auto &StackElem = *std::next(Stack.back().first.rbegin());
754 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000755 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000756 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000757 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000758 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000759 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000760}
761
Alexey Bataev90c228f2016-02-08 09:29:13 +0000762void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
763 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000764 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000765 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000766 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000767 Data.Attributes = A;
768 Data.RefExpr.setPointer(E);
769 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000770 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000771 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
772 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
774 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
775 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
776 (isLoopControlVariable(D).first && A == OMPC_private));
777 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
778 Data.RefExpr.setInt(/*IntVal=*/true);
779 return;
780 }
781 const bool IsLastprivate =
782 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
783 Data.Attributes = A;
784 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
785 Data.PrivateCopy = PrivateCopy;
786 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000787 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000788 Data.Attributes = A;
789 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
790 Data.PrivateCopy = nullptr;
791 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000792 }
793}
794
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000795/// \brief Build a variable declaration for OpenMP loop iteration variable.
796static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
797 StringRef Name, const AttrVec *Attrs = nullptr) {
798 DeclContext *DC = SemaRef.CurContext;
799 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
800 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
801 VarDecl *Decl =
802 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
803 if (Attrs) {
804 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
805 I != E; ++I)
806 Decl->addAttr(*I);
807 }
808 Decl->setImplicit();
809 return Decl;
810}
811
812static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
813 SourceLocation Loc,
814 bool RefersToCapture = false) {
815 D->setReferenced();
816 D->markUsed(S.Context);
817 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
818 SourceLocation(), D, RefersToCapture, Loc, Ty,
819 VK_LValue);
820}
821
822void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
823 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000824 D = getCanonicalDecl(D);
825 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000826 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000827 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000828 "Additional reduction info may be specified only for reduction items.");
829 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
830 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000831 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000832 "Additional reduction info may be specified only once for reduction "
833 "items.");
834 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000835 Expr *&TaskgroupReductionRef =
836 Stack.back().first.back().TaskgroupReductionRef;
837 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000838 auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000839 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000840 TaskgroupReductionRef =
841 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000842 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000843}
844
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000845void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
846 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000847 D = getCanonicalDecl(D);
848 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000849 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000850 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000851 "Additional reduction info may be specified only for reduction items.");
852 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
853 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000854 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000855 "Additional reduction info may be specified only once for reduction "
856 "items.");
857 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000858 Expr *&TaskgroupReductionRef =
859 Stack.back().first.back().TaskgroupReductionRef;
860 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000861 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
862 ".task_red.");
863 TaskgroupReductionRef =
864 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000865 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000866}
867
Alexey Bataevf189cb72017-07-24 14:52:13 +0000868DSAStackTy::DSAVarData
869DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000870 BinaryOperatorKind &BOK,
871 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000872 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000873 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
874 if (Stack.back().first.empty())
875 return DSAVarData();
876 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000877 E = Stack.back().first.rend();
878 I != E; std::advance(I, 1)) {
879 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000880 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000881 continue;
882 auto &ReductionData = I->ReductionMap[D];
883 if (!ReductionData.ReductionOp ||
884 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000885 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000887 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000888 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
889 "expression for the descriptor is not "
890 "set.");
891 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000892 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
893 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000894 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000895 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000896}
897
Alexey Bataevf189cb72017-07-24 14:52:13 +0000898DSAStackTy::DSAVarData
899DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000900 const Expr *&ReductionRef,
901 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000902 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000903 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
904 if (Stack.back().first.empty())
905 return DSAVarData();
906 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000907 E = Stack.back().first.rend();
908 I != E; std::advance(I, 1)) {
909 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000910 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000911 continue;
912 auto &ReductionData = I->ReductionMap[D];
913 if (!ReductionData.ReductionOp ||
914 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000915 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000916 SR = ReductionData.ReductionRange;
917 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000918 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
919 "expression for the descriptor is not "
920 "set.");
921 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000922 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
923 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000924 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000925 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000926}
927
Alexey Bataeved09d242014-05-28 05:53:51 +0000928bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000929 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000930 if (!isStackEmpty() && Stack.back().first.size() > 1) {
931 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000932 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000933 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000934 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000935 if (I == E)
936 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000937 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000938 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000939 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000940 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000941 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000942 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000943 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000944}
945
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000946DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
947 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000948 DSAVarData DVar;
949
950 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
951 // in a Construct, C/C++, predetermined, p.1]
952 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000953 auto *VD = dyn_cast<VarDecl>(D);
954 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
955 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000956 SemaRef.getLangOpts().OpenMPUseTLS &&
957 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000958 (VD && VD->getStorageClass() == SC_Register &&
959 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
960 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000961 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000962 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000963 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000964 auto TI = Threadprivates.find(D);
965 if (TI != Threadprivates.end()) {
966 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000967 DVar.CKind = OMPC_threadprivate;
968 return DVar;
Alexey Bataev817d7f32017-11-14 21:01:01 +0000969 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
970 DVar.RefExpr = buildDeclRefExpr(
971 SemaRef, VD, D->getType().getNonReferenceType(),
972 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
973 DVar.CKind = OMPC_threadprivate;
974 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 }
976
Alexey Bataev4b465392017-04-26 15:06:24 +0000977 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000978 // Not in OpenMP execution region and top scope was already checked.
979 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000980
Alexey Bataev758e55e2013-09-06 18:03:48 +0000981 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000982 // in a Construct, C/C++, predetermined, p.4]
983 // Static data members are shared.
984 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
985 // in a Construct, C/C++, predetermined, p.7]
986 // Variables with static storage duration that are declared in a scope
987 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000988 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000989 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000990 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000991 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000992 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000993
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000994 DVar.CKind = OMPC_shared;
995 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000996 }
997
998 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000999 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1000 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001001 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1002 // in a Construct, C/C++, predetermined, p.6]
1003 // Variables with const qualified type having no mutable member are
1004 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001005 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001006 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001007 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1008 if (auto *CTD = CTSD->getSpecializedTemplate())
1009 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001010 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001011 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1012 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001013 // Variables with const-qualified type having no mutable member may be
1014 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001015 DSAVarData DVarTemp = hasDSA(
1016 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1017 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001018 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1019 return DVar;
1020
Alexey Bataev758e55e2013-09-06 18:03:48 +00001021 DVar.CKind = OMPC_shared;
1022 return DVar;
1023 }
1024
Alexey Bataev758e55e2013-09-06 18:03:48 +00001025 // Explicitly specified attributes and local variables with predetermined
1026 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001027 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001028 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001029 if (FromParent && I != EndI)
1030 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001031 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001032 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001033 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001034 DVar.CKind = I->SharingMap[D].Attributes;
1035 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001036 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001037 }
1038
1039 return DVar;
1040}
1041
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001042DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1043 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001044 if (isStackEmpty()) {
1045 StackTy::reverse_iterator I;
1046 return getDSA(I, D);
1047 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001048 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001049 auto StartI = Stack.back().first.rbegin();
1050 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001051 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001052 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001053 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054}
1055
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001056DSAStackTy::DSAVarData
1057DSAStackTy::hasDSA(ValueDecl *D,
1058 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1059 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1060 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001061 if (isStackEmpty())
1062 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001063 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001064 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001065 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001066 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001067 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001068 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001069 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001070 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001071 auto NewI = I;
1072 DSAVarData DVar = getDSA(NewI, D);
1073 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001074 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001075 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001076 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001077}
1078
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001079DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1080 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1081 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1082 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001083 if (isStackEmpty())
1084 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001085 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001086 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001087 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001088 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001089 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001090 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001091 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001092 auto NewI = StartI;
1093 DSAVarData DVar = getDSA(NewI, D);
1094 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001095}
1096
Alexey Bataevaac108a2015-06-23 04:51:00 +00001097bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001098 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001099 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001100 if (CPred(ClauseKindMode))
1101 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 if (isStackEmpty())
1103 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001105 auto StartI = Stack.back().first.begin();
1106 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001107 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001108 return false;
1109 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001110 return (StartI->SharingMap.count(D) > 0) &&
1111 StartI->SharingMap[D].RefExpr.getPointer() &&
1112 CPred(StartI->SharingMap[D].Attributes) &&
1113 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001114}
1115
Samuel Antao4be30e92015-10-02 17:14:03 +00001116bool DSAStackTy::hasExplicitDirective(
1117 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1118 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001119 if (isStackEmpty())
1120 return false;
1121 auto StartI = Stack.back().first.begin();
1122 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001123 if (std::distance(StartI, EndI) <= (int)Level)
1124 return false;
1125 std::advance(StartI, Level);
1126 return DPred(StartI->Directive);
1127}
1128
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001129bool DSAStackTy::hasDirective(
1130 const llvm::function_ref<bool(OpenMPDirectiveKind,
1131 const DeclarationNameInfo &, SourceLocation)>
1132 &DPred,
1133 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001134 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001135 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001136 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001137 auto StartI = std::next(Stack.back().first.rbegin());
1138 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001139 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001140 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001141 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1142 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1143 return true;
1144 }
1145 return false;
1146}
1147
Alexey Bataev758e55e2013-09-06 18:03:48 +00001148void Sema::InitDataSharingAttributesStack() {
1149 VarDataSharingAttributesStack = new DSAStackTy(*this);
1150}
1151
1152#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1153
Alexey Bataev4b465392017-04-26 15:06:24 +00001154void Sema::pushOpenMPFunctionRegion() {
1155 DSAStack->pushFunction();
1156}
1157
1158void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1159 DSAStack->popFunction(OldFSI);
1160}
1161
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001162bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001163 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1164
1165 auto &Ctx = getASTContext();
1166 bool IsByRef = true;
1167
1168 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001169 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001170 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001171
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001172 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001173 // This table summarizes how a given variable should be passed to the device
1174 // given its type and the clauses where it appears. This table is based on
1175 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1176 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1177 //
1178 // =========================================================================
1179 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1180 // | |(tofrom:scalar)| | pvt | | | |
1181 // =========================================================================
1182 // | scl | | | | - | | bycopy|
1183 // | scl | | - | x | - | - | bycopy|
1184 // | scl | | x | - | - | - | null |
1185 // | scl | x | | | - | | byref |
1186 // | scl | x | - | x | - | - | bycopy|
1187 // | scl | x | x | - | - | - | null |
1188 // | scl | | - | - | - | x | byref |
1189 // | scl | x | - | - | - | x | byref |
1190 //
1191 // | agg | n.a. | | | - | | byref |
1192 // | agg | n.a. | - | x | - | - | byref |
1193 // | agg | n.a. | x | - | - | - | null |
1194 // | agg | n.a. | - | - | - | x | byref |
1195 // | agg | n.a. | - | - | - | x[] | byref |
1196 //
1197 // | ptr | n.a. | | | - | | bycopy|
1198 // | ptr | n.a. | - | x | - | - | bycopy|
1199 // | ptr | n.a. | x | - | - | - | null |
1200 // | ptr | n.a. | - | - | - | x | byref |
1201 // | ptr | n.a. | - | - | - | x[] | bycopy|
1202 // | ptr | n.a. | - | - | x | | bycopy|
1203 // | ptr | n.a. | - | - | x | x | bycopy|
1204 // | ptr | n.a. | - | - | x | x[] | bycopy|
1205 // =========================================================================
1206 // Legend:
1207 // scl - scalar
1208 // ptr - pointer
1209 // agg - aggregate
1210 // x - applies
1211 // - - invalid in this combination
1212 // [] - mapped with an array section
1213 // byref - should be mapped by reference
1214 // byval - should be mapped by value
1215 // null - initialize a local variable to null on the device
1216 //
1217 // Observations:
1218 // - All scalar declarations that show up in a map clause have to be passed
1219 // by reference, because they may have been mapped in the enclosing data
1220 // environment.
1221 // - If the scalar value does not fit the size of uintptr, it has to be
1222 // passed by reference, regardless the result in the table above.
1223 // - For pointers mapped by value that have either an implicit map or an
1224 // array section, the runtime library may pass the NULL value to the
1225 // device instead of the value passed to it by the compiler.
1226
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001227 if (Ty->isReferenceType())
1228 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001229
1230 // Locate map clauses and see if the variable being captured is referred to
1231 // in any of those clauses. Here we only care about variables, not fields,
1232 // because fields are part of aggregates.
1233 bool IsVariableUsedInMapClause = false;
1234 bool IsVariableAssociatedWithSection = false;
1235
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001236 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1237 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001238 MapExprComponents,
1239 OpenMPClauseKind WhereFoundClauseKind) {
1240 // Only the map clause information influences how a variable is
1241 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001242 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001243 if (WhereFoundClauseKind != OMPC_map)
1244 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001245
1246 auto EI = MapExprComponents.rbegin();
1247 auto EE = MapExprComponents.rend();
1248
1249 assert(EI != EE && "Invalid map expression!");
1250
1251 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1252 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1253
1254 ++EI;
1255 if (EI == EE)
1256 return false;
1257
1258 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1259 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1260 isa<MemberExpr>(EI->getAssociatedExpression())) {
1261 IsVariableAssociatedWithSection = true;
1262 // There is nothing more we need to know about this variable.
1263 return true;
1264 }
1265
1266 // Keep looking for more map info.
1267 return false;
1268 });
1269
1270 if (IsVariableUsedInMapClause) {
1271 // If variable is identified in a map clause it is always captured by
1272 // reference except if it is a pointer that is dereferenced somehow.
1273 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1274 } else {
1275 // By default, all the data that has a scalar type is mapped by copy.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001276 IsByRef = !Ty->isScalarType() ||
1277 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
Samuel Antao86ace552016-04-27 22:40:57 +00001278 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001279 }
1280
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001281 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1282 IsByRef = !DSAStack->hasExplicitDSA(
1283 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1284 Level, /*NotLastprivate=*/true);
1285 }
1286
Samuel Antao86ace552016-04-27 22:40:57 +00001287 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001288 // and alignment, because the runtime library only deals with uintptr types.
1289 // If it does not fit the uintptr size, we need to pass the data by reference
1290 // instead.
1291 if (!IsByRef &&
1292 (Ctx.getTypeSizeInChars(Ty) >
1293 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001294 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001295 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001296 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001297
1298 return IsByRef;
1299}
1300
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001301unsigned Sema::getOpenMPNestingLevel() const {
1302 assert(getLangOpts().OpenMP);
1303 return DSAStack->getNestingLevel();
1304}
1305
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001306bool Sema::isInOpenMPTargetExecutionDirective() const {
1307 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1308 !DSAStack->isClauseParsingMode()) ||
1309 DSAStack->hasDirective(
1310 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1311 SourceLocation) -> bool {
1312 return isOpenMPTargetExecutionDirective(K);
1313 },
1314 false);
1315}
1316
Alexey Bataev90c228f2016-02-08 09:29:13 +00001317VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001318 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001319 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001320
1321 // If we are attempting to capture a global variable in a directive with
1322 // 'target' we return true so that this global is also mapped to the device.
1323 //
1324 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1325 // then it should not be captured. Therefore, an extra check has to be
1326 // inserted here once support for 'declare target' is added.
1327 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001328 auto *VD = dyn_cast<VarDecl>(D);
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001329 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
1330 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001331
Alexey Bataev48977c32015-08-04 08:10:48 +00001332 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1333 (!DSAStack->isClauseParsingMode() ||
1334 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001335 auto &&Info = DSAStack->isLoopControlVariable(D);
1336 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001337 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001338 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001339 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001340 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001341 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001342 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001343 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001344 DVarPrivate = DSAStack->hasDSA(
1345 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1346 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001347 if (DVarPrivate.CKind != OMPC_unknown)
1348 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001349 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001350 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001351}
1352
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001353bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001354 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1355 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001356 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1357 Level) ||
1358 // Consider taskgroup reduction descriptor variable a private to avoid
1359 // possible capture in the region.
1360 (DSAStack->hasExplicitDirective(
1361 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1362 Level) &&
1363 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001364}
1365
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001366void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1367 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1368 D = getCanonicalDecl(D);
1369 OpenMPClauseKind OMPC = OMPC_unknown;
1370 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1371 const unsigned NewLevel = I - 1;
1372 if (DSAStack->hasExplicitDSA(D,
1373 [&OMPC](const OpenMPClauseKind K) {
1374 if (isOpenMPPrivate(K)) {
1375 OMPC = K;
1376 return true;
1377 }
1378 return false;
1379 },
1380 NewLevel))
1381 break;
1382 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1383 D, NewLevel,
1384 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1385 OpenMPClauseKind) { return true; })) {
1386 OMPC = OMPC_map;
1387 break;
1388 }
1389 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1390 NewLevel)) {
1391 OMPC = OMPC_firstprivate;
1392 break;
1393 }
1394 }
1395 if (OMPC != OMPC_unknown)
1396 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1397}
1398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001399bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001400 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1401 // Return true if the current level is no longer enclosed in a target region.
1402
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 auto *VD = dyn_cast<VarDecl>(D);
1404 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001405 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1406 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001407}
1408
Alexey Bataeved09d242014-05-28 05:53:51 +00001409void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001410
1411void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1412 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001413 Scope *CurScope, SourceLocation Loc) {
1414 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001415 PushExpressionEvaluationContext(
1416 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001417}
1418
Alexey Bataevaac108a2015-06-23 04:51:00 +00001419void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1420 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001421}
1422
Alexey Bataevaac108a2015-06-23 04:51:00 +00001423void Sema::EndOpenMPClause() {
1424 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001425}
1426
Alexey Bataev758e55e2013-09-06 18:03:48 +00001427void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001428 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1429 // A variable of class type (or array thereof) that appears in a lastprivate
1430 // clause requires an accessible, unambiguous default constructor for the
1431 // class type, unless the list item is also specified in a firstprivate
1432 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001433 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001434 for (auto *C : D->clauses()) {
1435 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1436 SmallVector<Expr *, 8> PrivateCopies;
1437 for (auto *DE : Clause->varlists()) {
1438 if (DE->isValueDependent() || DE->isTypeDependent()) {
1439 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001440 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001441 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001442 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001443 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1444 QualType Type = VD->getType().getNonReferenceType();
1445 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001446 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001447 // Generate helper private variable and initialize it with the
1448 // default value. The address of the original variable is replaced
1449 // by the address of the new private variable in CodeGen. This new
1450 // variable is not added to IdResolver, so the code in the OpenMP
1451 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001452 auto *VDPrivate = buildVarDecl(
1453 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001454 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001455 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001456 if (VDPrivate->isInvalidDecl())
1457 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001458 PrivateCopies.push_back(buildDeclRefExpr(
1459 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001460 } else {
1461 // The variable is also a firstprivate, so initialization sequence
1462 // for private copy is generated already.
1463 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001464 }
1465 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001466 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001467 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001468 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001469 }
1470 }
1471 }
1472
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 DSAStack->pop();
1474 DiscardCleanupsInEvaluationContext();
1475 PopExpressionEvaluationContext();
1476}
1477
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001478static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1479 Expr *NumIterations, Sema &SemaRef,
1480 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001481
Alexey Bataeva769e072013-03-22 06:34:35 +00001482namespace {
1483
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001484class VarDeclFilterCCC : public CorrectionCandidateCallback {
1485private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001486 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001487
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001488public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001489 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001490 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001491 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001492 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001493 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001494 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1495 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001496 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001497 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001498 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001499};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001500
1501class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1502private:
1503 Sema &SemaRef;
1504
1505public:
1506 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1507 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1508 NamedDecl *ND = Candidate.getCorrectionDecl();
1509 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1510 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1511 SemaRef.getCurScope());
1512 }
1513 return false;
1514 }
1515};
1516
Alexey Bataeved09d242014-05-28 05:53:51 +00001517} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001518
1519ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1520 CXXScopeSpec &ScopeSpec,
1521 const DeclarationNameInfo &Id) {
1522 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1523 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1524
1525 if (Lookup.isAmbiguous())
1526 return ExprError();
1527
1528 VarDecl *VD;
1529 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001530 if (TypoCorrection Corrected = CorrectTypo(
1531 Id, LookupOrdinaryName, CurScope, nullptr,
1532 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001533 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001534 PDiag(Lookup.empty()
1535 ? diag::err_undeclared_var_use_suggest
1536 : diag::err_omp_expected_var_arg_suggest)
1537 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001538 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001539 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001540 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1541 : diag::err_omp_expected_var_arg)
1542 << Id.getName();
1543 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001544 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001545 } else {
1546 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001547 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001548 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1549 return ExprError();
1550 }
1551 }
1552 Lookup.suppressDiagnostics();
1553
1554 // OpenMP [2.9.2, Syntax, C/C++]
1555 // Variables must be file-scope, namespace-scope, or static block-scope.
1556 if (!VD->hasGlobalStorage()) {
1557 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001558 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1559 bool IsDecl =
1560 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001561 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001562 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1563 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001564 return ExprError();
1565 }
1566
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001567 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1568 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001569 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1570 // A threadprivate directive for file-scope variables must appear outside
1571 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001572 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1573 !getCurLexicalContext()->isTranslationUnit()) {
1574 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001575 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1576 bool IsDecl =
1577 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1578 Diag(VD->getLocation(),
1579 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1580 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001581 return ExprError();
1582 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001583 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1584 // A threadprivate directive for static class member variables must appear
1585 // in the class definition, in the same scope in which the member
1586 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001587 if (CanonicalVD->isStaticDataMember() &&
1588 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1589 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001590 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1591 bool IsDecl =
1592 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1593 Diag(VD->getLocation(),
1594 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1595 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001596 return ExprError();
1597 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001598 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1599 // A threadprivate directive for namespace-scope variables must appear
1600 // outside any definition or declaration other than the namespace
1601 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001602 if (CanonicalVD->getDeclContext()->isNamespace() &&
1603 (!getCurLexicalContext()->isFileContext() ||
1604 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1605 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001606 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1607 bool IsDecl =
1608 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1609 Diag(VD->getLocation(),
1610 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1611 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001612 return ExprError();
1613 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001614 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1615 // A threadprivate directive for static block-scope variables must appear
1616 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001617 if (CanonicalVD->isStaticLocal() && CurScope &&
1618 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001619 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001620 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1621 bool IsDecl =
1622 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1623 Diag(VD->getLocation(),
1624 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1625 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001626 return ExprError();
1627 }
1628
1629 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1630 // A threadprivate directive must lexically precede all references to any
1631 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001632 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001633 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001634 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001635 return ExprError();
1636 }
1637
1638 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001639 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1640 SourceLocation(), VD,
1641 /*RefersToEnclosingVariableOrCapture=*/false,
1642 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001643}
1644
Alexey Bataeved09d242014-05-28 05:53:51 +00001645Sema::DeclGroupPtrTy
1646Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1647 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001648 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001649 CurContext->addDecl(D);
1650 return DeclGroupPtrTy::make(DeclGroupRef(D));
1651 }
David Blaikie0403cb12016-01-15 23:43:25 +00001652 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001653}
1654
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001655namespace {
1656class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1657 Sema &SemaRef;
1658
1659public:
1660 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001661 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001662 if (VD->hasLocalStorage()) {
1663 SemaRef.Diag(E->getLocStart(),
1664 diag::err_omp_local_var_in_threadprivate_init)
1665 << E->getSourceRange();
1666 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1667 << VD << VD->getSourceRange();
1668 return true;
1669 }
1670 }
1671 return false;
1672 }
1673 bool VisitStmt(const Stmt *S) {
1674 for (auto Child : S->children()) {
1675 if (Child && Visit(Child))
1676 return true;
1677 }
1678 return false;
1679 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001680 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001681};
1682} // namespace
1683
Alexey Bataeved09d242014-05-28 05:53:51 +00001684OMPThreadPrivateDecl *
1685Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001686 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001687 for (auto &RefExpr : VarList) {
1688 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001689 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1690 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001691
Alexey Bataev376b4a42016-02-09 09:41:09 +00001692 // Mark variable as used.
1693 VD->setReferenced();
1694 VD->markUsed(Context);
1695
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001696 QualType QType = VD->getType();
1697 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1698 // It will be analyzed later.
1699 Vars.push_back(DE);
1700 continue;
1701 }
1702
Alexey Bataeva769e072013-03-22 06:34:35 +00001703 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1704 // A threadprivate variable must not have an incomplete type.
1705 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001706 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001707 continue;
1708 }
1709
1710 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1711 // A threadprivate variable must not have a reference type.
1712 if (VD->getType()->isReferenceType()) {
1713 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001714 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1715 bool IsDecl =
1716 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1717 Diag(VD->getLocation(),
1718 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1719 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001720 continue;
1721 }
1722
Samuel Antaof8b50122015-07-13 22:54:53 +00001723 // Check if this is a TLS variable. If TLS is not being supported, produce
1724 // the corresponding diagnostic.
1725 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1726 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1727 getLangOpts().OpenMPUseTLS &&
1728 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001729 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1730 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001731 Diag(ILoc, diag::err_omp_var_thread_local)
1732 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001733 bool IsDecl =
1734 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1735 Diag(VD->getLocation(),
1736 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1737 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001738 continue;
1739 }
1740
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001741 // Check if initial value of threadprivate variable reference variable with
1742 // local storage (it is not supported by runtime).
1743 if (auto Init = VD->getAnyInitializer()) {
1744 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001745 if (Checker.Visit(Init))
1746 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001747 }
1748
Alexey Bataeved09d242014-05-28 05:53:51 +00001749 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001750 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001751 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1752 Context, SourceRange(Loc, Loc)));
1753 if (auto *ML = Context.getASTMutationListener())
1754 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001755 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001756 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001757 if (!Vars.empty()) {
1758 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1759 Vars);
1760 D->setAccess(AS_public);
1761 }
1762 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001763}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001764
Alexey Bataev7ff55242014-06-19 09:13:45 +00001765static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001766 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001767 bool IsLoopIterVar = false) {
1768 if (DVar.RefExpr) {
1769 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1770 << getOpenMPClauseName(DVar.CKind);
1771 return;
1772 }
1773 enum {
1774 PDSA_StaticMemberShared,
1775 PDSA_StaticLocalVarShared,
1776 PDSA_LoopIterVarPrivate,
1777 PDSA_LoopIterVarLinear,
1778 PDSA_LoopIterVarLastprivate,
1779 PDSA_ConstVarShared,
1780 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001781 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001782 PDSA_LocalVarPrivate,
1783 PDSA_Implicit
1784 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001785 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001786 auto ReportLoc = D->getLocation();
1787 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001788 if (IsLoopIterVar) {
1789 if (DVar.CKind == OMPC_private)
1790 Reason = PDSA_LoopIterVarPrivate;
1791 else if (DVar.CKind == OMPC_lastprivate)
1792 Reason = PDSA_LoopIterVarLastprivate;
1793 else
1794 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001795 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1796 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001797 Reason = PDSA_TaskVarFirstprivate;
1798 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001799 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001800 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001801 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001802 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001803 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001804 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001805 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001806 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001807 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001808 ReportHint = true;
1809 Reason = PDSA_LocalVarPrivate;
1810 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001811 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001812 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001813 << Reason << ReportHint
1814 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1815 } else if (DVar.ImplicitDSALoc.isValid()) {
1816 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1817 << getOpenMPClauseName(DVar.CKind);
1818 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001819}
1820
Alexey Bataev758e55e2013-09-06 18:03:48 +00001821namespace {
1822class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1823 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001824 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001825 bool ErrorFound;
1826 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001827 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001828 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001829 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001830 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001831
Alexey Bataev758e55e2013-09-06 18:03:48 +00001832public:
1833 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001834 if (E->isTypeDependent() || E->isValueDependent() ||
1835 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1836 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001837 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001838 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001839 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001840 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001841 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001842
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001843 auto DVar = Stack->getTopDSA(VD, false);
1844 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001845 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001846 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001847
Alexey Bataevafe50572017-10-06 17:00:28 +00001848 // Skip internally declared static variables.
1849 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1850 return;
1851
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001852 auto ELoc = E->getExprLoc();
1853 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001854 // The default(none) clause requires that each variable that is referenced
1855 // in the construct, and does not have a predetermined data-sharing
1856 // attribute, must have its data-sharing attribute explicitly determined
1857 // by being listed in a data-sharing attribute clause.
1858 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001859 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001860 VarsWithInheritedDSA.count(VD) == 0) {
1861 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001862 return;
1863 }
1864
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001865 if (isOpenMPTargetExecutionDirective(DKind) &&
1866 !Stack->isLoopControlVariable(VD).first) {
1867 if (!Stack->checkMappableExprComponentListsForDecl(
1868 VD, /*CurrentRegionOnly=*/true,
1869 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1870 StackComponents,
1871 OpenMPClauseKind) {
1872 // Variable is used if it has been marked as an array, array
1873 // section or the variable iself.
1874 return StackComponents.size() == 1 ||
1875 std::all_of(
1876 std::next(StackComponents.rbegin()),
1877 StackComponents.rend(),
1878 [](const OMPClauseMappableExprCommon::
1879 MappableComponent &MC) {
1880 return MC.getAssociatedDeclaration() ==
1881 nullptr &&
1882 (isa<OMPArraySectionExpr>(
1883 MC.getAssociatedExpression()) ||
1884 isa<ArraySubscriptExpr>(
1885 MC.getAssociatedExpression()));
1886 });
1887 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001888 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001889 // By default lambdas are captured as firstprivates.
1890 if (const auto *RD =
1891 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001892 IsFirstprivate = RD->isLambda();
1893 IsFirstprivate =
1894 IsFirstprivate ||
1895 (VD->getType().getNonReferenceType()->isScalarType() &&
1896 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1897 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001898 ImplicitFirstprivate.emplace_back(E);
1899 else
1900 ImplicitMap.emplace_back(E);
1901 return;
1902 }
1903 }
1904
Alexey Bataev758e55e2013-09-06 18:03:48 +00001905 // OpenMP [2.9.3.6, Restrictions, p.2]
1906 // A list item that appears in a reduction clause of the innermost
1907 // enclosing worksharing or parallel construct may not be accessed in an
1908 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001909 DVar = Stack->hasInnermostDSA(
1910 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1911 [](OpenMPDirectiveKind K) -> bool {
1912 return isOpenMPParallelDirective(K) ||
1913 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1914 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001915 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001916 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001917 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001918 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1919 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001920 return;
1921 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001922
1923 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001924 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001925 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1926 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001927 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001928 }
1929 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001930 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001931 if (E->isTypeDependent() || E->isValueDependent() ||
1932 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1933 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001934 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1935 if (!FD)
1936 return;
1937 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001938 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001939 auto DVar = Stack->getTopDSA(FD, false);
1940 // Check if the variable has explicit DSA set and stop analysis if it
1941 // so.
1942 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1943 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001944
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001945 if (isOpenMPTargetExecutionDirective(DKind) &&
1946 !Stack->isLoopControlVariable(FD).first &&
1947 !Stack->checkMappableExprComponentListsForDecl(
1948 FD, /*CurrentRegionOnly=*/true,
1949 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1950 StackComponents,
1951 OpenMPClauseKind) {
1952 return isa<CXXThisExpr>(
1953 cast<MemberExpr>(
1954 StackComponents.back().getAssociatedExpression())
1955 ->getBase()
1956 ->IgnoreParens());
1957 })) {
1958 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1959 // A bit-field cannot appear in a map clause.
1960 //
1961 if (FD->isBitField()) {
1962 SemaRef.Diag(E->getMemberLoc(),
1963 diag::err_omp_bit_fields_forbidden_in_clause)
1964 << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001965 return;
1966 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001967 ImplicitMap.emplace_back(E);
1968 return;
1969 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001970
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001971 auto ELoc = E->getExprLoc();
1972 // OpenMP [2.9.3.6, Restrictions, p.2]
1973 // A list item that appears in a reduction clause of the innermost
1974 // enclosing worksharing or parallel construct may not be accessed in
1975 // an explicit task.
1976 DVar = Stack->hasInnermostDSA(
1977 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1978 [](OpenMPDirectiveKind K) -> bool {
1979 return isOpenMPParallelDirective(K) ||
1980 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1981 },
1982 /*FromParent=*/true);
1983 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1984 ErrorFound = true;
1985 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1986 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1987 return;
1988 }
1989
1990 // Define implicit data-sharing attributes for task.
1991 DVar = Stack->getImplicitDSA(FD, false);
1992 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1993 !Stack->isLoopControlVariable(FD).first)
1994 ImplicitFirstprivate.push_back(E);
1995 return;
1996 }
1997 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
1998 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
1999 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
2000 auto *VD = cast<ValueDecl>(
2001 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2002 if (!Stack->checkMappableExprComponentListsForDecl(
2003 VD, /*CurrentRegionOnly=*/true,
2004 [&CurComponents](
2005 OMPClauseMappableExprCommon::MappableExprComponentListRef
2006 StackComponents,
2007 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002008 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002009 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002010 for (const auto &SC : llvm::reverse(StackComponents)) {
2011 // Do both expressions have the same kind?
2012 if (CCI->getAssociatedExpression()->getStmtClass() !=
2013 SC.getAssociatedExpression()->getStmtClass())
2014 if (!(isa<OMPArraySectionExpr>(
2015 SC.getAssociatedExpression()) &&
2016 isa<ArraySubscriptExpr>(
2017 CCI->getAssociatedExpression())))
2018 return false;
2019
2020 Decl *CCD = CCI->getAssociatedDeclaration();
2021 Decl *SCD = SC.getAssociatedDeclaration();
2022 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2023 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2024 if (SCD != CCD)
2025 return false;
2026 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002027 if (CCI == CCE)
2028 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002029 }
2030 return true;
2031 })) {
2032 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002033 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002034 } else
2035 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002036 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002037 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002038 for (auto *C : S->clauses()) {
2039 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002040 // for task|target directives.
2041 // Skip analysis of arguments of implicitly defined map clause for target
2042 // directives.
2043 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2044 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002045 for (auto *CC : C->children()) {
2046 if (CC)
2047 Visit(CC);
2048 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002049 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002050 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002051 }
2052 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002053 for (auto *C : S->children()) {
2054 if (C && !isa<OMPExecutableDirective>(C))
2055 Visit(C);
2056 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002057 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002058
2059 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002060 ArrayRef<Expr *> getImplicitFirstprivate() const {
2061 return ImplicitFirstprivate;
2062 }
2063 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002064 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002065 return VarsWithInheritedDSA;
2066 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002067
Alexey Bataev7ff55242014-06-19 09:13:45 +00002068 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2069 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002070};
Alexey Bataeved09d242014-05-28 05:53:51 +00002071} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002072
Alexey Bataevbae9a792014-06-27 10:37:06 +00002073void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002074 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002075 case OMPD_parallel:
2076 case OMPD_parallel_for:
2077 case OMPD_parallel_for_simd:
2078 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002079 case OMPD_teams:
2080 case OMPD_teams_distribute: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002081 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002082 QualType KmpInt32PtrTy =
2083 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002084 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002085 std::make_pair(".global_tid.", KmpInt32PtrTy),
2086 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2087 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002088 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002089 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2090 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002091 break;
2092 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002093 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002094 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002095 case OMPD_target_parallel_for:
2096 case OMPD_target_parallel_for_simd: {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002097 Sema::CapturedParamNameType ParamsTarget[] = {
2098 std::make_pair(StringRef(), QualType()) // __context with shared vars
2099 };
2100 // Start a captured region for 'target' with no implicit parameters.
2101 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2102 ParamsTarget);
2103 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2104 QualType KmpInt32PtrTy =
2105 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002106 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002107 std::make_pair(".global_tid.", KmpInt32PtrTy),
2108 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2109 std::make_pair(StringRef(), QualType()) // __context with shared vars
2110 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002111 // Start a captured region for 'teams' or 'parallel'. Both regions have
2112 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002113 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002114 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002115 break;
2116 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002117 case OMPD_simd:
2118 case OMPD_for:
2119 case OMPD_for_simd:
2120 case OMPD_sections:
2121 case OMPD_section:
2122 case OMPD_single:
2123 case OMPD_master:
2124 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002125 case OMPD_taskgroup:
2126 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00002127 case OMPD_ordered:
2128 case OMPD_atomic:
2129 case OMPD_target_data:
2130 case OMPD_target:
Kelvin Li986330c2016-07-20 22:57:10 +00002131 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002132 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002133 std::make_pair(StringRef(), QualType()) // __context with shared vars
2134 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002135 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2136 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002137 break;
2138 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002139 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002140 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002141 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2142 FunctionProtoType::ExtProtoInfo EPI;
2143 EPI.Variadic = true;
2144 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002145 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002146 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002147 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2148 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2149 std::make_pair(".copy_fn.",
2150 Context.getPointerType(CopyFnType).withConst()),
2151 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002152 std::make_pair(StringRef(), QualType()) // __context with shared vars
2153 };
2154 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2155 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002156 // Mark this captured region as inlined, because we don't use outlined
2157 // function directly.
2158 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2159 AlwaysInlineAttr::CreateImplicit(
2160 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002161 break;
2162 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002163 case OMPD_taskloop:
2164 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002165 QualType KmpInt32Ty =
2166 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2167 QualType KmpUInt64Ty =
2168 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2169 QualType KmpInt64Ty =
2170 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2171 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2172 FunctionProtoType::ExtProtoInfo EPI;
2173 EPI.Variadic = true;
2174 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002175 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002176 std::make_pair(".global_tid.", KmpInt32Ty),
2177 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2178 std::make_pair(".privates.",
2179 Context.VoidPtrTy.withConst().withRestrict()),
2180 std::make_pair(
2181 ".copy_fn.",
2182 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2183 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2184 std::make_pair(".lb.", KmpUInt64Ty),
2185 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2186 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002187 std::make_pair(".reductions.",
2188 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002189 std::make_pair(StringRef(), QualType()) // __context with shared vars
2190 };
2191 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2192 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002193 // Mark this captured region as inlined, because we don't use outlined
2194 // function directly.
2195 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2196 AlwaysInlineAttr::CreateImplicit(
2197 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002198 break;
2199 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002200 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00002201 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00002202 case OMPD_distribute_parallel_for:
Kelvin Li579e41c2016-11-30 23:51:03 +00002203 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00002204 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li80e8f562016-12-29 22:16:30 +00002205 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00002206 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00002207 case OMPD_target_teams_distribute_parallel_for_simd:
2208 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002209 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2210 QualType KmpInt32PtrTy =
2211 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2212 Sema::CapturedParamNameType Params[] = {
2213 std::make_pair(".global_tid.", KmpInt32PtrTy),
2214 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2215 std::make_pair(".previous.lb.", Context.getSizeType()),
2216 std::make_pair(".previous.ub.", Context.getSizeType()),
2217 std::make_pair(StringRef(), QualType()) // __context with shared vars
2218 };
2219 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2220 Params);
2221 break;
2222 }
Carlo Bertolli62fae152017-11-20 20:46:39 +00002223 case OMPD_teams_distribute_parallel_for: {
2224 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2225 QualType KmpInt32PtrTy =
2226 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2227
2228 Sema::CapturedParamNameType ParamsTeams[] = {
2229 std::make_pair(".global_tid.", KmpInt32PtrTy),
2230 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2231 std::make_pair(StringRef(), QualType()) // __context with shared vars
2232 };
2233 // Start a captured region for 'target' with no implicit parameters.
2234 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2235 ParamsTeams);
2236
2237 Sema::CapturedParamNameType ParamsParallel[] = {
2238 std::make_pair(".global_tid.", KmpInt32PtrTy),
2239 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2240 std::make_pair(".previous.lb.", Context.getSizeType()),
2241 std::make_pair(".previous.ub.", Context.getSizeType()),
2242 std::make_pair(StringRef(), QualType()) // __context with shared vars
2243 };
2244 // Start a captured region for 'teams' or 'parallel'. Both regions have
2245 // the same implicit parameters.
2246 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2247 ParamsParallel);
2248 break;
2249 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002250 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002251 case OMPD_taskyield:
2252 case OMPD_barrier:
2253 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002254 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002255 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002256 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00002257 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00002258 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002259 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002260 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002261 case OMPD_declare_target:
2262 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00002263 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00002264 llvm_unreachable("OpenMP Directive is not allowed");
2265 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002266 llvm_unreachable("Unknown OpenMP directive");
2267 }
2268}
2269
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002270int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2271 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2272 getOpenMPCaptureRegions(CaptureRegions, DKind);
2273 return CaptureRegions.size();
2274}
2275
Alexey Bataev3392d762016-02-16 11:18:12 +00002276static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002277 Expr *CaptureExpr, bool WithInit,
2278 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002279 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002280 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002281 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002282 QualType Ty = Init->getType();
2283 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2284 if (S.getLangOpts().CPlusPlus)
2285 Ty = C.getLValueReferenceType(Ty);
2286 else {
2287 Ty = C.getPointerType(Ty);
2288 ExprResult Res =
2289 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2290 if (!Res.isUsable())
2291 return nullptr;
2292 Init = Res.get();
2293 }
Alexey Bataev61205072016-03-02 04:57:40 +00002294 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002295 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002296 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2297 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002298 if (!WithInit)
2299 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002300 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002301 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002302 return CED;
2303}
2304
Alexey Bataev61205072016-03-02 04:57:40 +00002305static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2306 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002307 OMPCapturedExprDecl *CD;
2308 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2309 CD = cast<OMPCapturedExprDecl>(VD);
2310 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002311 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2312 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002313 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002314 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002315}
2316
Alexey Bataev5a3af132016-03-29 08:58:54 +00002317static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2318 if (!Ref) {
2319 auto *CD =
2320 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2321 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2322 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2323 CaptureExpr->getExprLoc());
2324 }
2325 ExprResult Res = Ref;
2326 if (!S.getLangOpts().CPlusPlus &&
2327 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2328 Ref->getType()->isPointerType())
2329 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2330 if (!Res.isUsable())
2331 return ExprError();
2332 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002333}
2334
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002335namespace {
2336// OpenMP directives parsed in this section are represented as a
2337// CapturedStatement with an associated statement. If a syntax error
2338// is detected during the parsing of the associated statement, the
2339// compiler must abort processing and close the CapturedStatement.
2340//
2341// Combined directives such as 'target parallel' have more than one
2342// nested CapturedStatements. This RAII ensures that we unwind out
2343// of all the nested CapturedStatements when an error is found.
2344class CaptureRegionUnwinderRAII {
2345private:
2346 Sema &S;
2347 bool &ErrorFound;
2348 OpenMPDirectiveKind DKind;
2349
2350public:
2351 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2352 OpenMPDirectiveKind DKind)
2353 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2354 ~CaptureRegionUnwinderRAII() {
2355 if (ErrorFound) {
2356 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2357 while (--ThisCaptureLevel >= 0)
2358 S.ActOnCapturedRegionError();
2359 }
2360 }
2361};
2362} // namespace
2363
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002364StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2365 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002366 bool ErrorFound = false;
2367 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2368 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002369 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002370 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002371 return StmtError();
2372 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002373
2374 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002375 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002376 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002377 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002378 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002379 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002380 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2381 Clause->getClauseKind() == OMPC_in_reduction) {
2382 // Capture taskgroup task_reduction descriptors inside the tasking regions
2383 // with the corresponding in_reduction items.
2384 auto *IRC = cast<OMPInReductionClause>(Clause);
2385 for (auto *E : IRC->taskgroup_descriptors())
2386 if (E)
2387 MarkDeclarationsReferencedInExpr(E);
2388 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002389 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002390 Clause->getClauseKind() == OMPC_copyprivate ||
2391 (getLangOpts().OpenMPUseTLS &&
2392 getASTContext().getTargetInfo().isTLSSupported() &&
2393 Clause->getClauseKind() == OMPC_copyin)) {
2394 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002395 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002396 for (auto *VarRef : Clause->children()) {
2397 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002398 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002399 }
2400 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002401 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002402 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002403 if (auto *C = OMPClauseWithPreInit::get(Clause))
2404 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002405 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2406 if (auto *E = C->getPostUpdateExpr())
2407 MarkDeclarationsReferencedInExpr(E);
2408 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002409 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002410 if (Clause->getClauseKind() == OMPC_schedule)
2411 SC = cast<OMPScheduleClause>(Clause);
2412 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002413 OC = cast<OMPOrderedClause>(Clause);
2414 else if (Clause->getClauseKind() == OMPC_linear)
2415 LCs.push_back(cast<OMPLinearClause>(Clause));
2416 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002417 // OpenMP, 2.7.1 Loop Construct, Restrictions
2418 // The nonmonotonic modifier cannot be specified if an ordered clause is
2419 // specified.
2420 if (SC &&
2421 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2422 SC->getSecondScheduleModifier() ==
2423 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2424 OC) {
2425 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2426 ? SC->getFirstScheduleModifierLoc()
2427 : SC->getSecondScheduleModifierLoc(),
2428 diag::err_omp_schedule_nonmonotonic_ordered)
2429 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2430 ErrorFound = true;
2431 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002432 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2433 for (auto *C : LCs) {
2434 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2435 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2436 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002437 ErrorFound = true;
2438 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002439 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2440 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2441 OC->getNumForLoops()) {
2442 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2443 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2444 ErrorFound = true;
2445 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002446 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002447 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002448 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002449 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002450 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2451 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2452 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2453 // Mark all variables in private list clauses as used in inner region.
2454 // Required for proper codegen of combined directives.
2455 // TODO: add processing for other clauses.
2456 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2457 for (auto *C : PICs) {
2458 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2459 // Find the particular capture region for the clause if the
2460 // directive is a combined one with multiple capture regions.
2461 // If the directive is not a combined one, the capture region
2462 // associated with the clause is OMPD_unknown and is generated
2463 // only once.
2464 if (CaptureRegion == ThisCaptureRegion ||
2465 CaptureRegion == OMPD_unknown) {
2466 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2467 for (auto *D : DS->decls())
2468 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2469 }
2470 }
2471 }
2472 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002473 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002474 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002475 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002476}
2477
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002478static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2479 OpenMPDirectiveKind CancelRegion,
2480 SourceLocation StartLoc) {
2481 // CancelRegion is only needed for cancel and cancellation_point.
2482 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2483 return false;
2484
2485 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2486 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2487 return false;
2488
2489 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2490 << getOpenMPDirectiveName(CancelRegion);
2491 return true;
2492}
2493
2494static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002495 OpenMPDirectiveKind CurrentRegion,
2496 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002497 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002498 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002499 if (Stack->getCurScope()) {
2500 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002501 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002502 bool NestingProhibited = false;
2503 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002504 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002505 enum {
2506 NoRecommend,
2507 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002508 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002509 ShouldBeInTargetRegion,
2510 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002511 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002512 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002513 // OpenMP [2.16, Nesting of Regions]
2514 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002515 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002516 // An ordered construct with the simd clause is the only OpenMP
2517 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002518 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002519 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2520 // message.
2521 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2522 ? diag::err_omp_prohibited_region_simd
2523 : diag::warn_omp_nesting_simd);
2524 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002525 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002526 if (ParentRegion == OMPD_atomic) {
2527 // OpenMP [2.16, Nesting of Regions]
2528 // OpenMP constructs may not be nested inside an atomic region.
2529 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2530 return true;
2531 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002532 if (CurrentRegion == OMPD_section) {
2533 // OpenMP [2.7.2, sections Construct, Restrictions]
2534 // Orphaned section directives are prohibited. That is, the section
2535 // directives must appear within the sections construct and must not be
2536 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002537 if (ParentRegion != OMPD_sections &&
2538 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002539 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2540 << (ParentRegion != OMPD_unknown)
2541 << getOpenMPDirectiveName(ParentRegion);
2542 return true;
2543 }
2544 return false;
2545 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002546 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002547 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002548 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002549 if (ParentRegion == OMPD_unknown &&
2550 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002551 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002552 if (CurrentRegion == OMPD_cancellation_point ||
2553 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002554 // OpenMP [2.16, Nesting of Regions]
2555 // A cancellation point construct for which construct-type-clause is
2556 // taskgroup must be nested inside a task construct. A cancellation
2557 // point construct for which construct-type-clause is not taskgroup must
2558 // be closely nested inside an OpenMP construct that matches the type
2559 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002560 // A cancel construct for which construct-type-clause is taskgroup must be
2561 // nested inside a task construct. A cancel construct for which
2562 // construct-type-clause is not taskgroup must be closely nested inside an
2563 // OpenMP construct that matches the type specified in
2564 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002565 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002566 !((CancelRegion == OMPD_parallel &&
2567 (ParentRegion == OMPD_parallel ||
2568 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002569 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002570 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2571 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002572 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2573 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002574 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2575 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002576 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002577 // OpenMP [2.16, Nesting of Regions]
2578 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002579 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002580 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002581 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002582 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2583 // OpenMP [2.16, Nesting of Regions]
2584 // A critical region may not be nested (closely or otherwise) inside a
2585 // critical region with the same name. Note that this restriction is not
2586 // sufficient to prevent deadlock.
2587 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002588 bool DeadLock = Stack->hasDirective(
2589 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2590 const DeclarationNameInfo &DNI,
2591 SourceLocation Loc) -> bool {
2592 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2593 PreviousCriticalLoc = Loc;
2594 return true;
2595 } else
2596 return false;
2597 },
2598 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002599 if (DeadLock) {
2600 SemaRef.Diag(StartLoc,
2601 diag::err_omp_prohibited_region_critical_same_name)
2602 << CurrentName.getName();
2603 if (PreviousCriticalLoc.isValid())
2604 SemaRef.Diag(PreviousCriticalLoc,
2605 diag::note_omp_previous_critical_region);
2606 return true;
2607 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002608 } else if (CurrentRegion == OMPD_barrier) {
2609 // OpenMP [2.16, Nesting of Regions]
2610 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002611 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002612 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2613 isOpenMPTaskingDirective(ParentRegion) ||
2614 ParentRegion == OMPD_master ||
2615 ParentRegion == OMPD_critical ||
2616 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002617 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002618 !isOpenMPParallelDirective(CurrentRegion) &&
2619 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002620 // OpenMP [2.16, Nesting of Regions]
2621 // A worksharing region may not be closely nested inside a worksharing,
2622 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002623 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2624 isOpenMPTaskingDirective(ParentRegion) ||
2625 ParentRegion == OMPD_master ||
2626 ParentRegion == OMPD_critical ||
2627 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002628 Recommend = ShouldBeInParallelRegion;
2629 } else if (CurrentRegion == OMPD_ordered) {
2630 // OpenMP [2.16, Nesting of Regions]
2631 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002632 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002633 // An ordered region must be closely nested inside a loop region (or
2634 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002635 // OpenMP [2.8.1,simd Construct, Restrictions]
2636 // An ordered construct with the simd clause is the only OpenMP construct
2637 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002638 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002639 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002640 !(isOpenMPSimdDirective(ParentRegion) ||
2641 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002642 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002643 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002644 // OpenMP [2.16, Nesting of Regions]
2645 // If specified, a teams construct must be contained within a target
2646 // construct.
2647 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002648 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002649 Recommend = ShouldBeInTargetRegion;
2650 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2651 }
Kelvin Libf594a52016-12-17 05:48:59 +00002652 if (!NestingProhibited &&
2653 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2654 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2655 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002656 // OpenMP [2.16, Nesting of Regions]
2657 // distribute, parallel, parallel sections, parallel workshare, and the
2658 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2659 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002660 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2661 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002662 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002663 }
David Majnemer9d168222016-08-05 17:44:54 +00002664 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002665 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002666 // OpenMP 4.5 [2.17 Nesting of Regions]
2667 // The region associated with the distribute construct must be strictly
2668 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002669 NestingProhibited =
2670 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002671 Recommend = ShouldBeInTeamsRegion;
2672 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002673 if (!NestingProhibited &&
2674 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2675 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2676 // OpenMP 4.5 [2.17 Nesting of Regions]
2677 // If a target, target update, target data, target enter data, or
2678 // target exit data construct is encountered during execution of a
2679 // target region, the behavior is unspecified.
2680 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002681 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2682 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002683 if (isOpenMPTargetExecutionDirective(K)) {
2684 OffendingRegion = K;
2685 return true;
2686 } else
2687 return false;
2688 },
2689 false /* don't skip top directive */);
2690 CloseNesting = false;
2691 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002692 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002693 if (OrphanSeen) {
2694 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2695 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2696 } else {
2697 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2698 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2699 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2700 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002701 return true;
2702 }
2703 }
2704 return false;
2705}
2706
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002707static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2708 ArrayRef<OMPClause *> Clauses,
2709 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2710 bool ErrorFound = false;
2711 unsigned NamedModifiersNumber = 0;
2712 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2713 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002714 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002715 for (const auto *C : Clauses) {
2716 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2717 // At most one if clause without a directive-name-modifier can appear on
2718 // the directive.
2719 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2720 if (FoundNameModifiers[CurNM]) {
2721 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2722 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2723 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2724 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002725 } else if (CurNM != OMPD_unknown) {
2726 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002727 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002728 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002729 FoundNameModifiers[CurNM] = IC;
2730 if (CurNM == OMPD_unknown)
2731 continue;
2732 // Check if the specified name modifier is allowed for the current
2733 // directive.
2734 // At most one if clause with the particular directive-name-modifier can
2735 // appear on the directive.
2736 bool MatchFound = false;
2737 for (auto NM : AllowedNameModifiers) {
2738 if (CurNM == NM) {
2739 MatchFound = true;
2740 break;
2741 }
2742 }
2743 if (!MatchFound) {
2744 S.Diag(IC->getNameModifierLoc(),
2745 diag::err_omp_wrong_if_directive_name_modifier)
2746 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2747 ErrorFound = true;
2748 }
2749 }
2750 }
2751 // If any if clause on the directive includes a directive-name-modifier then
2752 // all if clauses on the directive must include a directive-name-modifier.
2753 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2754 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2755 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2756 diag::err_omp_no_more_if_clause);
2757 } else {
2758 std::string Values;
2759 std::string Sep(", ");
2760 unsigned AllowedCnt = 0;
2761 unsigned TotalAllowedNum =
2762 AllowedNameModifiers.size() - NamedModifiersNumber;
2763 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2764 ++Cnt) {
2765 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2766 if (!FoundNameModifiers[NM]) {
2767 Values += "'";
2768 Values += getOpenMPDirectiveName(NM);
2769 Values += "'";
2770 if (AllowedCnt + 2 == TotalAllowedNum)
2771 Values += " or ";
2772 else if (AllowedCnt + 1 != TotalAllowedNum)
2773 Values += Sep;
2774 ++AllowedCnt;
2775 }
2776 }
2777 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2778 diag::err_omp_unnamed_if_clause)
2779 << (TotalAllowedNum > 1) << Values;
2780 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002781 for (auto Loc : NameModifierLoc) {
2782 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2783 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002784 ErrorFound = true;
2785 }
2786 return ErrorFound;
2787}
2788
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002789StmtResult Sema::ActOnOpenMPExecutableDirective(
2790 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2791 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2792 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002793 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002794 // First check CancelRegion which is then used in checkNestingOfRegions.
2795 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2796 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002797 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002798 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002799
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002800 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002801 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002802 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002803 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002804 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002805 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2806
2807 // Check default data sharing attributes for referenced variables.
2808 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002809 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2810 Stmt *S = AStmt;
2811 while (--ThisCaptureLevel >= 0)
2812 S = cast<CapturedStmt>(S)->getCapturedStmt();
2813 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002814 if (DSAChecker.isErrorFound())
2815 return StmtError();
2816 // Generate list of implicitly defined firstprivate variables.
2817 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002818
Alexey Bataev88202be2017-07-27 13:20:36 +00002819 SmallVector<Expr *, 4> ImplicitFirstprivates(
2820 DSAChecker.getImplicitFirstprivate().begin(),
2821 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002822 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2823 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002824 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2825 for (auto *C : Clauses) {
2826 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2827 for (auto *E : IRC->taskgroup_descriptors())
2828 if (E)
2829 ImplicitFirstprivates.emplace_back(E);
2830 }
2831 }
2832 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002833 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002834 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2835 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002836 ClausesWithImplicit.push_back(Implicit);
2837 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002838 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002839 } else
2840 ErrorFound = true;
2841 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002842 if (!ImplicitMaps.empty()) {
2843 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2844 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2845 SourceLocation(), SourceLocation(), ImplicitMaps,
2846 SourceLocation(), SourceLocation(), SourceLocation())) {
2847 ClausesWithImplicit.emplace_back(Implicit);
2848 ErrorFound |=
2849 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2850 } else
2851 ErrorFound = true;
2852 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002853 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002854
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002855 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002856 switch (Kind) {
2857 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002858 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2859 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002860 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002861 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002862 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002863 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2864 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002865 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002866 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002867 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2868 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002869 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002870 case OMPD_for_simd:
2871 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2872 EndLoc, VarsWithInheritedDSA);
2873 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002874 case OMPD_sections:
2875 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2876 EndLoc);
2877 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002878 case OMPD_section:
2879 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002880 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002881 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2882 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002883 case OMPD_single:
2884 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2885 EndLoc);
2886 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002887 case OMPD_master:
2888 assert(ClausesWithImplicit.empty() &&
2889 "No clauses are allowed for 'omp master' directive");
2890 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2891 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002892 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002893 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2894 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002895 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002896 case OMPD_parallel_for:
2897 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2898 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002899 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002900 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002901 case OMPD_parallel_for_simd:
2902 Res = ActOnOpenMPParallelForSimdDirective(
2903 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002904 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002905 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002906 case OMPD_parallel_sections:
2907 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2908 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002909 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002910 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002911 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002912 Res =
2913 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002914 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002915 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002916 case OMPD_taskyield:
2917 assert(ClausesWithImplicit.empty() &&
2918 "No clauses are allowed for 'omp taskyield' directive");
2919 assert(AStmt == nullptr &&
2920 "No associated statement allowed for 'omp taskyield' directive");
2921 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2922 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002923 case OMPD_barrier:
2924 assert(ClausesWithImplicit.empty() &&
2925 "No clauses are allowed for 'omp barrier' directive");
2926 assert(AStmt == nullptr &&
2927 "No associated statement allowed for 'omp barrier' directive");
2928 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2929 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002930 case OMPD_taskwait:
2931 assert(ClausesWithImplicit.empty() &&
2932 "No clauses are allowed for 'omp taskwait' directive");
2933 assert(AStmt == nullptr &&
2934 "No associated statement allowed for 'omp taskwait' directive");
2935 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2936 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002937 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002938 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2939 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002940 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002941 case OMPD_flush:
2942 assert(AStmt == nullptr &&
2943 "No associated statement allowed for 'omp flush' directive");
2944 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2945 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002946 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002947 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2948 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002949 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002950 case OMPD_atomic:
2951 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2952 EndLoc);
2953 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002954 case OMPD_teams:
2955 Res =
2956 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2957 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002958 case OMPD_target:
2959 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2960 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002961 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002962 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002963 case OMPD_target_parallel:
2964 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2965 StartLoc, EndLoc);
2966 AllowedNameModifiers.push_back(OMPD_target);
2967 AllowedNameModifiers.push_back(OMPD_parallel);
2968 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002969 case OMPD_target_parallel_for:
2970 Res = ActOnOpenMPTargetParallelForDirective(
2971 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2972 AllowedNameModifiers.push_back(OMPD_target);
2973 AllowedNameModifiers.push_back(OMPD_parallel);
2974 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002975 case OMPD_cancellation_point:
2976 assert(ClausesWithImplicit.empty() &&
2977 "No clauses are allowed for 'omp cancellation point' directive");
2978 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2979 "cancellation point' directive");
2980 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2981 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002982 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002983 assert(AStmt == nullptr &&
2984 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002985 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2986 CancelRegion);
2987 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002988 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002989 case OMPD_target_data:
2990 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2991 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002992 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002993 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002994 case OMPD_target_enter_data:
2995 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2996 EndLoc);
2997 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2998 break;
Samuel Antao72590762016-01-19 20:04:50 +00002999 case OMPD_target_exit_data:
3000 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3001 EndLoc);
3002 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3003 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003004 case OMPD_taskloop:
3005 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3006 EndLoc, VarsWithInheritedDSA);
3007 AllowedNameModifiers.push_back(OMPD_taskloop);
3008 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003009 case OMPD_taskloop_simd:
3010 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3011 EndLoc, VarsWithInheritedDSA);
3012 AllowedNameModifiers.push_back(OMPD_taskloop);
3013 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003014 case OMPD_distribute:
3015 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3016 EndLoc, VarsWithInheritedDSA);
3017 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003018 case OMPD_target_update:
3019 assert(!AStmt && "Statement is not allowed for target update");
3020 Res =
3021 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
3022 AllowedNameModifiers.push_back(OMPD_target_update);
3023 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003024 case OMPD_distribute_parallel_for:
3025 Res = ActOnOpenMPDistributeParallelForDirective(
3026 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3027 AllowedNameModifiers.push_back(OMPD_parallel);
3028 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003029 case OMPD_distribute_parallel_for_simd:
3030 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3031 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3032 AllowedNameModifiers.push_back(OMPD_parallel);
3033 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003034 case OMPD_distribute_simd:
3035 Res = ActOnOpenMPDistributeSimdDirective(
3036 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3037 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003038 case OMPD_target_parallel_for_simd:
3039 Res = ActOnOpenMPTargetParallelForSimdDirective(
3040 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3041 AllowedNameModifiers.push_back(OMPD_target);
3042 AllowedNameModifiers.push_back(OMPD_parallel);
3043 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003044 case OMPD_target_simd:
3045 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3046 EndLoc, VarsWithInheritedDSA);
3047 AllowedNameModifiers.push_back(OMPD_target);
3048 break;
Kelvin Li02532872016-08-05 14:37:37 +00003049 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003050 Res = ActOnOpenMPTeamsDistributeDirective(
3051 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003052 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003053 case OMPD_teams_distribute_simd:
3054 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3055 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3056 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003057 case OMPD_teams_distribute_parallel_for_simd:
3058 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3059 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3060 AllowedNameModifiers.push_back(OMPD_parallel);
3061 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003062 case OMPD_teams_distribute_parallel_for:
3063 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3064 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3065 AllowedNameModifiers.push_back(OMPD_parallel);
3066 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003067 case OMPD_target_teams:
3068 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3069 EndLoc);
3070 AllowedNameModifiers.push_back(OMPD_target);
3071 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003072 case OMPD_target_teams_distribute:
3073 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3074 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3075 AllowedNameModifiers.push_back(OMPD_target);
3076 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003077 case OMPD_target_teams_distribute_parallel_for:
3078 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3079 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3080 AllowedNameModifiers.push_back(OMPD_target);
3081 AllowedNameModifiers.push_back(OMPD_parallel);
3082 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003083 case OMPD_target_teams_distribute_parallel_for_simd:
3084 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3085 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3086 AllowedNameModifiers.push_back(OMPD_target);
3087 AllowedNameModifiers.push_back(OMPD_parallel);
3088 break;
Kelvin Lida681182017-01-10 18:08:18 +00003089 case OMPD_target_teams_distribute_simd:
3090 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3091 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3092 AllowedNameModifiers.push_back(OMPD_target);
3093 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003094 case OMPD_declare_target:
3095 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003096 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003097 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003098 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003099 llvm_unreachable("OpenMP Directive is not allowed");
3100 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003101 llvm_unreachable("Unknown OpenMP directive");
3102 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003103
Alexey Bataev4acb8592014-07-07 13:01:15 +00003104 for (auto P : VarsWithInheritedDSA) {
3105 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3106 << P.first << P.second->getSourceRange();
3107 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003108 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3109
3110 if (!AllowedNameModifiers.empty())
3111 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3112 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003113
Alexey Bataeved09d242014-05-28 05:53:51 +00003114 if (ErrorFound)
3115 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003116 return Res;
3117}
3118
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003119Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3120 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003121 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003122 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3123 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003124 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003125 assert(Linears.size() == LinModifiers.size());
3126 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003127 if (!DG || DG.get().isNull())
3128 return DeclGroupPtrTy();
3129
3130 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003131 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003132 return DG;
3133 }
3134 auto *ADecl = DG.get().getSingleDecl();
3135 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3136 ADecl = FTD->getTemplatedDecl();
3137
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003138 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3139 if (!FD) {
3140 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003141 return DeclGroupPtrTy();
3142 }
3143
Alexey Bataev2af33e32016-04-07 12:45:37 +00003144 // OpenMP [2.8.2, declare simd construct, Description]
3145 // The parameter of the simdlen clause must be a constant positive integer
3146 // expression.
3147 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003148 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003149 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003150 // OpenMP [2.8.2, declare simd construct, Description]
3151 // The special this pointer can be used as if was one of the arguments to the
3152 // function in any of the linear, aligned, or uniform clauses.
3153 // The uniform clause declares one or more arguments to have an invariant
3154 // value for all concurrent invocations of the function in the execution of a
3155 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003156 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3157 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003158 for (auto *E : Uniforms) {
3159 E = E->IgnoreParenImpCasts();
3160 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3161 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3162 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3163 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003164 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3165 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003166 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003167 }
3168 if (isa<CXXThisExpr>(E)) {
3169 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003170 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003171 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003172 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3173 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003174 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003175 // OpenMP [2.8.2, declare simd construct, Description]
3176 // The aligned clause declares that the object to which each list item points
3177 // is aligned to the number of bytes expressed in the optional parameter of
3178 // the aligned clause.
3179 // The special this pointer can be used as if was one of the arguments to the
3180 // function in any of the linear, aligned, or uniform clauses.
3181 // The type of list items appearing in the aligned clause must be array,
3182 // pointer, reference to array, or reference to pointer.
3183 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3184 Expr *AlignedThis = nullptr;
3185 for (auto *E : Aligneds) {
3186 E = E->IgnoreParenImpCasts();
3187 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3188 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3189 auto *CanonPVD = PVD->getCanonicalDecl();
3190 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3191 FD->getParamDecl(PVD->getFunctionScopeIndex())
3192 ->getCanonicalDecl() == CanonPVD) {
3193 // OpenMP [2.8.1, simd construct, Restrictions]
3194 // A list-item cannot appear in more than one aligned clause.
3195 if (AlignedArgs.count(CanonPVD) > 0) {
3196 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3197 << 1 << E->getSourceRange();
3198 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3199 diag::note_omp_explicit_dsa)
3200 << getOpenMPClauseName(OMPC_aligned);
3201 continue;
3202 }
3203 AlignedArgs[CanonPVD] = E;
3204 QualType QTy = PVD->getType()
3205 .getNonReferenceType()
3206 .getUnqualifiedType()
3207 .getCanonicalType();
3208 const Type *Ty = QTy.getTypePtrOrNull();
3209 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3210 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3211 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3212 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3213 }
3214 continue;
3215 }
3216 }
3217 if (isa<CXXThisExpr>(E)) {
3218 if (AlignedThis) {
3219 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3220 << 2 << E->getSourceRange();
3221 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3222 << getOpenMPClauseName(OMPC_aligned);
3223 }
3224 AlignedThis = E;
3225 continue;
3226 }
3227 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3228 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3229 }
3230 // The optional parameter of the aligned clause, alignment, must be a constant
3231 // positive integer expression. If no optional parameter is specified,
3232 // implementation-defined default alignments for SIMD instructions on the
3233 // target platforms are assumed.
3234 SmallVector<Expr *, 4> NewAligns;
3235 for (auto *E : Alignments) {
3236 ExprResult Align;
3237 if (E)
3238 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3239 NewAligns.push_back(Align.get());
3240 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003241 // OpenMP [2.8.2, declare simd construct, Description]
3242 // The linear clause declares one or more list items to be private to a SIMD
3243 // lane and to have a linear relationship with respect to the iteration space
3244 // of a loop.
3245 // The special this pointer can be used as if was one of the arguments to the
3246 // function in any of the linear, aligned, or uniform clauses.
3247 // When a linear-step expression is specified in a linear clause it must be
3248 // either a constant integer expression or an integer-typed parameter that is
3249 // specified in a uniform clause on the directive.
3250 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3251 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3252 auto MI = LinModifiers.begin();
3253 for (auto *E : Linears) {
3254 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3255 ++MI;
3256 E = E->IgnoreParenImpCasts();
3257 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3258 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3259 auto *CanonPVD = PVD->getCanonicalDecl();
3260 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3261 FD->getParamDecl(PVD->getFunctionScopeIndex())
3262 ->getCanonicalDecl() == CanonPVD) {
3263 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3264 // A list-item cannot appear in more than one linear clause.
3265 if (LinearArgs.count(CanonPVD) > 0) {
3266 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3267 << getOpenMPClauseName(OMPC_linear)
3268 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3269 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3270 diag::note_omp_explicit_dsa)
3271 << getOpenMPClauseName(OMPC_linear);
3272 continue;
3273 }
3274 // Each argument can appear in at most one uniform or linear clause.
3275 if (UniformedArgs.count(CanonPVD) > 0) {
3276 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3277 << getOpenMPClauseName(OMPC_linear)
3278 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3279 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3280 diag::note_omp_explicit_dsa)
3281 << getOpenMPClauseName(OMPC_uniform);
3282 continue;
3283 }
3284 LinearArgs[CanonPVD] = E;
3285 if (E->isValueDependent() || E->isTypeDependent() ||
3286 E->isInstantiationDependent() ||
3287 E->containsUnexpandedParameterPack())
3288 continue;
3289 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3290 PVD->getOriginalType());
3291 continue;
3292 }
3293 }
3294 if (isa<CXXThisExpr>(E)) {
3295 if (UniformedLinearThis) {
3296 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3297 << getOpenMPClauseName(OMPC_linear)
3298 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3299 << E->getSourceRange();
3300 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3301 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3302 : OMPC_linear);
3303 continue;
3304 }
3305 UniformedLinearThis = E;
3306 if (E->isValueDependent() || E->isTypeDependent() ||
3307 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3308 continue;
3309 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3310 E->getType());
3311 continue;
3312 }
3313 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3314 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3315 }
3316 Expr *Step = nullptr;
3317 Expr *NewStep = nullptr;
3318 SmallVector<Expr *, 4> NewSteps;
3319 for (auto *E : Steps) {
3320 // Skip the same step expression, it was checked already.
3321 if (Step == E || !E) {
3322 NewSteps.push_back(E ? NewStep : nullptr);
3323 continue;
3324 }
3325 Step = E;
3326 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3327 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3328 auto *CanonPVD = PVD->getCanonicalDecl();
3329 if (UniformedArgs.count(CanonPVD) == 0) {
3330 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3331 << Step->getSourceRange();
3332 } else if (E->isValueDependent() || E->isTypeDependent() ||
3333 E->isInstantiationDependent() ||
3334 E->containsUnexpandedParameterPack() ||
3335 CanonPVD->getType()->hasIntegerRepresentation())
3336 NewSteps.push_back(Step);
3337 else {
3338 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3339 << Step->getSourceRange();
3340 }
3341 continue;
3342 }
3343 NewStep = Step;
3344 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3345 !Step->isInstantiationDependent() &&
3346 !Step->containsUnexpandedParameterPack()) {
3347 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3348 .get();
3349 if (NewStep)
3350 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3351 }
3352 NewSteps.push_back(NewStep);
3353 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003354 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3355 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003356 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003357 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3358 const_cast<Expr **>(Linears.data()), Linears.size(),
3359 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3360 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003361 ADecl->addAttr(NewAttr);
3362 return ConvertDeclToDeclGroup(ADecl);
3363}
3364
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003365StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3366 Stmt *AStmt,
3367 SourceLocation StartLoc,
3368 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003369 if (!AStmt)
3370 return StmtError();
3371
Alexey Bataev9959db52014-05-06 10:08:46 +00003372 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3373 // 1.2.2 OpenMP Language Terminology
3374 // Structured block - An executable statement with a single entry at the
3375 // top and a single exit at the bottom.
3376 // The point of exit cannot be a branch out of the structured block.
3377 // longjmp() and throw() must not violate the entry/exit criteria.
3378 CS->getCapturedDecl()->setNothrow();
3379
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003380 getCurFunction()->setHasBranchProtectedScope();
3381
Alexey Bataev25e5b442015-09-15 12:52:43 +00003382 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3383 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003384}
3385
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003386namespace {
3387/// \brief Helper class for checking canonical form of the OpenMP loops and
3388/// extracting iteration space of each loop in the loop nest, that will be used
3389/// for IR generation.
3390class OpenMPIterationSpaceChecker {
3391 /// \brief Reference to Sema.
3392 Sema &SemaRef;
3393 /// \brief A location for diagnostics (when there is no some better location).
3394 SourceLocation DefaultLoc;
3395 /// \brief A location for diagnostics (when increment is not compatible).
3396 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003397 /// \brief A source location for referring to loop init later.
3398 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003399 /// \brief A source location for referring to condition later.
3400 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003401 /// \brief A source location for referring to increment later.
3402 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003403 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003404 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003405 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003406 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003407 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003408 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003409 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003410 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003411 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003412 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003413 /// \brief This flag is true when condition is one of:
3414 /// Var < UB
3415 /// Var <= UB
3416 /// UB > Var
3417 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003418 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003419 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003420 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003421 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003422 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003423
3424public:
3425 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003426 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003427 /// \brief Check init-expr for canonical loop form and save loop counter
3428 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003429 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003430 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3431 /// for less/greater and for strict/non-strict comparison.
3432 bool CheckCond(Expr *S);
3433 /// \brief Check incr-expr for canonical loop form and return true if it
3434 /// does not conform, otherwise save loop step (#Step).
3435 bool CheckInc(Expr *S);
3436 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003437 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003438 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003439 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003440 /// \brief Source range of the loop init.
3441 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3442 /// \brief Source range of the loop condition.
3443 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3444 /// \brief Source range of the loop increment.
3445 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3446 /// \brief True if the step should be subtracted.
3447 bool ShouldSubtractStep() const { return SubtractStep; }
3448 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003449 Expr *
3450 BuildNumIterations(Scope *S, const bool LimitedType,
3451 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003452 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003453 Expr *BuildPreCond(Scope *S, Expr *Cond,
3454 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003455 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003456 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3457 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003458 /// \brief Build reference expression to the private counter be used for
3459 /// codegen.
3460 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003461 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003462 Expr *BuildCounterInit() const;
3463 /// \brief Build step of the counter be used for codegen.
3464 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003465 /// \brief Return true if any expression is dependent.
3466 bool Dependent() const;
3467
3468private:
3469 /// \brief Check the right-hand side of an assignment in the increment
3470 /// expression.
3471 bool CheckIncRHS(Expr *RHS);
3472 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003473 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003474 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003475 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003476 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003477 /// \brief Helper to set loop increment.
3478 bool SetStep(Expr *NewStep, bool Subtract);
3479};
3480
3481bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003482 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003483 assert(!LB && !UB && !Step);
3484 return false;
3485 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003486 return LCDecl->getType()->isDependentType() ||
3487 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3488 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003489}
3490
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003491bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3492 Expr *NewLCRefExpr,
3493 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003494 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003495 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003496 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003497 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003498 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003499 LCDecl = getCanonicalDecl(NewLCDecl);
3500 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003501 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3502 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003503 if ((Ctor->isCopyOrMoveConstructor() ||
3504 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3505 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003506 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003507 LB = NewLB;
3508 return false;
3509}
3510
3511bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003512 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003513 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003514 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3515 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003516 if (!NewUB)
3517 return true;
3518 UB = NewUB;
3519 TestIsLessOp = LessOp;
3520 TestIsStrictOp = StrictOp;
3521 ConditionSrcRange = SR;
3522 ConditionLoc = SL;
3523 return false;
3524}
3525
3526bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3527 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003528 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003529 if (!NewStep)
3530 return true;
3531 if (!NewStep->isValueDependent()) {
3532 // Check that the step is integer expression.
3533 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003534 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3535 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003536 if (Val.isInvalid())
3537 return true;
3538 NewStep = Val.get();
3539
3540 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3541 // If test-expr is of form var relational-op b and relational-op is < or
3542 // <= then incr-expr must cause var to increase on each iteration of the
3543 // loop. If test-expr is of form var relational-op b and relational-op is
3544 // > or >= then incr-expr must cause var to decrease on each iteration of
3545 // the loop.
3546 // If test-expr is of form b relational-op var and relational-op is < or
3547 // <= then incr-expr must cause var to decrease on each iteration of the
3548 // loop. If test-expr is of form b relational-op var and relational-op is
3549 // > or >= then incr-expr must cause var to increase on each iteration of
3550 // the loop.
3551 llvm::APSInt Result;
3552 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3553 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3554 bool IsConstNeg =
3555 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003556 bool IsConstPos =
3557 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003558 bool IsConstZero = IsConstant && !Result.getBoolValue();
3559 if (UB && (IsConstZero ||
3560 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003561 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003562 SemaRef.Diag(NewStep->getExprLoc(),
3563 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003564 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003565 SemaRef.Diag(ConditionLoc,
3566 diag::note_omp_loop_cond_requres_compatible_incr)
3567 << TestIsLessOp << ConditionSrcRange;
3568 return true;
3569 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003570 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003571 NewStep =
3572 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3573 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003574 Subtract = !Subtract;
3575 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003576 }
3577
3578 Step = NewStep;
3579 SubtractStep = Subtract;
3580 return false;
3581}
3582
Alexey Bataev9c821032015-04-30 04:23:23 +00003583bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003584 // Check init-expr for canonical loop form and save loop counter
3585 // variable - #Var and its initialization value - #LB.
3586 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3587 // var = lb
3588 // integer-type var = lb
3589 // random-access-iterator-type var = lb
3590 // pointer-type var = lb
3591 //
3592 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003593 if (EmitDiags) {
3594 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3595 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003596 return true;
3597 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003598 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3599 if (!ExprTemp->cleanupsHaveSideEffects())
3600 S = ExprTemp->getSubExpr();
3601
Alexander Musmana5f070a2014-10-01 06:03:56 +00003602 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003603 if (Expr *E = dyn_cast<Expr>(S))
3604 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003605 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003606 if (BO->getOpcode() == BO_Assign) {
3607 auto *LHS = BO->getLHS()->IgnoreParens();
3608 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3609 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3610 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3611 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3612 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3613 }
3614 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3615 if (ME->isArrow() &&
3616 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3617 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3618 }
3619 }
David Majnemer9d168222016-08-05 17:44:54 +00003620 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003621 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003622 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003623 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003624 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003625 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003626 SemaRef.Diag(S->getLocStart(),
3627 diag::ext_omp_loop_not_canonical_init)
3628 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003629 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003630 }
3631 }
3632 }
David Majnemer9d168222016-08-05 17:44:54 +00003633 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003634 if (CE->getOperator() == OO_Equal) {
3635 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003636 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003637 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3638 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3639 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3640 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3641 }
3642 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3643 if (ME->isArrow() &&
3644 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3645 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3646 }
3647 }
3648 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003649
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003650 if (Dependent() || SemaRef.CurContext->isDependentContext())
3651 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003652 if (EmitDiags) {
3653 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3654 << S->getSourceRange();
3655 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003656 return true;
3657}
3658
Alexey Bataev23b69422014-06-18 07:08:49 +00003659/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003660/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003661static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003662 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003663 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003664 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003665 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3666 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003667 if ((Ctor->isCopyOrMoveConstructor() ||
3668 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3669 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003670 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003671 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003672 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003673 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003674 }
3675 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3676 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3677 return getCanonicalDecl(ME->getMemberDecl());
3678 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003679}
3680
3681bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3682 // Check test-expr for canonical form, save upper-bound UB, flags for
3683 // less/greater and for strict/non-strict comparison.
3684 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3685 // var relational-op b
3686 // b relational-op var
3687 //
3688 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003689 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003690 return true;
3691 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003692 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003693 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003694 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003695 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003696 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003697 return SetUB(BO->getRHS(),
3698 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3699 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3700 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003701 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003702 return SetUB(BO->getLHS(),
3703 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3704 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3705 BO->getSourceRange(), BO->getOperatorLoc());
3706 }
David Majnemer9d168222016-08-05 17:44:54 +00003707 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003708 if (CE->getNumArgs() == 2) {
3709 auto Op = CE->getOperator();
3710 switch (Op) {
3711 case OO_Greater:
3712 case OO_GreaterEqual:
3713 case OO_Less:
3714 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003715 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003716 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3717 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3718 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003719 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003720 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3721 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3722 CE->getOperatorLoc());
3723 break;
3724 default:
3725 break;
3726 }
3727 }
3728 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003729 if (Dependent() || SemaRef.CurContext->isDependentContext())
3730 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003731 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003732 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003733 return true;
3734}
3735
3736bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3737 // RHS of canonical loop form increment can be:
3738 // var + incr
3739 // incr + var
3740 // var - incr
3741 //
3742 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003743 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003744 if (BO->isAdditiveOp()) {
3745 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003746 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003747 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003748 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003749 return SetStep(BO->getLHS(), false);
3750 }
David Majnemer9d168222016-08-05 17:44:54 +00003751 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003752 bool IsAdd = CE->getOperator() == OO_Plus;
3753 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003754 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003755 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003756 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003757 return SetStep(CE->getArg(0), false);
3758 }
3759 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003760 if (Dependent() || SemaRef.CurContext->isDependentContext())
3761 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003762 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003763 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003764 return true;
3765}
3766
3767bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3768 // Check incr-expr for canonical loop form and return true if it
3769 // does not conform.
3770 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3771 // ++var
3772 // var++
3773 // --var
3774 // var--
3775 // var += incr
3776 // var -= incr
3777 // var = var + incr
3778 // var = incr + var
3779 // var = var - incr
3780 //
3781 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003782 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003783 return true;
3784 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003785 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3786 if (!ExprTemp->cleanupsHaveSideEffects())
3787 S = ExprTemp->getSubExpr();
3788
Alexander Musmana5f070a2014-10-01 06:03:56 +00003789 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003790 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003791 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003792 if (UO->isIncrementDecrementOp() &&
3793 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003794 return SetStep(SemaRef
3795 .ActOnIntegerConstant(UO->getLocStart(),
3796 (UO->isDecrementOp() ? -1 : 1))
3797 .get(),
3798 false);
3799 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003800 switch (BO->getOpcode()) {
3801 case BO_AddAssign:
3802 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003803 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003804 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3805 break;
3806 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003807 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003808 return CheckIncRHS(BO->getRHS());
3809 break;
3810 default:
3811 break;
3812 }
David Majnemer9d168222016-08-05 17:44:54 +00003813 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003814 switch (CE->getOperator()) {
3815 case OO_PlusPlus:
3816 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003817 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003818 return SetStep(SemaRef
3819 .ActOnIntegerConstant(
3820 CE->getLocStart(),
3821 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3822 .get(),
3823 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003824 break;
3825 case OO_PlusEqual:
3826 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003827 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003828 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3829 break;
3830 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003831 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003832 return CheckIncRHS(CE->getArg(1));
3833 break;
3834 default:
3835 break;
3836 }
3837 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003838 if (Dependent() || SemaRef.CurContext->isDependentContext())
3839 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003840 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003841 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003842 return true;
3843}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003844
Alexey Bataev5a3af132016-03-29 08:58:54 +00003845static ExprResult
3846tryBuildCapture(Sema &SemaRef, Expr *Capture,
3847 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003848 if (SemaRef.CurContext->isDependentContext())
3849 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003850 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3851 return SemaRef.PerformImplicitConversion(
3852 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3853 /*AllowExplicit=*/true);
3854 auto I = Captures.find(Capture);
3855 if (I != Captures.end())
3856 return buildCapture(SemaRef, Capture, I->second);
3857 DeclRefExpr *Ref = nullptr;
3858 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3859 Captures[Capture] = Ref;
3860 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003861}
3862
Alexander Musmana5f070a2014-10-01 06:03:56 +00003863/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003864Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3865 Scope *S, const bool LimitedType,
3866 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003867 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003868 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003869 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003870 SemaRef.getLangOpts().CPlusPlus) {
3871 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003872 auto *UBExpr = TestIsLessOp ? UB : LB;
3873 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003874 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3875 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003876 if (!Upper || !Lower)
3877 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003878
3879 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3880
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003881 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003882 // BuildBinOp already emitted error, this one is to point user to upper
3883 // and lower bound, and to tell what is passed to 'operator-'.
3884 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3885 << Upper->getSourceRange() << Lower->getSourceRange();
3886 return nullptr;
3887 }
3888 }
3889
3890 if (!Diff.isUsable())
3891 return nullptr;
3892
3893 // Upper - Lower [- 1]
3894 if (TestIsStrictOp)
3895 Diff = SemaRef.BuildBinOp(
3896 S, DefaultLoc, BO_Sub, Diff.get(),
3897 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3898 if (!Diff.isUsable())
3899 return nullptr;
3900
3901 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003902 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3903 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003904 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003905 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003906 if (!Diff.isUsable())
3907 return nullptr;
3908
3909 // Parentheses (for dumping/debugging purposes only).
3910 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3911 if (!Diff.isUsable())
3912 return nullptr;
3913
3914 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003915 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003916 if (!Diff.isUsable())
3917 return nullptr;
3918
Alexander Musman174b3ca2014-10-06 11:16:29 +00003919 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003920 QualType Type = Diff.get()->getType();
3921 auto &C = SemaRef.Context;
3922 bool UseVarType = VarType->hasIntegerRepresentation() &&
3923 C.getTypeSize(Type) > C.getTypeSize(VarType);
3924 if (!Type->isIntegerType() || UseVarType) {
3925 unsigned NewSize =
3926 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3927 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3928 : Type->hasSignedIntegerRepresentation();
3929 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003930 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3931 Diff = SemaRef.PerformImplicitConversion(
3932 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3933 if (!Diff.isUsable())
3934 return nullptr;
3935 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003936 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003937 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003938 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3939 if (NewSize != C.getTypeSize(Type)) {
3940 if (NewSize < C.getTypeSize(Type)) {
3941 assert(NewSize == 64 && "incorrect loop var size");
3942 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3943 << InitSrcRange << ConditionSrcRange;
3944 }
3945 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003946 NewSize, Type->hasSignedIntegerRepresentation() ||
3947 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003948 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3949 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3950 Sema::AA_Converting, true);
3951 if (!Diff.isUsable())
3952 return nullptr;
3953 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003954 }
3955 }
3956
Alexander Musmana5f070a2014-10-01 06:03:56 +00003957 return Diff.get();
3958}
3959
Alexey Bataev5a3af132016-03-29 08:58:54 +00003960Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3961 Scope *S, Expr *Cond,
3962 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003963 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3964 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3965 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003966
Alexey Bataev5a3af132016-03-29 08:58:54 +00003967 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3968 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3969 if (!NewLB.isUsable() || !NewUB.isUsable())
3970 return nullptr;
3971
Alexey Bataev62dbb972015-04-22 11:59:37 +00003972 auto CondExpr = SemaRef.BuildBinOp(
3973 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3974 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003975 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003976 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003977 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3978 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003979 CondExpr = SemaRef.PerformImplicitConversion(
3980 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3981 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003982 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003983 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3984 // Otherwise use original loop conditon and evaluate it in runtime.
3985 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3986}
3987
Alexander Musmana5f070a2014-10-01 06:03:56 +00003988/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003989DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003990 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003991 auto *VD = dyn_cast<VarDecl>(LCDecl);
3992 if (!VD) {
3993 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3994 auto *Ref = buildDeclRefExpr(
3995 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003996 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3997 // If the loop control decl is explicitly marked as private, do not mark it
3998 // as captured again.
3999 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4000 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004001 return Ref;
4002 }
4003 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004004 DefaultLoc);
4005}
4006
4007Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004008 if (LCDecl && !LCDecl->isInvalidDecl()) {
4009 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004010 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004011 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4012 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004013 if (PrivateVar->isInvalidDecl())
4014 return nullptr;
4015 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4016 }
4017 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004018}
4019
Samuel Antao4c8035b2016-12-12 18:00:20 +00004020/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004021Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4022
4023/// \brief Build step of the counter be used for codegen.
4024Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4025
4026/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004027struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004028 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004029 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004030 /// \brief This expression calculates the number of iterations in the loop.
4031 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004032 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004033 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004034 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004035 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004036 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004037 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004038 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004039 /// \brief This is step for the #CounterVar used to generate its update:
4040 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004041 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004042 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004043 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004044 /// \brief Source range of the loop init.
4045 SourceRange InitSrcRange;
4046 /// \brief Source range of the loop condition.
4047 SourceRange CondSrcRange;
4048 /// \brief Source range of the loop increment.
4049 SourceRange IncSrcRange;
4050};
4051
Alexey Bataev23b69422014-06-18 07:08:49 +00004052} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004053
Alexey Bataev9c821032015-04-30 04:23:23 +00004054void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4055 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4056 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004057 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4058 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004059 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4060 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004061 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4062 if (auto *D = ISC.GetLoopDecl()) {
4063 auto *VD = dyn_cast<VarDecl>(D);
4064 if (!VD) {
4065 if (auto *Private = IsOpenMPCapturedDecl(D))
4066 VD = Private;
4067 else {
4068 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4069 /*WithInit=*/false);
4070 VD = cast<VarDecl>(Ref->getDecl());
4071 }
4072 }
4073 DSAStack->addLoopControlVariable(D, VD);
4074 }
4075 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004076 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004077 }
4078}
4079
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004080/// \brief Called on a for stmt to check and extract its iteration space
4081/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004082static bool CheckOpenMPIterationSpace(
4083 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4084 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004085 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004086 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004087 LoopIterationSpace &ResultIterSpace,
4088 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004089 // OpenMP [2.6, Canonical Loop Form]
4090 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004091 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004092 if (!For) {
4093 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004094 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4095 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4096 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4097 if (NestedLoopCount > 1) {
4098 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4099 SemaRef.Diag(DSA.getConstructLoc(),
4100 diag::note_omp_collapse_ordered_expr)
4101 << 2 << CollapseLoopCountExpr->getSourceRange()
4102 << OrderedLoopCountExpr->getSourceRange();
4103 else if (CollapseLoopCountExpr)
4104 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4105 diag::note_omp_collapse_ordered_expr)
4106 << 0 << CollapseLoopCountExpr->getSourceRange();
4107 else
4108 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4109 diag::note_omp_collapse_ordered_expr)
4110 << 1 << OrderedLoopCountExpr->getSourceRange();
4111 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004112 return true;
4113 }
4114 assert(For->getBody());
4115
4116 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4117
4118 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004119 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004120 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004121 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004122
4123 bool HasErrors = false;
4124
4125 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004126 if (auto *LCDecl = ISC.GetLoopDecl()) {
4127 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004128
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004129 // OpenMP [2.6, Canonical Loop Form]
4130 // Var is one of the following:
4131 // A variable of signed or unsigned integer type.
4132 // For C++, a variable of a random access iterator type.
4133 // For C, a variable of a pointer type.
4134 auto VarType = LCDecl->getType().getNonReferenceType();
4135 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4136 !VarType->isPointerType() &&
4137 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4138 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4139 << SemaRef.getLangOpts().CPlusPlus;
4140 HasErrors = true;
4141 }
4142
4143 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4144 // a Construct
4145 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4146 // parallel for construct is (are) private.
4147 // The loop iteration variable in the associated for-loop of a simd
4148 // construct with just one associated for-loop is linear with a
4149 // constant-linear-step that is the increment of the associated for-loop.
4150 // Exclude loop var from the list of variables with implicitly defined data
4151 // sharing attributes.
4152 VarsWithImplicitDSA.erase(LCDecl);
4153
4154 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4155 // in a Construct, C/C++].
4156 // The loop iteration variable in the associated for-loop of a simd
4157 // construct with just one associated for-loop may be listed in a linear
4158 // clause with a constant-linear-step that is the increment of the
4159 // associated for-loop.
4160 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4161 // parallel for construct may be listed in a private or lastprivate clause.
4162 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4163 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4164 // declared in the loop and it is predetermined as a private.
4165 auto PredeterminedCKind =
4166 isOpenMPSimdDirective(DKind)
4167 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4168 : OMPC_private;
4169 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4170 DVar.CKind != PredeterminedCKind) ||
4171 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4172 isOpenMPDistributeDirective(DKind)) &&
4173 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4174 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4175 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4176 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4177 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4178 << getOpenMPClauseName(PredeterminedCKind);
4179 if (DVar.RefExpr == nullptr)
4180 DVar.CKind = PredeterminedCKind;
4181 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4182 HasErrors = true;
4183 } else if (LoopDeclRefExpr != nullptr) {
4184 // Make the loop iteration variable private (for worksharing constructs),
4185 // linear (for simd directives with the only one associated loop) or
4186 // lastprivate (for simd directives with several collapsed or ordered
4187 // loops).
4188 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004189 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4190 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004191 /*FromParent=*/false);
4192 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4193 }
4194
4195 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4196
4197 // Check test-expr.
4198 HasErrors |= ISC.CheckCond(For->getCond());
4199
4200 // Check incr-expr.
4201 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004202 }
4203
Alexander Musmana5f070a2014-10-01 06:03:56 +00004204 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004205 return HasErrors;
4206
Alexander Musmana5f070a2014-10-01 06:03:56 +00004207 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004208 ResultIterSpace.PreCond =
4209 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004210 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004211 DSA.getCurScope(),
4212 (isOpenMPWorksharingDirective(DKind) ||
4213 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4214 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004215 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004216 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004217 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4218 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4219 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4220 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4221 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4222 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4223
Alexey Bataev62dbb972015-04-22 11:59:37 +00004224 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4225 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004226 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004227 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004228 ResultIterSpace.CounterInit == nullptr ||
4229 ResultIterSpace.CounterStep == nullptr);
4230
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004231 return HasErrors;
4232}
4233
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004234/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004235static ExprResult
4236BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4237 ExprResult Start,
4238 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004239 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004240 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4241 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004242 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004243 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004244 VarRef.get()->getType())) {
4245 NewStart = SemaRef.PerformImplicitConversion(
4246 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4247 /*AllowExplicit=*/true);
4248 if (!NewStart.isUsable())
4249 return ExprError();
4250 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004251
4252 auto Init =
4253 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4254 return Init;
4255}
4256
Alexander Musmana5f070a2014-10-01 06:03:56 +00004257/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004258static ExprResult
4259BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4260 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4261 ExprResult Step, bool Subtract,
4262 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004263 // Add parentheses (for debugging purposes only).
4264 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4265 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4266 !Step.isUsable())
4267 return ExprError();
4268
Alexey Bataev5a3af132016-03-29 08:58:54 +00004269 ExprResult NewStep = Step;
4270 if (Captures)
4271 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004272 if (NewStep.isInvalid())
4273 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004274 ExprResult Update =
4275 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004276 if (!Update.isUsable())
4277 return ExprError();
4278
Alexey Bataevc0214e02016-02-16 12:13:49 +00004279 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4280 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004281 ExprResult NewStart = Start;
4282 if (Captures)
4283 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004284 if (NewStart.isInvalid())
4285 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004286
Alexey Bataevc0214e02016-02-16 12:13:49 +00004287 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4288 ExprResult SavedUpdate = Update;
4289 ExprResult UpdateVal;
4290 if (VarRef.get()->getType()->isOverloadableType() ||
4291 NewStart.get()->getType()->isOverloadableType() ||
4292 Update.get()->getType()->isOverloadableType()) {
4293 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4294 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4295 Update =
4296 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4297 if (Update.isUsable()) {
4298 UpdateVal =
4299 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4300 VarRef.get(), SavedUpdate.get());
4301 if (UpdateVal.isUsable()) {
4302 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4303 UpdateVal.get());
4304 }
4305 }
4306 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4307 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004308
Alexey Bataevc0214e02016-02-16 12:13:49 +00004309 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4310 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4311 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4312 NewStart.get(), SavedUpdate.get());
4313 if (!Update.isUsable())
4314 return ExprError();
4315
Alexey Bataev11481f52016-02-17 10:29:05 +00004316 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4317 VarRef.get()->getType())) {
4318 Update = SemaRef.PerformImplicitConversion(
4319 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4320 if (!Update.isUsable())
4321 return ExprError();
4322 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004323
4324 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4325 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004326 return Update;
4327}
4328
4329/// \brief Convert integer expression \a E to make it have at least \a Bits
4330/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004331static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004332 if (E == nullptr)
4333 return ExprError();
4334 auto &C = SemaRef.Context;
4335 QualType OldType = E->getType();
4336 unsigned HasBits = C.getTypeSize(OldType);
4337 if (HasBits >= Bits)
4338 return ExprResult(E);
4339 // OK to convert to signed, because new type has more bits than old.
4340 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4341 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4342 true);
4343}
4344
4345/// \brief Check if the given expression \a E is a constant integer that fits
4346/// into \a Bits bits.
4347static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4348 if (E == nullptr)
4349 return false;
4350 llvm::APSInt Result;
4351 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4352 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4353 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004354}
4355
Alexey Bataev5a3af132016-03-29 08:58:54 +00004356/// Build preinits statement for the given declarations.
4357static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004358 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004359 if (!PreInits.empty()) {
4360 return new (Context) DeclStmt(
4361 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4362 SourceLocation(), SourceLocation());
4363 }
4364 return nullptr;
4365}
4366
4367/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004368static Stmt *
4369buildPreInits(ASTContext &Context,
4370 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004371 if (!Captures.empty()) {
4372 SmallVector<Decl *, 16> PreInits;
4373 for (auto &Pair : Captures)
4374 PreInits.push_back(Pair.second->getDecl());
4375 return buildPreInits(Context, PreInits);
4376 }
4377 return nullptr;
4378}
4379
4380/// Build postupdate expression for the given list of postupdates expressions.
4381static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4382 Expr *PostUpdate = nullptr;
4383 if (!PostUpdates.empty()) {
4384 for (auto *E : PostUpdates) {
4385 Expr *ConvE = S.BuildCStyleCastExpr(
4386 E->getExprLoc(),
4387 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4388 E->getExprLoc(), E)
4389 .get();
4390 PostUpdate = PostUpdate
4391 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4392 PostUpdate, ConvE)
4393 .get()
4394 : ConvE;
4395 }
4396 }
4397 return PostUpdate;
4398}
4399
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004400/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004401/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4402/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004403static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004404CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4405 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4406 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004407 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004408 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004409 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004410 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004411 // Found 'collapse' clause - calculate collapse number.
4412 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004413 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004414 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004415 }
4416 if (OrderedLoopCountExpr) {
4417 // Found 'ordered' clause - calculate collapse number.
4418 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004419 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4420 if (Result.getLimitedValue() < NestedLoopCount) {
4421 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4422 diag::err_omp_wrong_ordered_loop_count)
4423 << OrderedLoopCountExpr->getSourceRange();
4424 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4425 diag::note_collapse_loop_count)
4426 << CollapseLoopCountExpr->getSourceRange();
4427 }
4428 NestedLoopCount = Result.getLimitedValue();
4429 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004430 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004431 // This is helper routine for loop directives (e.g., 'for', 'simd',
4432 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004433 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004434 SmallVector<LoopIterationSpace, 4> IterSpaces;
4435 IterSpaces.resize(NestedLoopCount);
4436 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004437 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004438 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004439 NestedLoopCount, CollapseLoopCountExpr,
4440 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004441 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004442 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004443 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004444 // OpenMP [2.8.1, simd construct, Restrictions]
4445 // All loops associated with the construct must be perfectly nested; that
4446 // is, there must be no intervening code nor any OpenMP directive between
4447 // any two loops.
4448 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004449 }
4450
Alexander Musmana5f070a2014-10-01 06:03:56 +00004451 Built.clear(/* size */ NestedLoopCount);
4452
4453 if (SemaRef.CurContext->isDependentContext())
4454 return NestedLoopCount;
4455
4456 // An example of what is generated for the following code:
4457 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004458 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004459 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004460 // for (k = 0; k < NK; ++k)
4461 // for (j = J0; j < NJ; j+=2) {
4462 // <loop body>
4463 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004464 //
4465 // We generate the code below.
4466 // Note: the loop body may be outlined in CodeGen.
4467 // Note: some counters may be C++ classes, operator- is used to find number of
4468 // iterations and operator+= to calculate counter value.
4469 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4470 // or i64 is currently supported).
4471 //
4472 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4473 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4474 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4475 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4476 // // similar updates for vars in clauses (e.g. 'linear')
4477 // <loop body (using local i and j)>
4478 // }
4479 // i = NI; // assign final values of counters
4480 // j = NJ;
4481 //
4482
4483 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4484 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004485 // Precondition tests if there is at least one iteration (all conditions are
4486 // true).
4487 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004488 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004489 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004490 32 /* Bits */, SemaRef
4491 .PerformImplicitConversion(
4492 N0->IgnoreImpCasts(), N0->getType(),
4493 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004494 .get(),
4495 SemaRef);
4496 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004497 64 /* Bits */, SemaRef
4498 .PerformImplicitConversion(
4499 N0->IgnoreImpCasts(), N0->getType(),
4500 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004501 .get(),
4502 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004503
4504 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4505 return NestedLoopCount;
4506
4507 auto &C = SemaRef.Context;
4508 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4509
4510 Scope *CurScope = DSA.getCurScope();
4511 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004512 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004513 PreCond =
4514 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4515 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004516 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004517 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004518 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004519 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4520 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004521 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004522 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004523 SemaRef
4524 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4525 Sema::AA_Converting,
4526 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004527 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004528 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004529 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004530 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004531 SemaRef
4532 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4533 Sema::AA_Converting,
4534 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004535 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004536 }
4537
4538 // Choose either the 32-bit or 64-bit version.
4539 ExprResult LastIteration = LastIteration64;
4540 if (LastIteration32.isUsable() &&
4541 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4542 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4543 FitsInto(
4544 32 /* Bits */,
4545 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4546 LastIteration64.get(), SemaRef)))
4547 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004548 QualType VType = LastIteration.get()->getType();
4549 QualType RealVType = VType;
4550 QualType StrideVType = VType;
4551 if (isOpenMPTaskLoopDirective(DKind)) {
4552 VType =
4553 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4554 StrideVType =
4555 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4556 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004557
4558 if (!LastIteration.isUsable())
4559 return 0;
4560
4561 // Save the number of iterations.
4562 ExprResult NumIterations = LastIteration;
4563 {
4564 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004565 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4566 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004567 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4568 if (!LastIteration.isUsable())
4569 return 0;
4570 }
4571
4572 // Calculate the last iteration number beforehand instead of doing this on
4573 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4574 llvm::APSInt Result;
4575 bool IsConstant =
4576 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4577 ExprResult CalcLastIteration;
4578 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004579 ExprResult SaveRef =
4580 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004581 LastIteration = SaveRef;
4582
4583 // Prepare SaveRef + 1.
4584 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004585 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004586 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4587 if (!NumIterations.isUsable())
4588 return 0;
4589 }
4590
4591 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4592
David Majnemer9d168222016-08-05 17:44:54 +00004593 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004594 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004595 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4596 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004597 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004598 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4599 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004600 SemaRef.AddInitializerToDecl(LBDecl,
4601 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4602 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004603
4604 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004605 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4606 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004607 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004608 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004609
4610 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4611 // This will be used to implement clause 'lastprivate'.
4612 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004613 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4614 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004615 SemaRef.AddInitializerToDecl(ILDecl,
4616 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4617 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004618
4619 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004620 VarDecl *STDecl =
4621 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4622 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004623 SemaRef.AddInitializerToDecl(STDecl,
4624 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4625 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004626
4627 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004628 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004629 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4630 UB.get(), LastIteration.get());
4631 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4632 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4633 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4634 CondOp.get());
4635 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004636
4637 // If we have a combined directive that combines 'distribute', 'for' or
4638 // 'simd' we need to be able to access the bounds of the schedule of the
4639 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4640 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4641 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004642
Carlo Bertolliffafe102017-04-20 00:39:39 +00004643 // Lower bound variable, initialized with zero.
4644 VarDecl *CombLBDecl =
4645 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4646 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4647 SemaRef.AddInitializerToDecl(
4648 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4649 /*DirectInit*/ false);
4650
4651 // Upper bound variable, initialized with last iteration number.
4652 VarDecl *CombUBDecl =
4653 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4654 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4655 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4656 /*DirectInit*/ false);
4657
4658 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4659 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4660 ExprResult CombCondOp =
4661 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4662 LastIteration.get(), CombUB.get());
4663 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4664 CombCondOp.get());
4665 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4666
4667 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004668 // We expect to have at least 2 more parameters than the 'parallel'
4669 // directive does - the lower and upper bounds of the previous schedule.
4670 assert(CD->getNumParams() >= 4 &&
4671 "Unexpected number of parameters in loop combined directive");
4672
4673 // Set the proper type for the bounds given what we learned from the
4674 // enclosed loops.
4675 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4676 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4677
4678 // Previous lower and upper bounds are obtained from the region
4679 // parameters.
4680 PrevLB =
4681 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4682 PrevUB =
4683 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4684 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004685 }
4686
4687 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004688 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004689 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004690 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004691 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4692 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004693 Expr *RHS =
4694 (isOpenMPWorksharingDirective(DKind) ||
4695 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4696 ? LB.get()
4697 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004698 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4699 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004700
4701 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4702 Expr *CombRHS =
4703 (isOpenMPWorksharingDirective(DKind) ||
4704 isOpenMPTaskLoopDirective(DKind) ||
4705 isOpenMPDistributeDirective(DKind))
4706 ? CombLB.get()
4707 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4708 CombInit =
4709 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4710 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4711 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004712 }
4713
Alexander Musmanc6388682014-12-15 07:07:06 +00004714 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004715 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004716 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004717 (isOpenMPWorksharingDirective(DKind) ||
4718 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004719 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4720 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4721 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004722 ExprResult CombCond;
4723 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4724 CombCond =
4725 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4726 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004727 // Loop increment (IV = IV + 1)
4728 SourceLocation IncLoc;
4729 ExprResult Inc =
4730 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4731 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4732 if (!Inc.isUsable())
4733 return 0;
4734 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004735 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4736 if (!Inc.isUsable())
4737 return 0;
4738
4739 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4740 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004741 // In combined construct, add combined version that use CombLB and CombUB
4742 // base variables for the update
4743 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004744 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4745 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004746 // LB + ST
4747 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4748 if (!NextLB.isUsable())
4749 return 0;
4750 // LB = LB + ST
4751 NextLB =
4752 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4753 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4754 if (!NextLB.isUsable())
4755 return 0;
4756 // UB + ST
4757 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4758 if (!NextUB.isUsable())
4759 return 0;
4760 // UB = UB + ST
4761 NextUB =
4762 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4763 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4764 if (!NextUB.isUsable())
4765 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004766 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4767 CombNextLB =
4768 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4769 if (!NextLB.isUsable())
4770 return 0;
4771 // LB = LB + ST
4772 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4773 CombNextLB.get());
4774 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4775 if (!CombNextLB.isUsable())
4776 return 0;
4777 // UB + ST
4778 CombNextUB =
4779 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4780 if (!CombNextUB.isUsable())
4781 return 0;
4782 // UB = UB + ST
4783 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4784 CombNextUB.get());
4785 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4786 if (!CombNextUB.isUsable())
4787 return 0;
4788 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004789 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004790
Carlo Bertolliffafe102017-04-20 00:39:39 +00004791 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004792 // directive with for as IV = IV + ST; ensure upper bound expression based
4793 // on PrevUB instead of NumIterations - used to implement 'for' when found
4794 // in combination with 'distribute', like in 'distribute parallel for'
4795 SourceLocation DistIncLoc;
4796 ExprResult DistCond, DistInc, PrevEUB;
4797 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4798 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4799 assert(DistCond.isUsable() && "distribute cond expr was not built");
4800
4801 DistInc =
4802 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4803 assert(DistInc.isUsable() && "distribute inc expr was not built");
4804 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4805 DistInc.get());
4806 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4807 assert(DistInc.isUsable() && "distribute inc expr was not built");
4808
4809 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4810 // construct
4811 SourceLocation DistEUBLoc;
4812 ExprResult IsUBGreater =
4813 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4814 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4815 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4816 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4817 CondOp.get());
4818 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4819 }
4820
Alexander Musmana5f070a2014-10-01 06:03:56 +00004821 // Build updates and final values of the loop counters.
4822 bool HasErrors = false;
4823 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004824 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004825 Built.Updates.resize(NestedLoopCount);
4826 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004827 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004828 {
4829 ExprResult Div;
4830 // Go from inner nested loop to outer.
4831 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4832 LoopIterationSpace &IS = IterSpaces[Cnt];
4833 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4834 // Build: Iter = (IV / Div) % IS.NumIters
4835 // where Div is product of previous iterations' IS.NumIters.
4836 ExprResult Iter;
4837 if (Div.isUsable()) {
4838 Iter =
4839 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4840 } else {
4841 Iter = IV;
4842 assert((Cnt == (int)NestedLoopCount - 1) &&
4843 "unusable div expected on first iteration only");
4844 }
4845
4846 if (Cnt != 0 && Iter.isUsable())
4847 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4848 IS.NumIterations);
4849 if (!Iter.isUsable()) {
4850 HasErrors = true;
4851 break;
4852 }
4853
Alexey Bataev39f915b82015-05-08 10:41:21 +00004854 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004855 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4856 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4857 IS.CounterVar->getExprLoc(),
4858 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004859 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004860 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004861 if (!Init.isUsable()) {
4862 HasErrors = true;
4863 break;
4864 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004865 ExprResult Update = BuildCounterUpdate(
4866 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4867 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004868 if (!Update.isUsable()) {
4869 HasErrors = true;
4870 break;
4871 }
4872
4873 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4874 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004875 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004876 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004877 if (!Final.isUsable()) {
4878 HasErrors = true;
4879 break;
4880 }
4881
4882 // Build Div for the next iteration: Div <- Div * IS.NumIters
4883 if (Cnt != 0) {
4884 if (Div.isUnset())
4885 Div = IS.NumIterations;
4886 else
4887 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4888 IS.NumIterations);
4889
4890 // Add parentheses (for debugging purposes only).
4891 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004892 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004893 if (!Div.isUsable()) {
4894 HasErrors = true;
4895 break;
4896 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004897 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004898 }
4899 if (!Update.isUsable() || !Final.isUsable()) {
4900 HasErrors = true;
4901 break;
4902 }
4903 // Save results
4904 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004905 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004906 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004907 Built.Updates[Cnt] = Update.get();
4908 Built.Finals[Cnt] = Final.get();
4909 }
4910 }
4911
4912 if (HasErrors)
4913 return 0;
4914
4915 // Save results
4916 Built.IterationVarRef = IV.get();
4917 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004918 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004919 Built.CalcLastIteration =
4920 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004921 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004922 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004923 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004924 Built.Init = Init.get();
4925 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004926 Built.LB = LB.get();
4927 Built.UB = UB.get();
4928 Built.IL = IL.get();
4929 Built.ST = ST.get();
4930 Built.EUB = EUB.get();
4931 Built.NLB = NextLB.get();
4932 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004933 Built.PrevLB = PrevLB.get();
4934 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004935 Built.DistInc = DistInc.get();
4936 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004937 Built.DistCombinedFields.LB = CombLB.get();
4938 Built.DistCombinedFields.UB = CombUB.get();
4939 Built.DistCombinedFields.EUB = CombEUB.get();
4940 Built.DistCombinedFields.Init = CombInit.get();
4941 Built.DistCombinedFields.Cond = CombCond.get();
4942 Built.DistCombinedFields.NLB = CombNextLB.get();
4943 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004944
Alexey Bataev8b427062016-05-25 12:36:08 +00004945 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4946 // Fill data for doacross depend clauses.
4947 for (auto Pair : DSA.getDoacrossDependClauses()) {
4948 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4949 Pair.first->setCounterValue(CounterVal);
4950 else {
4951 if (NestedLoopCount != Pair.second.size() ||
4952 NestedLoopCount != LoopMultipliers.size() + 1) {
4953 // Erroneous case - clause has some problems.
4954 Pair.first->setCounterValue(CounterVal);
4955 continue;
4956 }
4957 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4958 auto I = Pair.second.rbegin();
4959 auto IS = IterSpaces.rbegin();
4960 auto ILM = LoopMultipliers.rbegin();
4961 Expr *UpCounterVal = CounterVal;
4962 Expr *Multiplier = nullptr;
4963 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4964 if (I->first) {
4965 assert(IS->CounterStep);
4966 Expr *NormalizedOffset =
4967 SemaRef
4968 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4969 I->first, IS->CounterStep)
4970 .get();
4971 if (Multiplier) {
4972 NormalizedOffset =
4973 SemaRef
4974 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4975 NormalizedOffset, Multiplier)
4976 .get();
4977 }
4978 assert(I->second == OO_Plus || I->second == OO_Minus);
4979 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004980 UpCounterVal = SemaRef
4981 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4982 UpCounterVal, NormalizedOffset)
4983 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004984 }
4985 Multiplier = *ILM;
4986 ++I;
4987 ++IS;
4988 ++ILM;
4989 }
4990 Pair.first->setCounterValue(UpCounterVal);
4991 }
4992 }
4993
Alexey Bataevabfc0692014-06-25 06:52:00 +00004994 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004995}
4996
Alexey Bataev10e775f2015-07-30 11:36:16 +00004997static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004998 auto CollapseClauses =
4999 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5000 if (CollapseClauses.begin() != CollapseClauses.end())
5001 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005002 return nullptr;
5003}
5004
Alexey Bataev10e775f2015-07-30 11:36:16 +00005005static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005006 auto OrderedClauses =
5007 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5008 if (OrderedClauses.begin() != OrderedClauses.end())
5009 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005010 return nullptr;
5011}
5012
Kelvin Lic5609492016-07-15 04:39:07 +00005013static bool checkSimdlenSafelenSpecified(Sema &S,
5014 const ArrayRef<OMPClause *> Clauses) {
5015 OMPSafelenClause *Safelen = nullptr;
5016 OMPSimdlenClause *Simdlen = nullptr;
5017
5018 for (auto *Clause : Clauses) {
5019 if (Clause->getClauseKind() == OMPC_safelen)
5020 Safelen = cast<OMPSafelenClause>(Clause);
5021 else if (Clause->getClauseKind() == OMPC_simdlen)
5022 Simdlen = cast<OMPSimdlenClause>(Clause);
5023 if (Safelen && Simdlen)
5024 break;
5025 }
5026
5027 if (Simdlen && Safelen) {
5028 llvm::APSInt SimdlenRes, SafelenRes;
5029 auto SimdlenLength = Simdlen->getSimdlen();
5030 auto SafelenLength = Safelen->getSafelen();
5031 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5032 SimdlenLength->isInstantiationDependent() ||
5033 SimdlenLength->containsUnexpandedParameterPack())
5034 return false;
5035 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5036 SafelenLength->isInstantiationDependent() ||
5037 SafelenLength->containsUnexpandedParameterPack())
5038 return false;
5039 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5040 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5041 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5042 // If both simdlen and safelen clauses are specified, the value of the
5043 // simdlen parameter must be less than or equal to the value of the safelen
5044 // parameter.
5045 if (SimdlenRes > SafelenRes) {
5046 S.Diag(SimdlenLength->getExprLoc(),
5047 diag::err_omp_wrong_simdlen_safelen_values)
5048 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5049 return true;
5050 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005051 }
5052 return false;
5053}
5054
Alexey Bataev4acb8592014-07-07 13:01:15 +00005055StmtResult Sema::ActOnOpenMPSimdDirective(
5056 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5057 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005058 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005059 if (!AStmt)
5060 return StmtError();
5061
5062 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005063 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005064 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5065 // define the nested loops number.
5066 unsigned NestedLoopCount = CheckOpenMPLoop(
5067 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5068 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005069 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005070 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005071
Alexander Musmana5f070a2014-10-01 06:03:56 +00005072 assert((CurContext->isDependentContext() || B.builtAll()) &&
5073 "omp simd loop exprs were not built");
5074
Alexander Musman3276a272015-03-21 10:12:56 +00005075 if (!CurContext->isDependentContext()) {
5076 // Finalize the clauses that need pre-built expressions for CodeGen.
5077 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005078 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005079 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005080 B.NumIterations, *this, CurScope,
5081 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005082 return StmtError();
5083 }
5084 }
5085
Kelvin Lic5609492016-07-15 04:39:07 +00005086 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005087 return StmtError();
5088
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005089 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005090 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5091 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005092}
5093
Alexey Bataev4acb8592014-07-07 13:01:15 +00005094StmtResult Sema::ActOnOpenMPForDirective(
5095 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5096 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005097 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005098 if (!AStmt)
5099 return StmtError();
5100
5101 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005102 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005103 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5104 // define the nested loops number.
5105 unsigned NestedLoopCount = CheckOpenMPLoop(
5106 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5107 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005108 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005109 return StmtError();
5110
Alexander Musmana5f070a2014-10-01 06:03:56 +00005111 assert((CurContext->isDependentContext() || B.builtAll()) &&
5112 "omp for loop exprs were not built");
5113
Alexey Bataev54acd402015-08-04 11:18:19 +00005114 if (!CurContext->isDependentContext()) {
5115 // Finalize the clauses that need pre-built expressions for CodeGen.
5116 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005117 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005118 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005119 B.NumIterations, *this, CurScope,
5120 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005121 return StmtError();
5122 }
5123 }
5124
Alexey Bataevf29276e2014-06-18 04:14:57 +00005125 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005126 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005127 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005128}
5129
Alexander Musmanf82886e2014-09-18 05:12:34 +00005130StmtResult Sema::ActOnOpenMPForSimdDirective(
5131 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5132 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005133 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005134 if (!AStmt)
5135 return StmtError();
5136
5137 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005138 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005139 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5140 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005141 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005142 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5143 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5144 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005145 if (NestedLoopCount == 0)
5146 return StmtError();
5147
Alexander Musmanc6388682014-12-15 07:07:06 +00005148 assert((CurContext->isDependentContext() || B.builtAll()) &&
5149 "omp for simd loop exprs were not built");
5150
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005151 if (!CurContext->isDependentContext()) {
5152 // Finalize the clauses that need pre-built expressions for CodeGen.
5153 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005154 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005155 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005156 B.NumIterations, *this, CurScope,
5157 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005158 return StmtError();
5159 }
5160 }
5161
Kelvin Lic5609492016-07-15 04:39:07 +00005162 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005163 return StmtError();
5164
Alexander Musmanf82886e2014-09-18 05:12:34 +00005165 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005166 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5167 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005168}
5169
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005170StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5171 Stmt *AStmt,
5172 SourceLocation StartLoc,
5173 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005174 if (!AStmt)
5175 return StmtError();
5176
5177 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005178 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005179 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005180 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005181 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005182 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005183 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005184 return StmtError();
5185 // All associated statements must be '#pragma omp section' except for
5186 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005187 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005188 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5189 if (SectionStmt)
5190 Diag(SectionStmt->getLocStart(),
5191 diag::err_omp_sections_substmt_not_section);
5192 return StmtError();
5193 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005194 cast<OMPSectionDirective>(SectionStmt)
5195 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005196 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005197 } else {
5198 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5199 return StmtError();
5200 }
5201
5202 getCurFunction()->setHasBranchProtectedScope();
5203
Alexey Bataev25e5b442015-09-15 12:52:43 +00005204 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5205 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005206}
5207
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005208StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5209 SourceLocation StartLoc,
5210 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005211 if (!AStmt)
5212 return StmtError();
5213
5214 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005215
5216 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005217 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005218
Alexey Bataev25e5b442015-09-15 12:52:43 +00005219 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5220 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005221}
5222
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005223StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5224 Stmt *AStmt,
5225 SourceLocation StartLoc,
5226 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005227 if (!AStmt)
5228 return StmtError();
5229
5230 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005231
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005232 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005233
Alexey Bataev3255bf32015-01-19 05:20:46 +00005234 // OpenMP [2.7.3, single Construct, Restrictions]
5235 // The copyprivate clause must not be used with the nowait clause.
5236 OMPClause *Nowait = nullptr;
5237 OMPClause *Copyprivate = nullptr;
5238 for (auto *Clause : Clauses) {
5239 if (Clause->getClauseKind() == OMPC_nowait)
5240 Nowait = Clause;
5241 else if (Clause->getClauseKind() == OMPC_copyprivate)
5242 Copyprivate = Clause;
5243 if (Copyprivate && Nowait) {
5244 Diag(Copyprivate->getLocStart(),
5245 diag::err_omp_single_copyprivate_with_nowait);
5246 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5247 return StmtError();
5248 }
5249 }
5250
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005251 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5252}
5253
Alexander Musman80c22892014-07-17 08:54:58 +00005254StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5255 SourceLocation StartLoc,
5256 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005257 if (!AStmt)
5258 return StmtError();
5259
5260 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005261
5262 getCurFunction()->setHasBranchProtectedScope();
5263
5264 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5265}
5266
Alexey Bataev28c75412015-12-15 08:19:24 +00005267StmtResult Sema::ActOnOpenMPCriticalDirective(
5268 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5269 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005270 if (!AStmt)
5271 return StmtError();
5272
5273 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005274
Alexey Bataev28c75412015-12-15 08:19:24 +00005275 bool ErrorFound = false;
5276 llvm::APSInt Hint;
5277 SourceLocation HintLoc;
5278 bool DependentHint = false;
5279 for (auto *C : Clauses) {
5280 if (C->getClauseKind() == OMPC_hint) {
5281 if (!DirName.getName()) {
5282 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5283 ErrorFound = true;
5284 }
5285 Expr *E = cast<OMPHintClause>(C)->getHint();
5286 if (E->isTypeDependent() || E->isValueDependent() ||
5287 E->isInstantiationDependent())
5288 DependentHint = true;
5289 else {
5290 Hint = E->EvaluateKnownConstInt(Context);
5291 HintLoc = C->getLocStart();
5292 }
5293 }
5294 }
5295 if (ErrorFound)
5296 return StmtError();
5297 auto Pair = DSAStack->getCriticalWithHint(DirName);
5298 if (Pair.first && DirName.getName() && !DependentHint) {
5299 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5300 Diag(StartLoc, diag::err_omp_critical_with_hint);
5301 if (HintLoc.isValid()) {
5302 Diag(HintLoc, diag::note_omp_critical_hint_here)
5303 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5304 } else
5305 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5306 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5307 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5308 << 1
5309 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5310 /*Radix=*/10, /*Signed=*/false);
5311 } else
5312 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5313 }
5314 }
5315
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005316 getCurFunction()->setHasBranchProtectedScope();
5317
Alexey Bataev28c75412015-12-15 08:19:24 +00005318 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5319 Clauses, AStmt);
5320 if (!Pair.first && DirName.getName() && !DependentHint)
5321 DSAStack->addCriticalWithHint(Dir, Hint);
5322 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005323}
5324
Alexey Bataev4acb8592014-07-07 13:01:15 +00005325StmtResult Sema::ActOnOpenMPParallelForDirective(
5326 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5327 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005328 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005329 if (!AStmt)
5330 return StmtError();
5331
Alexey Bataev4acb8592014-07-07 13:01:15 +00005332 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5333 // 1.2.2 OpenMP Language Terminology
5334 // Structured block - An executable statement with a single entry at the
5335 // top and a single exit at the bottom.
5336 // The point of exit cannot be a branch out of the structured block.
5337 // longjmp() and throw() must not violate the entry/exit criteria.
5338 CS->getCapturedDecl()->setNothrow();
5339
Alexander Musmanc6388682014-12-15 07:07:06 +00005340 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005341 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5342 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005343 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005344 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5345 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5346 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005347 if (NestedLoopCount == 0)
5348 return StmtError();
5349
Alexander Musmana5f070a2014-10-01 06:03:56 +00005350 assert((CurContext->isDependentContext() || B.builtAll()) &&
5351 "omp parallel for loop exprs were not built");
5352
Alexey Bataev54acd402015-08-04 11:18:19 +00005353 if (!CurContext->isDependentContext()) {
5354 // Finalize the clauses that need pre-built expressions for CodeGen.
5355 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005356 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005357 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005358 B.NumIterations, *this, CurScope,
5359 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005360 return StmtError();
5361 }
5362 }
5363
Alexey Bataev4acb8592014-07-07 13:01:15 +00005364 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005365 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005366 NestedLoopCount, Clauses, AStmt, B,
5367 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005368}
5369
Alexander Musmane4e893b2014-09-23 09:33:00 +00005370StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5371 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5372 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005373 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005374 if (!AStmt)
5375 return StmtError();
5376
Alexander Musmane4e893b2014-09-23 09:33:00 +00005377 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5378 // 1.2.2 OpenMP Language Terminology
5379 // Structured block - An executable statement with a single entry at the
5380 // top and a single exit at the bottom.
5381 // The point of exit cannot be a branch out of the structured block.
5382 // longjmp() and throw() must not violate the entry/exit criteria.
5383 CS->getCapturedDecl()->setNothrow();
5384
Alexander Musmanc6388682014-12-15 07:07:06 +00005385 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005386 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5387 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005388 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005389 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5390 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5391 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005392 if (NestedLoopCount == 0)
5393 return StmtError();
5394
Alexey Bataev3b5b5c42015-06-18 10:10:12 +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 Bataev3b5b5c42015-06-18 10:10:12 +00005399 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005400 B.NumIterations, *this, CurScope,
5401 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +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
Alexander Musmane4e893b2014-09-23 09:33:00 +00005409 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005410 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005411 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005412}
5413
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005414StmtResult
5415Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5416 Stmt *AStmt, 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 Bataev84d0b3e2014-07-08 08:12:03 +00005422 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005423 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005424 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005425 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005426 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005427 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +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 Bataev84d0b3e2014-07-08 08:12:03 +00005432 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5433 if (SectionStmt)
5434 Diag(SectionStmt->getLocStart(),
5435 diag::err_omp_parallel_sections_substmt_not_section);
5436 return StmtError();
5437 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005438 cast<OMPSectionDirective>(SectionStmt)
5439 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005440 }
5441 } else {
5442 Diag(AStmt->getLocStart(),
5443 diag::err_omp_parallel_sections_not_compound_stmt);
5444 return StmtError();
5445 }
5446
5447 getCurFunction()->setHasBranchProtectedScope();
5448
Alexey Bataev25e5b442015-09-15 12:52:43 +00005449 return OMPParallelSectionsDirective::Create(
5450 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005451}
5452
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005453StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5454 Stmt *AStmt, SourceLocation StartLoc,
5455 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005456 if (!AStmt)
5457 return StmtError();
5458
David Majnemer9d168222016-08-05 17:44:54 +00005459 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005460 // 1.2.2 OpenMP Language Terminology
5461 // Structured block - An executable statement with a single entry at the
5462 // top and a single exit at the bottom.
5463 // The point of exit cannot be a branch out of the structured block.
5464 // longjmp() and throw() must not violate the entry/exit criteria.
5465 CS->getCapturedDecl()->setNothrow();
5466
5467 getCurFunction()->setHasBranchProtectedScope();
5468
Alexey Bataev25e5b442015-09-15 12:52:43 +00005469 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5470 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005471}
5472
Alexey Bataev68446b72014-07-18 07:47:19 +00005473StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5474 SourceLocation EndLoc) {
5475 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5476}
5477
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005478StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5479 SourceLocation EndLoc) {
5480 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5481}
5482
Alexey Bataev2df347a2014-07-18 10:17:07 +00005483StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5484 SourceLocation EndLoc) {
5485 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5486}
5487
Alexey Bataev169d96a2017-07-18 20:17:46 +00005488StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5489 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005490 SourceLocation StartLoc,
5491 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005492 if (!AStmt)
5493 return StmtError();
5494
5495 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005496
5497 getCurFunction()->setHasBranchProtectedScope();
5498
Alexey Bataev169d96a2017-07-18 20:17:46 +00005499 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005500 AStmt,
5501 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005502}
5503
Alexey Bataev6125da92014-07-21 11:26:11 +00005504StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5505 SourceLocation StartLoc,
5506 SourceLocation EndLoc) {
5507 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5508 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5509}
5510
Alexey Bataev346265e2015-09-25 10:37:12 +00005511StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5512 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005513 SourceLocation StartLoc,
5514 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005515 OMPClause *DependFound = nullptr;
5516 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005517 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005518 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005519 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005520 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005521 for (auto *C : Clauses) {
5522 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5523 DependFound = C;
5524 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5525 if (DependSourceClause) {
5526 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5527 << getOpenMPDirectiveName(OMPD_ordered)
5528 << getOpenMPClauseName(OMPC_depend) << 2;
5529 ErrorFound = true;
5530 } else
5531 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005532 if (DependSinkClause) {
5533 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5534 << 0;
5535 ErrorFound = true;
5536 }
5537 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5538 if (DependSourceClause) {
5539 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5540 << 1;
5541 ErrorFound = true;
5542 }
5543 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005544 }
5545 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005546 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005547 else if (C->getClauseKind() == OMPC_simd)
5548 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005549 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005550 if (!ErrorFound && !SC &&
5551 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005552 // OpenMP [2.8.1,simd Construct, Restrictions]
5553 // An ordered construct with the simd clause is the only OpenMP construct
5554 // that can appear in the simd region.
5555 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005556 ErrorFound = true;
5557 } else if (DependFound && (TC || SC)) {
5558 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5559 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5560 ErrorFound = true;
5561 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5562 Diag(DependFound->getLocStart(),
5563 diag::err_omp_ordered_directive_without_param);
5564 ErrorFound = true;
5565 } else if (TC || Clauses.empty()) {
5566 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5567 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5568 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5569 << (TC != nullptr);
5570 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5571 ErrorFound = true;
5572 }
5573 }
5574 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005575 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005576
5577 if (AStmt) {
5578 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5579
5580 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005581 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005582
5583 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005584}
5585
Alexey Bataev1d160b12015-03-13 12:27:31 +00005586namespace {
5587/// \brief Helper class for checking expression in 'omp atomic [update]'
5588/// construct.
5589class OpenMPAtomicUpdateChecker {
5590 /// \brief Error results for atomic update expressions.
5591 enum ExprAnalysisErrorCode {
5592 /// \brief A statement is not an expression statement.
5593 NotAnExpression,
5594 /// \brief Expression is not builtin binary or unary operation.
5595 NotABinaryOrUnaryExpression,
5596 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5597 NotAnUnaryIncDecExpression,
5598 /// \brief An expression is not of scalar type.
5599 NotAScalarType,
5600 /// \brief A binary operation is not an assignment operation.
5601 NotAnAssignmentOp,
5602 /// \brief RHS part of the binary operation is not a binary expression.
5603 NotABinaryExpression,
5604 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5605 /// expression.
5606 NotABinaryOperator,
5607 /// \brief RHS binary operation does not have reference to the updated LHS
5608 /// part.
5609 NotAnUpdateExpression,
5610 /// \brief No errors is found.
5611 NoError
5612 };
5613 /// \brief Reference to Sema.
5614 Sema &SemaRef;
5615 /// \brief A location for note diagnostics (when error is found).
5616 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005617 /// \brief 'x' lvalue part of the source atomic expression.
5618 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005619 /// \brief 'expr' rvalue part of the source atomic expression.
5620 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005621 /// \brief Helper expression of the form
5622 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5623 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5624 Expr *UpdateExpr;
5625 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5626 /// important for non-associative operations.
5627 bool IsXLHSInRHSPart;
5628 BinaryOperatorKind Op;
5629 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005630 /// \brief true if the source expression is a postfix unary operation, false
5631 /// if it is a prefix unary operation.
5632 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005633
5634public:
5635 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005636 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005637 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005638 /// \brief Check specified statement that it is suitable for 'atomic update'
5639 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005640 /// expression. If DiagId and NoteId == 0, then only check is performed
5641 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005642 /// \param DiagId Diagnostic which should be emitted if error is found.
5643 /// \param NoteId Diagnostic note for the main error message.
5644 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005645 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005646 /// \brief Return the 'x' lvalue part of the source atomic expression.
5647 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005648 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5649 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005650 /// \brief Return the update expression used in calculation of the updated
5651 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5652 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5653 Expr *getUpdateExpr() const { return UpdateExpr; }
5654 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5655 /// false otherwise.
5656 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5657
Alexey Bataevb78ca832015-04-01 03:33:17 +00005658 /// \brief true if the source expression is a postfix unary operation, false
5659 /// if it is a prefix unary operation.
5660 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5661
Alexey Bataev1d160b12015-03-13 12:27:31 +00005662private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005663 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5664 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005665};
5666} // namespace
5667
5668bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5669 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5670 ExprAnalysisErrorCode ErrorFound = NoError;
5671 SourceLocation ErrorLoc, NoteLoc;
5672 SourceRange ErrorRange, NoteRange;
5673 // Allowed constructs are:
5674 // x = x binop expr;
5675 // x = expr binop x;
5676 if (AtomicBinOp->getOpcode() == BO_Assign) {
5677 X = AtomicBinOp->getLHS();
5678 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5679 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5680 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5681 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5682 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005683 Op = AtomicInnerBinOp->getOpcode();
5684 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005685 auto *LHS = AtomicInnerBinOp->getLHS();
5686 auto *RHS = AtomicInnerBinOp->getRHS();
5687 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5688 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5689 /*Canonical=*/true);
5690 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5691 /*Canonical=*/true);
5692 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5693 /*Canonical=*/true);
5694 if (XId == LHSId) {
5695 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005696 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005697 } else if (XId == RHSId) {
5698 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005699 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005700 } else {
5701 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5702 ErrorRange = AtomicInnerBinOp->getSourceRange();
5703 NoteLoc = X->getExprLoc();
5704 NoteRange = X->getSourceRange();
5705 ErrorFound = NotAnUpdateExpression;
5706 }
5707 } else {
5708 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5709 ErrorRange = AtomicInnerBinOp->getSourceRange();
5710 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5711 NoteRange = SourceRange(NoteLoc, NoteLoc);
5712 ErrorFound = NotABinaryOperator;
5713 }
5714 } else {
5715 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5716 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5717 ErrorFound = NotABinaryExpression;
5718 }
5719 } else {
5720 ErrorLoc = AtomicBinOp->getExprLoc();
5721 ErrorRange = AtomicBinOp->getSourceRange();
5722 NoteLoc = AtomicBinOp->getOperatorLoc();
5723 NoteRange = SourceRange(NoteLoc, NoteLoc);
5724 ErrorFound = NotAnAssignmentOp;
5725 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005726 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005727 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5728 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5729 return true;
5730 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005731 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005732 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005733}
5734
5735bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5736 unsigned NoteId) {
5737 ExprAnalysisErrorCode ErrorFound = NoError;
5738 SourceLocation ErrorLoc, NoteLoc;
5739 SourceRange ErrorRange, NoteRange;
5740 // Allowed constructs are:
5741 // x++;
5742 // x--;
5743 // ++x;
5744 // --x;
5745 // x binop= expr;
5746 // x = x binop expr;
5747 // x = expr binop x;
5748 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5749 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5750 if (AtomicBody->getType()->isScalarType() ||
5751 AtomicBody->isInstantiationDependent()) {
5752 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5753 AtomicBody->IgnoreParenImpCasts())) {
5754 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005755 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005756 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005757 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005758 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005759 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005760 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005761 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5762 AtomicBody->IgnoreParenImpCasts())) {
5763 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005764 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005765 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005766 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5767 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005768 // Check for Unary Operation
5769 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005770 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005771 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5772 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005773 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005774 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5775 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005776 } else {
5777 ErrorFound = NotAnUnaryIncDecExpression;
5778 ErrorLoc = AtomicUnaryOp->getExprLoc();
5779 ErrorRange = AtomicUnaryOp->getSourceRange();
5780 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5781 NoteRange = SourceRange(NoteLoc, NoteLoc);
5782 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005783 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005784 ErrorFound = NotABinaryOrUnaryExpression;
5785 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5786 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5787 }
5788 } else {
5789 ErrorFound = NotAScalarType;
5790 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5791 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5792 }
5793 } else {
5794 ErrorFound = NotAnExpression;
5795 NoteLoc = ErrorLoc = S->getLocStart();
5796 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5797 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005798 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005799 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5800 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5801 return true;
5802 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005803 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005804 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005805 // Build an update expression of form 'OpaqueValueExpr(x) binop
5806 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5807 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5808 auto *OVEX = new (SemaRef.getASTContext())
5809 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5810 auto *OVEExpr = new (SemaRef.getASTContext())
5811 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5812 auto Update =
5813 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5814 IsXLHSInRHSPart ? OVEExpr : OVEX);
5815 if (Update.isInvalid())
5816 return true;
5817 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5818 Sema::AA_Casting);
5819 if (Update.isInvalid())
5820 return true;
5821 UpdateExpr = Update.get();
5822 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005823 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005824}
5825
Alexey Bataev0162e452014-07-22 10:10:35 +00005826StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5827 Stmt *AStmt,
5828 SourceLocation StartLoc,
5829 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005830 if (!AStmt)
5831 return StmtError();
5832
David Majnemer9d168222016-08-05 17:44:54 +00005833 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005834 // 1.2.2 OpenMP Language Terminology
5835 // Structured block - An executable statement with a single entry at the
5836 // top and a single exit at the bottom.
5837 // The point of exit cannot be a branch out of the structured block.
5838 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005839 OpenMPClauseKind AtomicKind = OMPC_unknown;
5840 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005841 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005842 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005843 C->getClauseKind() == OMPC_update ||
5844 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005845 if (AtomicKind != OMPC_unknown) {
5846 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5847 << SourceRange(C->getLocStart(), C->getLocEnd());
5848 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5849 << getOpenMPClauseName(AtomicKind);
5850 } else {
5851 AtomicKind = C->getClauseKind();
5852 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005853 }
5854 }
5855 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005856
Alexey Bataev459dec02014-07-24 06:46:57 +00005857 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005858 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5859 Body = EWC->getSubExpr();
5860
Alexey Bataev62cec442014-11-18 10:14:22 +00005861 Expr *X = nullptr;
5862 Expr *V = nullptr;
5863 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005864 Expr *UE = nullptr;
5865 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005866 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005867 // OpenMP [2.12.6, atomic Construct]
5868 // In the next expressions:
5869 // * x and v (as applicable) are both l-value expressions with scalar type.
5870 // * During the execution of an atomic region, multiple syntactic
5871 // occurrences of x must designate the same storage location.
5872 // * Neither of v and expr (as applicable) may access the storage location
5873 // designated by x.
5874 // * Neither of x and expr (as applicable) may access the storage location
5875 // designated by v.
5876 // * expr is an expression with scalar type.
5877 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5878 // * binop, binop=, ++, and -- are not overloaded operators.
5879 // * The expression x binop expr must be numerically equivalent to x binop
5880 // (expr). This requirement is satisfied if the operators in expr have
5881 // precedence greater than binop, or by using parentheses around expr or
5882 // subexpressions of expr.
5883 // * The expression expr binop x must be numerically equivalent to (expr)
5884 // binop x. This requirement is satisfied if the operators in expr have
5885 // precedence equal to or greater than binop, or by using parentheses around
5886 // expr or subexpressions of expr.
5887 // * For forms that allow multiple occurrences of x, the number of times
5888 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005889 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005890 enum {
5891 NotAnExpression,
5892 NotAnAssignmentOp,
5893 NotAScalarType,
5894 NotAnLValue,
5895 NoError
5896 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005897 SourceLocation ErrorLoc, NoteLoc;
5898 SourceRange ErrorRange, NoteRange;
5899 // If clause is read:
5900 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005901 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5902 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005903 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5904 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5905 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5906 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5907 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5908 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5909 if (!X->isLValue() || !V->isLValue()) {
5910 auto NotLValueExpr = X->isLValue() ? V : X;
5911 ErrorFound = NotAnLValue;
5912 ErrorLoc = AtomicBinOp->getExprLoc();
5913 ErrorRange = AtomicBinOp->getSourceRange();
5914 NoteLoc = NotLValueExpr->getExprLoc();
5915 NoteRange = NotLValueExpr->getSourceRange();
5916 }
5917 } else if (!X->isInstantiationDependent() ||
5918 !V->isInstantiationDependent()) {
5919 auto NotScalarExpr =
5920 (X->isInstantiationDependent() || X->getType()->isScalarType())
5921 ? V
5922 : X;
5923 ErrorFound = NotAScalarType;
5924 ErrorLoc = AtomicBinOp->getExprLoc();
5925 ErrorRange = AtomicBinOp->getSourceRange();
5926 NoteLoc = NotScalarExpr->getExprLoc();
5927 NoteRange = NotScalarExpr->getSourceRange();
5928 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005929 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005930 ErrorFound = NotAnAssignmentOp;
5931 ErrorLoc = AtomicBody->getExprLoc();
5932 ErrorRange = AtomicBody->getSourceRange();
5933 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5934 : AtomicBody->getExprLoc();
5935 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5936 : AtomicBody->getSourceRange();
5937 }
5938 } else {
5939 ErrorFound = NotAnExpression;
5940 NoteLoc = ErrorLoc = Body->getLocStart();
5941 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005942 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005943 if (ErrorFound != NoError) {
5944 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5945 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005946 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5947 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005948 return StmtError();
5949 } else if (CurContext->isDependentContext())
5950 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005951 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005952 enum {
5953 NotAnExpression,
5954 NotAnAssignmentOp,
5955 NotAScalarType,
5956 NotAnLValue,
5957 NoError
5958 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005959 SourceLocation ErrorLoc, NoteLoc;
5960 SourceRange ErrorRange, NoteRange;
5961 // If clause is write:
5962 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005963 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5964 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005965 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5966 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005967 X = AtomicBinOp->getLHS();
5968 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005969 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5970 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5971 if (!X->isLValue()) {
5972 ErrorFound = NotAnLValue;
5973 ErrorLoc = AtomicBinOp->getExprLoc();
5974 ErrorRange = AtomicBinOp->getSourceRange();
5975 NoteLoc = X->getExprLoc();
5976 NoteRange = X->getSourceRange();
5977 }
5978 } else if (!X->isInstantiationDependent() ||
5979 !E->isInstantiationDependent()) {
5980 auto NotScalarExpr =
5981 (X->isInstantiationDependent() || X->getType()->isScalarType())
5982 ? E
5983 : X;
5984 ErrorFound = NotAScalarType;
5985 ErrorLoc = AtomicBinOp->getExprLoc();
5986 ErrorRange = AtomicBinOp->getSourceRange();
5987 NoteLoc = NotScalarExpr->getExprLoc();
5988 NoteRange = NotScalarExpr->getSourceRange();
5989 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005990 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005991 ErrorFound = NotAnAssignmentOp;
5992 ErrorLoc = AtomicBody->getExprLoc();
5993 ErrorRange = AtomicBody->getSourceRange();
5994 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5995 : AtomicBody->getExprLoc();
5996 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5997 : AtomicBody->getSourceRange();
5998 }
5999 } else {
6000 ErrorFound = NotAnExpression;
6001 NoteLoc = ErrorLoc = Body->getLocStart();
6002 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006003 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006004 if (ErrorFound != NoError) {
6005 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6006 << ErrorRange;
6007 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6008 << NoteRange;
6009 return StmtError();
6010 } else if (CurContext->isDependentContext())
6011 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006012 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006013 // If clause is update:
6014 // x++;
6015 // x--;
6016 // ++x;
6017 // --x;
6018 // x binop= expr;
6019 // x = x binop expr;
6020 // x = expr binop x;
6021 OpenMPAtomicUpdateChecker Checker(*this);
6022 if (Checker.checkStatement(
6023 Body, (AtomicKind == OMPC_update)
6024 ? diag::err_omp_atomic_update_not_expression_statement
6025 : diag::err_omp_atomic_not_expression_statement,
6026 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006027 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006028 if (!CurContext->isDependentContext()) {
6029 E = Checker.getExpr();
6030 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006031 UE = Checker.getUpdateExpr();
6032 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006033 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006034 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006035 enum {
6036 NotAnAssignmentOp,
6037 NotACompoundStatement,
6038 NotTwoSubstatements,
6039 NotASpecificExpression,
6040 NoError
6041 } ErrorFound = NoError;
6042 SourceLocation ErrorLoc, NoteLoc;
6043 SourceRange ErrorRange, NoteRange;
6044 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6045 // If clause is a capture:
6046 // v = x++;
6047 // v = x--;
6048 // v = ++x;
6049 // v = --x;
6050 // v = x binop= expr;
6051 // v = x = x binop expr;
6052 // v = x = expr binop x;
6053 auto *AtomicBinOp =
6054 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6055 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6056 V = AtomicBinOp->getLHS();
6057 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6058 OpenMPAtomicUpdateChecker Checker(*this);
6059 if (Checker.checkStatement(
6060 Body, diag::err_omp_atomic_capture_not_expression_statement,
6061 diag::note_omp_atomic_update))
6062 return StmtError();
6063 E = Checker.getExpr();
6064 X = Checker.getX();
6065 UE = Checker.getUpdateExpr();
6066 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6067 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006068 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006069 ErrorLoc = AtomicBody->getExprLoc();
6070 ErrorRange = AtomicBody->getSourceRange();
6071 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6072 : AtomicBody->getExprLoc();
6073 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6074 : AtomicBody->getSourceRange();
6075 ErrorFound = NotAnAssignmentOp;
6076 }
6077 if (ErrorFound != NoError) {
6078 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6079 << ErrorRange;
6080 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6081 return StmtError();
6082 } else if (CurContext->isDependentContext()) {
6083 UE = V = E = X = nullptr;
6084 }
6085 } else {
6086 // If clause is a capture:
6087 // { v = x; x = expr; }
6088 // { v = x; x++; }
6089 // { v = x; x--; }
6090 // { v = x; ++x; }
6091 // { v = x; --x; }
6092 // { v = x; x binop= expr; }
6093 // { v = x; x = x binop expr; }
6094 // { v = x; x = expr binop x; }
6095 // { x++; v = x; }
6096 // { x--; v = x; }
6097 // { ++x; v = x; }
6098 // { --x; v = x; }
6099 // { x binop= expr; v = x; }
6100 // { x = x binop expr; v = x; }
6101 // { x = expr binop x; v = x; }
6102 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6103 // Check that this is { expr1; expr2; }
6104 if (CS->size() == 2) {
6105 auto *First = CS->body_front();
6106 auto *Second = CS->body_back();
6107 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6108 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6109 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6110 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6111 // Need to find what subexpression is 'v' and what is 'x'.
6112 OpenMPAtomicUpdateChecker Checker(*this);
6113 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6114 BinaryOperator *BinOp = nullptr;
6115 if (IsUpdateExprFound) {
6116 BinOp = dyn_cast<BinaryOperator>(First);
6117 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6118 }
6119 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6120 // { v = x; x++; }
6121 // { v = x; x--; }
6122 // { v = x; ++x; }
6123 // { v = x; --x; }
6124 // { v = x; x binop= expr; }
6125 // { v = x; x = x binop expr; }
6126 // { v = x; x = expr binop x; }
6127 // Check that the first expression has form v = x.
6128 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6129 llvm::FoldingSetNodeID XId, PossibleXId;
6130 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6131 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6132 IsUpdateExprFound = XId == PossibleXId;
6133 if (IsUpdateExprFound) {
6134 V = BinOp->getLHS();
6135 X = Checker.getX();
6136 E = Checker.getExpr();
6137 UE = Checker.getUpdateExpr();
6138 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006139 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006140 }
6141 }
6142 if (!IsUpdateExprFound) {
6143 IsUpdateExprFound = !Checker.checkStatement(First);
6144 BinOp = nullptr;
6145 if (IsUpdateExprFound) {
6146 BinOp = dyn_cast<BinaryOperator>(Second);
6147 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6148 }
6149 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6150 // { x++; v = x; }
6151 // { x--; v = x; }
6152 // { ++x; v = x; }
6153 // { --x; v = x; }
6154 // { x binop= expr; v = x; }
6155 // { x = x binop expr; v = x; }
6156 // { x = expr binop x; v = x; }
6157 // Check that the second expression has form v = x.
6158 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6159 llvm::FoldingSetNodeID XId, PossibleXId;
6160 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6161 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6162 IsUpdateExprFound = XId == PossibleXId;
6163 if (IsUpdateExprFound) {
6164 V = BinOp->getLHS();
6165 X = Checker.getX();
6166 E = Checker.getExpr();
6167 UE = Checker.getUpdateExpr();
6168 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006169 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006170 }
6171 }
6172 }
6173 if (!IsUpdateExprFound) {
6174 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006175 auto *FirstExpr = dyn_cast<Expr>(First);
6176 auto *SecondExpr = dyn_cast<Expr>(Second);
6177 if (!FirstExpr || !SecondExpr ||
6178 !(FirstExpr->isInstantiationDependent() ||
6179 SecondExpr->isInstantiationDependent())) {
6180 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6181 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006182 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006183 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6184 : First->getLocStart();
6185 NoteRange = ErrorRange = FirstBinOp
6186 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006187 : SourceRange(ErrorLoc, ErrorLoc);
6188 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006189 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6190 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6191 ErrorFound = NotAnAssignmentOp;
6192 NoteLoc = ErrorLoc = SecondBinOp
6193 ? SecondBinOp->getOperatorLoc()
6194 : Second->getLocStart();
6195 NoteRange = ErrorRange =
6196 SecondBinOp ? SecondBinOp->getSourceRange()
6197 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006198 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006199 auto *PossibleXRHSInFirst =
6200 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6201 auto *PossibleXLHSInSecond =
6202 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6203 llvm::FoldingSetNodeID X1Id, X2Id;
6204 PossibleXRHSInFirst->Profile(X1Id, Context,
6205 /*Canonical=*/true);
6206 PossibleXLHSInSecond->Profile(X2Id, Context,
6207 /*Canonical=*/true);
6208 IsUpdateExprFound = X1Id == X2Id;
6209 if (IsUpdateExprFound) {
6210 V = FirstBinOp->getLHS();
6211 X = SecondBinOp->getLHS();
6212 E = SecondBinOp->getRHS();
6213 UE = nullptr;
6214 IsXLHSInRHSPart = false;
6215 IsPostfixUpdate = true;
6216 } else {
6217 ErrorFound = NotASpecificExpression;
6218 ErrorLoc = FirstBinOp->getExprLoc();
6219 ErrorRange = FirstBinOp->getSourceRange();
6220 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6221 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6222 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006223 }
6224 }
6225 }
6226 }
6227 } else {
6228 NoteLoc = ErrorLoc = Body->getLocStart();
6229 NoteRange = ErrorRange =
6230 SourceRange(Body->getLocStart(), Body->getLocStart());
6231 ErrorFound = NotTwoSubstatements;
6232 }
6233 } else {
6234 NoteLoc = ErrorLoc = Body->getLocStart();
6235 NoteRange = ErrorRange =
6236 SourceRange(Body->getLocStart(), Body->getLocStart());
6237 ErrorFound = NotACompoundStatement;
6238 }
6239 if (ErrorFound != NoError) {
6240 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6241 << ErrorRange;
6242 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6243 return StmtError();
6244 } else if (CurContext->isDependentContext()) {
6245 UE = V = E = X = nullptr;
6246 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006247 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006248 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006249
6250 getCurFunction()->setHasBranchProtectedScope();
6251
Alexey Bataev62cec442014-11-18 10:14:22 +00006252 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006253 X, V, E, UE, IsXLHSInRHSPart,
6254 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006255}
6256
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006257StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6258 Stmt *AStmt,
6259 SourceLocation StartLoc,
6260 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006261 if (!AStmt)
6262 return StmtError();
6263
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006264 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6265 // 1.2.2 OpenMP Language Terminology
6266 // Structured block - An executable statement with a single entry at the
6267 // top and a single exit at the bottom.
6268 // The point of exit cannot be a branch out of the structured block.
6269 // longjmp() and throw() must not violate the entry/exit criteria.
6270 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006271
Alexey Bataev13314bf2014-10-09 04:18:56 +00006272 // OpenMP [2.16, Nesting of Regions]
6273 // If specified, a teams construct must be contained within a target
6274 // construct. That target construct must contain no statements or directives
6275 // outside of the teams construct.
6276 if (DSAStack->hasInnerTeamsRegion()) {
6277 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6278 bool OMPTeamsFound = true;
6279 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6280 auto I = CS->body_begin();
6281 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006282 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006283 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6284 OMPTeamsFound = false;
6285 break;
6286 }
6287 ++I;
6288 }
6289 assert(I != CS->body_end() && "Not found statement");
6290 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006291 } else {
6292 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6293 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006294 }
6295 if (!OMPTeamsFound) {
6296 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6297 Diag(DSAStack->getInnerTeamsRegionLoc(),
6298 diag::note_omp_nested_teams_construct_here);
6299 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6300 << isa<OMPExecutableDirective>(S);
6301 return StmtError();
6302 }
6303 }
6304
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006305 getCurFunction()->setHasBranchProtectedScope();
6306
6307 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6308}
6309
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006310StmtResult
6311Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6312 Stmt *AStmt, SourceLocation StartLoc,
6313 SourceLocation EndLoc) {
6314 if (!AStmt)
6315 return StmtError();
6316
6317 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6318 // 1.2.2 OpenMP Language Terminology
6319 // Structured block - An executable statement with a single entry at the
6320 // top and a single exit at the bottom.
6321 // The point of exit cannot be a branch out of the structured block.
6322 // longjmp() and throw() must not violate the entry/exit criteria.
6323 CS->getCapturedDecl()->setNothrow();
6324
6325 getCurFunction()->setHasBranchProtectedScope();
6326
6327 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6328 AStmt);
6329}
6330
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006331StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6332 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6333 SourceLocation EndLoc,
6334 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6335 if (!AStmt)
6336 return StmtError();
6337
6338 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6339 // 1.2.2 OpenMP Language Terminology
6340 // Structured block - An executable statement with a single entry at the
6341 // top and a single exit at the bottom.
6342 // The point of exit cannot be a branch out of the structured block.
6343 // longjmp() and throw() must not violate the entry/exit criteria.
6344 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006345 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6346 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6347 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6348 // 1.2.2 OpenMP Language Terminology
6349 // Structured block - An executable statement with a single entry at the
6350 // top and a single exit at the bottom.
6351 // The point of exit cannot be a branch out of the structured block.
6352 // longjmp() and throw() must not violate the entry/exit criteria.
6353 CS->getCapturedDecl()->setNothrow();
6354 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006355
6356 OMPLoopDirective::HelperExprs B;
6357 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6358 // define the nested loops number.
6359 unsigned NestedLoopCount =
6360 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006361 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006362 VarsWithImplicitDSA, B);
6363 if (NestedLoopCount == 0)
6364 return StmtError();
6365
6366 assert((CurContext->isDependentContext() || B.builtAll()) &&
6367 "omp target parallel for loop exprs were not built");
6368
6369 if (!CurContext->isDependentContext()) {
6370 // Finalize the clauses that need pre-built expressions for CodeGen.
6371 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006372 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006373 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006374 B.NumIterations, *this, CurScope,
6375 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006376 return StmtError();
6377 }
6378 }
6379
6380 getCurFunction()->setHasBranchProtectedScope();
6381 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6382 NestedLoopCount, Clauses, AStmt,
6383 B, DSAStack->isCancelRegion());
6384}
6385
Alexey Bataev95b64a92017-05-30 16:00:04 +00006386/// Check for existence of a map clause in the list of clauses.
6387static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6388 const OpenMPClauseKind K) {
6389 return llvm::any_of(
6390 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6391}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006392
Alexey Bataev95b64a92017-05-30 16:00:04 +00006393template <typename... Params>
6394static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6395 const Params... ClauseTypes) {
6396 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006397}
6398
Michael Wong65f367f2015-07-21 13:44:28 +00006399StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6400 Stmt *AStmt,
6401 SourceLocation StartLoc,
6402 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006403 if (!AStmt)
6404 return StmtError();
6405
6406 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6407
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006408 // OpenMP [2.10.1, Restrictions, p. 97]
6409 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006410 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6411 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6412 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006413 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006414 return StmtError();
6415 }
6416
Michael Wong65f367f2015-07-21 13:44:28 +00006417 getCurFunction()->setHasBranchProtectedScope();
6418
6419 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6420 AStmt);
6421}
6422
Samuel Antaodf67fc42016-01-19 19:15:56 +00006423StmtResult
6424Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6425 SourceLocation StartLoc,
6426 SourceLocation EndLoc) {
6427 // OpenMP [2.10.2, Restrictions, p. 99]
6428 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006429 if (!hasClauses(Clauses, OMPC_map)) {
6430 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6431 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006432 return StmtError();
6433 }
6434
6435 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6436 Clauses);
6437}
6438
Samuel Antao72590762016-01-19 20:04:50 +00006439StmtResult
6440Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6441 SourceLocation StartLoc,
6442 SourceLocation EndLoc) {
6443 // OpenMP [2.10.3, Restrictions, p. 102]
6444 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006445 if (!hasClauses(Clauses, OMPC_map)) {
6446 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6447 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006448 return StmtError();
6449 }
6450
6451 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6452}
6453
Samuel Antao686c70c2016-05-26 17:30:50 +00006454StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6455 SourceLocation StartLoc,
6456 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006457 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006458 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6459 return StmtError();
6460 }
6461 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6462}
6463
Alexey Bataev13314bf2014-10-09 04:18:56 +00006464StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6465 Stmt *AStmt, SourceLocation StartLoc,
6466 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006467 if (!AStmt)
6468 return StmtError();
6469
Alexey Bataev13314bf2014-10-09 04:18:56 +00006470 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6471 // 1.2.2 OpenMP Language Terminology
6472 // Structured block - An executable statement with a single entry at the
6473 // top and a single exit at the bottom.
6474 // The point of exit cannot be a branch out of the structured block.
6475 // longjmp() and throw() must not violate the entry/exit criteria.
6476 CS->getCapturedDecl()->setNothrow();
6477
6478 getCurFunction()->setHasBranchProtectedScope();
6479
6480 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6481}
6482
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006483StmtResult
6484Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6485 SourceLocation EndLoc,
6486 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006487 if (DSAStack->isParentNowaitRegion()) {
6488 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6489 return StmtError();
6490 }
6491 if (DSAStack->isParentOrderedRegion()) {
6492 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6493 return StmtError();
6494 }
6495 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6496 CancelRegion);
6497}
6498
Alexey Bataev87933c72015-09-18 08:07:34 +00006499StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6500 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006501 SourceLocation EndLoc,
6502 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006503 if (DSAStack->isParentNowaitRegion()) {
6504 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6505 return StmtError();
6506 }
6507 if (DSAStack->isParentOrderedRegion()) {
6508 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6509 return StmtError();
6510 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006511 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006512 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6513 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006514}
6515
Alexey Bataev382967a2015-12-08 12:06:20 +00006516static bool checkGrainsizeNumTasksClauses(Sema &S,
6517 ArrayRef<OMPClause *> Clauses) {
6518 OMPClause *PrevClause = nullptr;
6519 bool ErrorFound = false;
6520 for (auto *C : Clauses) {
6521 if (C->getClauseKind() == OMPC_grainsize ||
6522 C->getClauseKind() == OMPC_num_tasks) {
6523 if (!PrevClause)
6524 PrevClause = C;
6525 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6526 S.Diag(C->getLocStart(),
6527 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6528 << getOpenMPClauseName(C->getClauseKind())
6529 << getOpenMPClauseName(PrevClause->getClauseKind());
6530 S.Diag(PrevClause->getLocStart(),
6531 diag::note_omp_previous_grainsize_num_tasks)
6532 << getOpenMPClauseName(PrevClause->getClauseKind());
6533 ErrorFound = true;
6534 }
6535 }
6536 }
6537 return ErrorFound;
6538}
6539
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006540static bool checkReductionClauseWithNogroup(Sema &S,
6541 ArrayRef<OMPClause *> Clauses) {
6542 OMPClause *ReductionClause = nullptr;
6543 OMPClause *NogroupClause = nullptr;
6544 for (auto *C : Clauses) {
6545 if (C->getClauseKind() == OMPC_reduction) {
6546 ReductionClause = C;
6547 if (NogroupClause)
6548 break;
6549 continue;
6550 }
6551 if (C->getClauseKind() == OMPC_nogroup) {
6552 NogroupClause = C;
6553 if (ReductionClause)
6554 break;
6555 continue;
6556 }
6557 }
6558 if (ReductionClause && NogroupClause) {
6559 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6560 << SourceRange(NogroupClause->getLocStart(),
6561 NogroupClause->getLocEnd());
6562 return true;
6563 }
6564 return false;
6565}
6566
Alexey Bataev49f6e782015-12-01 04:18:41 +00006567StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6568 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6569 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006570 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006571 if (!AStmt)
6572 return StmtError();
6573
6574 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6575 OMPLoopDirective::HelperExprs B;
6576 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6577 // define the nested loops number.
6578 unsigned NestedLoopCount =
6579 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006580 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006581 VarsWithImplicitDSA, B);
6582 if (NestedLoopCount == 0)
6583 return StmtError();
6584
6585 assert((CurContext->isDependentContext() || B.builtAll()) &&
6586 "omp for loop exprs were not built");
6587
Alexey Bataev382967a2015-12-08 12:06:20 +00006588 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6589 // The grainsize clause and num_tasks clause are mutually exclusive and may
6590 // not appear on the same taskloop directive.
6591 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6592 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006593 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6594 // If a reduction clause is present on the taskloop directive, the nogroup
6595 // clause must not be specified.
6596 if (checkReductionClauseWithNogroup(*this, Clauses))
6597 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006598
Alexey Bataev49f6e782015-12-01 04:18:41 +00006599 getCurFunction()->setHasBranchProtectedScope();
6600 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6601 NestedLoopCount, Clauses, AStmt, B);
6602}
6603
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006604StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6605 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6606 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006607 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006608 if (!AStmt)
6609 return StmtError();
6610
6611 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6612 OMPLoopDirective::HelperExprs B;
6613 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6614 // define the nested loops number.
6615 unsigned NestedLoopCount =
6616 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6617 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6618 VarsWithImplicitDSA, B);
6619 if (NestedLoopCount == 0)
6620 return StmtError();
6621
6622 assert((CurContext->isDependentContext() || B.builtAll()) &&
6623 "omp for loop exprs were not built");
6624
Alexey Bataev5a3af132016-03-29 08:58:54 +00006625 if (!CurContext->isDependentContext()) {
6626 // Finalize the clauses that need pre-built expressions for CodeGen.
6627 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006628 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006629 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006630 B.NumIterations, *this, CurScope,
6631 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006632 return StmtError();
6633 }
6634 }
6635
Alexey Bataev382967a2015-12-08 12:06:20 +00006636 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6637 // The grainsize clause and num_tasks clause are mutually exclusive and may
6638 // not appear on the same taskloop directive.
6639 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6640 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006641 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6642 // If a reduction clause is present on the taskloop directive, the nogroup
6643 // clause must not be specified.
6644 if (checkReductionClauseWithNogroup(*this, Clauses))
6645 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006646
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006647 getCurFunction()->setHasBranchProtectedScope();
6648 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6649 NestedLoopCount, Clauses, AStmt, B);
6650}
6651
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006652StmtResult Sema::ActOnOpenMPDistributeDirective(
6653 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6654 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006655 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006656 if (!AStmt)
6657 return StmtError();
6658
6659 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6660 OMPLoopDirective::HelperExprs B;
6661 // In presence of clause 'collapse' with number of loops, it will
6662 // define the nested loops number.
6663 unsigned NestedLoopCount =
6664 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6665 nullptr /*ordered not a clause on distribute*/, AStmt,
6666 *this, *DSAStack, VarsWithImplicitDSA, B);
6667 if (NestedLoopCount == 0)
6668 return StmtError();
6669
6670 assert((CurContext->isDependentContext() || B.builtAll()) &&
6671 "omp for loop exprs were not built");
6672
6673 getCurFunction()->setHasBranchProtectedScope();
6674 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6675 NestedLoopCount, Clauses, AStmt, B);
6676}
6677
Carlo Bertolli9925f152016-06-27 14:55:37 +00006678StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6679 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6680 SourceLocation EndLoc,
6681 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6682 if (!AStmt)
6683 return StmtError();
6684
6685 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6686 // 1.2.2 OpenMP Language Terminology
6687 // Structured block - An executable statement with a single entry at the
6688 // top and a single exit at the bottom.
6689 // The point of exit cannot be a branch out of the structured block.
6690 // longjmp() and throw() must not violate the entry/exit criteria.
6691 CS->getCapturedDecl()->setNothrow();
6692
6693 OMPLoopDirective::HelperExprs B;
6694 // In presence of clause 'collapse' with number of loops, it will
6695 // define the nested loops number.
6696 unsigned NestedLoopCount = CheckOpenMPLoop(
6697 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6698 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6699 VarsWithImplicitDSA, B);
6700 if (NestedLoopCount == 0)
6701 return StmtError();
6702
6703 assert((CurContext->isDependentContext() || B.builtAll()) &&
6704 "omp for loop exprs were not built");
6705
6706 getCurFunction()->setHasBranchProtectedScope();
6707 return OMPDistributeParallelForDirective::Create(
6708 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6709}
6710
Kelvin Li4a39add2016-07-05 05:00:15 +00006711StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6713 SourceLocation EndLoc,
6714 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6715 if (!AStmt)
6716 return StmtError();
6717
6718 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6719 // 1.2.2 OpenMP Language Terminology
6720 // Structured block - An executable statement with a single entry at the
6721 // top and a single exit at the bottom.
6722 // The point of exit cannot be a branch out of the structured block.
6723 // longjmp() and throw() must not violate the entry/exit criteria.
6724 CS->getCapturedDecl()->setNothrow();
6725
6726 OMPLoopDirective::HelperExprs B;
6727 // In presence of clause 'collapse' with number of loops, it will
6728 // define the nested loops number.
6729 unsigned NestedLoopCount = CheckOpenMPLoop(
6730 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6731 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6732 VarsWithImplicitDSA, B);
6733 if (NestedLoopCount == 0)
6734 return StmtError();
6735
6736 assert((CurContext->isDependentContext() || B.builtAll()) &&
6737 "omp for loop exprs were not built");
6738
Kelvin Lic5609492016-07-15 04:39:07 +00006739 if (checkSimdlenSafelenSpecified(*this, Clauses))
6740 return StmtError();
6741
Kelvin Li4a39add2016-07-05 05:00:15 +00006742 getCurFunction()->setHasBranchProtectedScope();
6743 return OMPDistributeParallelForSimdDirective::Create(
6744 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6745}
6746
Kelvin Li787f3fc2016-07-06 04:45:38 +00006747StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6748 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6749 SourceLocation EndLoc,
6750 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6751 if (!AStmt)
6752 return StmtError();
6753
6754 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6755 // 1.2.2 OpenMP Language Terminology
6756 // Structured block - An executable statement with a single entry at the
6757 // top and a single exit at the bottom.
6758 // The point of exit cannot be a branch out of the structured block.
6759 // longjmp() and throw() must not violate the entry/exit criteria.
6760 CS->getCapturedDecl()->setNothrow();
6761
6762 OMPLoopDirective::HelperExprs B;
6763 // In presence of clause 'collapse' with number of loops, it will
6764 // define the nested loops number.
6765 unsigned NestedLoopCount =
6766 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6767 nullptr /*ordered not a clause on distribute*/, AStmt,
6768 *this, *DSAStack, VarsWithImplicitDSA, B);
6769 if (NestedLoopCount == 0)
6770 return StmtError();
6771
6772 assert((CurContext->isDependentContext() || B.builtAll()) &&
6773 "omp for loop exprs were not built");
6774
Kelvin Lic5609492016-07-15 04:39:07 +00006775 if (checkSimdlenSafelenSpecified(*this, Clauses))
6776 return StmtError();
6777
Kelvin Li787f3fc2016-07-06 04:45:38 +00006778 getCurFunction()->setHasBranchProtectedScope();
6779 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6780 NestedLoopCount, Clauses, AStmt, B);
6781}
6782
Kelvin Lia579b912016-07-14 02:54:56 +00006783StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6784 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6785 SourceLocation EndLoc,
6786 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6787 if (!AStmt)
6788 return StmtError();
6789
6790 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6791 // 1.2.2 OpenMP Language Terminology
6792 // Structured block - An executable statement with a single entry at the
6793 // top and a single exit at the bottom.
6794 // The point of exit cannot be a branch out of the structured block.
6795 // longjmp() and throw() must not violate the entry/exit criteria.
6796 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006797 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6798 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6799 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6800 // 1.2.2 OpenMP Language Terminology
6801 // Structured block - An executable statement with a single entry at the
6802 // top and a single exit at the bottom.
6803 // The point of exit cannot be a branch out of the structured block.
6804 // longjmp() and throw() must not violate the entry/exit criteria.
6805 CS->getCapturedDecl()->setNothrow();
6806 }
Kelvin Lia579b912016-07-14 02:54:56 +00006807
6808 OMPLoopDirective::HelperExprs B;
6809 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6810 // define the nested loops number.
6811 unsigned NestedLoopCount = CheckOpenMPLoop(
6812 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006813 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00006814 VarsWithImplicitDSA, B);
6815 if (NestedLoopCount == 0)
6816 return StmtError();
6817
6818 assert((CurContext->isDependentContext() || B.builtAll()) &&
6819 "omp target parallel for simd loop exprs were not built");
6820
6821 if (!CurContext->isDependentContext()) {
6822 // Finalize the clauses that need pre-built expressions for CodeGen.
6823 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006824 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006825 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6826 B.NumIterations, *this, CurScope,
6827 DSAStack))
6828 return StmtError();
6829 }
6830 }
Kelvin Lic5609492016-07-15 04:39:07 +00006831 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006832 return StmtError();
6833
6834 getCurFunction()->setHasBranchProtectedScope();
6835 return OMPTargetParallelForSimdDirective::Create(
6836 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6837}
6838
Kelvin Li986330c2016-07-20 22:57:10 +00006839StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6840 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6841 SourceLocation EndLoc,
6842 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6843 if (!AStmt)
6844 return StmtError();
6845
6846 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6847 // 1.2.2 OpenMP Language Terminology
6848 // Structured block - An executable statement with a single entry at the
6849 // top and a single exit at the bottom.
6850 // The point of exit cannot be a branch out of the structured block.
6851 // longjmp() and throw() must not violate the entry/exit criteria.
6852 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00006853 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
6854 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6855 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6856 // 1.2.2 OpenMP Language Terminology
6857 // Structured block - An executable statement with a single entry at the
6858 // top and a single exit at the bottom.
6859 // The point of exit cannot be a branch out of the structured block.
6860 // longjmp() and throw() must not violate the entry/exit criteria.
6861 CS->getCapturedDecl()->setNothrow();
6862 }
6863
Kelvin Li986330c2016-07-20 22:57:10 +00006864
6865 OMPLoopDirective::HelperExprs B;
6866 // In presence of clause 'collapse' with number of loops, it will define the
6867 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006868 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006869 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00006870 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00006871 VarsWithImplicitDSA, B);
6872 if (NestedLoopCount == 0)
6873 return StmtError();
6874
6875 assert((CurContext->isDependentContext() || B.builtAll()) &&
6876 "omp target simd loop exprs were not built");
6877
6878 if (!CurContext->isDependentContext()) {
6879 // Finalize the clauses that need pre-built expressions for CodeGen.
6880 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006881 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006882 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6883 B.NumIterations, *this, CurScope,
6884 DSAStack))
6885 return StmtError();
6886 }
6887 }
6888
6889 if (checkSimdlenSafelenSpecified(*this, Clauses))
6890 return StmtError();
6891
6892 getCurFunction()->setHasBranchProtectedScope();
6893 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6894 NestedLoopCount, Clauses, AStmt, B);
6895}
6896
Kelvin Li02532872016-08-05 14:37:37 +00006897StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6898 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6899 SourceLocation EndLoc,
6900 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6901 if (!AStmt)
6902 return StmtError();
6903
6904 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6905 // 1.2.2 OpenMP Language Terminology
6906 // Structured block - An executable statement with a single entry at the
6907 // top and a single exit at the bottom.
6908 // The point of exit cannot be a branch out of the structured block.
6909 // longjmp() and throw() must not violate the entry/exit criteria.
6910 CS->getCapturedDecl()->setNothrow();
6911
6912 OMPLoopDirective::HelperExprs B;
6913 // In presence of clause 'collapse' with number of loops, it will
6914 // define the nested loops number.
6915 unsigned NestedLoopCount =
6916 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6917 nullptr /*ordered not a clause on distribute*/, AStmt,
6918 *this, *DSAStack, VarsWithImplicitDSA, B);
6919 if (NestedLoopCount == 0)
6920 return StmtError();
6921
6922 assert((CurContext->isDependentContext() || B.builtAll()) &&
6923 "omp teams distribute loop exprs were not built");
6924
6925 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006926 return OMPTeamsDistributeDirective::Create(
6927 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006928}
6929
Kelvin Li4e325f72016-10-25 12:50:55 +00006930StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6931 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6932 SourceLocation EndLoc,
6933 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6934 if (!AStmt)
6935 return StmtError();
6936
6937 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6938 // 1.2.2 OpenMP Language Terminology
6939 // Structured block - An executable statement with a single entry at the
6940 // top and a single exit at the bottom.
6941 // The point of exit cannot be a branch out of the structured block.
6942 // longjmp() and throw() must not violate the entry/exit criteria.
6943 CS->getCapturedDecl()->setNothrow();
6944
6945 OMPLoopDirective::HelperExprs B;
6946 // In presence of clause 'collapse' with number of loops, it will
6947 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006948 unsigned NestedLoopCount = CheckOpenMPLoop(
6949 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6950 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6951 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006952
6953 if (NestedLoopCount == 0)
6954 return StmtError();
6955
6956 assert((CurContext->isDependentContext() || B.builtAll()) &&
6957 "omp teams distribute simd loop exprs were not built");
6958
6959 if (!CurContext->isDependentContext()) {
6960 // Finalize the clauses that need pre-built expressions for CodeGen.
6961 for (auto C : Clauses) {
6962 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6963 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6964 B.NumIterations, *this, CurScope,
6965 DSAStack))
6966 return StmtError();
6967 }
6968 }
6969
6970 if (checkSimdlenSafelenSpecified(*this, Clauses))
6971 return StmtError();
6972
6973 getCurFunction()->setHasBranchProtectedScope();
6974 return OMPTeamsDistributeSimdDirective::Create(
6975 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6976}
6977
Kelvin Li579e41c2016-11-30 23:51:03 +00006978StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6979 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6980 SourceLocation EndLoc,
6981 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6982 if (!AStmt)
6983 return StmtError();
6984
6985 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6986 // 1.2.2 OpenMP Language Terminology
6987 // Structured block - An executable statement with a single entry at the
6988 // top and a single exit at the bottom.
6989 // The point of exit cannot be a branch out of the structured block.
6990 // longjmp() and throw() must not violate the entry/exit criteria.
6991 CS->getCapturedDecl()->setNothrow();
6992
6993 OMPLoopDirective::HelperExprs B;
6994 // In presence of clause 'collapse' with number of loops, it will
6995 // define the nested loops number.
6996 auto NestedLoopCount = CheckOpenMPLoop(
6997 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6998 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6999 VarsWithImplicitDSA, B);
7000
7001 if (NestedLoopCount == 0)
7002 return StmtError();
7003
7004 assert((CurContext->isDependentContext() || B.builtAll()) &&
7005 "omp for loop exprs were not built");
7006
7007 if (!CurContext->isDependentContext()) {
7008 // Finalize the clauses that need pre-built expressions for CodeGen.
7009 for (auto C : Clauses) {
7010 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7011 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7012 B.NumIterations, *this, CurScope,
7013 DSAStack))
7014 return StmtError();
7015 }
7016 }
7017
7018 if (checkSimdlenSafelenSpecified(*this, Clauses))
7019 return StmtError();
7020
7021 getCurFunction()->setHasBranchProtectedScope();
7022 return OMPTeamsDistributeParallelForSimdDirective::Create(
7023 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7024}
7025
Kelvin Li7ade93f2016-12-09 03:24:30 +00007026StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7027 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7028 SourceLocation EndLoc,
7029 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7030 if (!AStmt)
7031 return StmtError();
7032
7033 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7034 // 1.2.2 OpenMP Language Terminology
7035 // Structured block - An executable statement with a single entry at the
7036 // top and a single exit at the bottom.
7037 // The point of exit cannot be a branch out of the structured block.
7038 // longjmp() and throw() must not violate the entry/exit criteria.
7039 CS->getCapturedDecl()->setNothrow();
7040
Carlo Bertolli62fae152017-11-20 20:46:39 +00007041 for (int ThisCaptureLevel =
7042 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7043 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7044 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7045 // 1.2.2 OpenMP Language Terminology
7046 // Structured block - An executable statement with a single entry at the
7047 // top and a single exit at the bottom.
7048 // The point of exit cannot be a branch out of the structured block.
7049 // longjmp() and throw() must not violate the entry/exit criteria.
7050 CS->getCapturedDecl()->setNothrow();
7051 }
7052
Kelvin Li7ade93f2016-12-09 03:24:30 +00007053 OMPLoopDirective::HelperExprs B;
7054 // In presence of clause 'collapse' with number of loops, it will
7055 // define the nested loops number.
7056 unsigned NestedLoopCount = CheckOpenMPLoop(
7057 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007058 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007059 VarsWithImplicitDSA, B);
7060
7061 if (NestedLoopCount == 0)
7062 return StmtError();
7063
7064 assert((CurContext->isDependentContext() || B.builtAll()) &&
7065 "omp for loop exprs were not built");
7066
7067 if (!CurContext->isDependentContext()) {
7068 // Finalize the clauses that need pre-built expressions for CodeGen.
7069 for (auto C : Clauses) {
7070 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7071 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7072 B.NumIterations, *this, CurScope,
7073 DSAStack))
7074 return StmtError();
7075 }
7076 }
7077
7078 getCurFunction()->setHasBranchProtectedScope();
7079 return OMPTeamsDistributeParallelForDirective::Create(
7080 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7081}
7082
Kelvin Libf594a52016-12-17 05:48:59 +00007083StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7084 Stmt *AStmt,
7085 SourceLocation StartLoc,
7086 SourceLocation EndLoc) {
7087 if (!AStmt)
7088 return StmtError();
7089
7090 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7091 // 1.2.2 OpenMP Language Terminology
7092 // Structured block - An executable statement with a single entry at the
7093 // top and a single exit at the bottom.
7094 // The point of exit cannot be a branch out of the structured block.
7095 // longjmp() and throw() must not violate the entry/exit criteria.
7096 CS->getCapturedDecl()->setNothrow();
7097
7098 getCurFunction()->setHasBranchProtectedScope();
7099
7100 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7101 AStmt);
7102}
7103
Kelvin Li83c451e2016-12-25 04:52:54 +00007104StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7105 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7106 SourceLocation EndLoc,
7107 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7108 if (!AStmt)
7109 return StmtError();
7110
7111 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7112 // 1.2.2 OpenMP Language Terminology
7113 // Structured block - An executable statement with a single entry at the
7114 // top and a single exit at the bottom.
7115 // The point of exit cannot be a branch out of the structured block.
7116 // longjmp() and throw() must not violate the entry/exit criteria.
7117 CS->getCapturedDecl()->setNothrow();
7118
7119 OMPLoopDirective::HelperExprs B;
7120 // In presence of clause 'collapse' with number of loops, it will
7121 // define the nested loops number.
7122 auto NestedLoopCount = CheckOpenMPLoop(
7123 OMPD_target_teams_distribute,
7124 getCollapseNumberExpr(Clauses),
7125 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7126 VarsWithImplicitDSA, B);
7127 if (NestedLoopCount == 0)
7128 return StmtError();
7129
7130 assert((CurContext->isDependentContext() || B.builtAll()) &&
7131 "omp target teams distribute loop exprs were not built");
7132
7133 getCurFunction()->setHasBranchProtectedScope();
7134 return OMPTargetTeamsDistributeDirective::Create(
7135 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7136}
7137
Kelvin Li80e8f562016-12-29 22:16:30 +00007138StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7139 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7140 SourceLocation EndLoc,
7141 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7142 if (!AStmt)
7143 return StmtError();
7144
7145 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7146 // 1.2.2 OpenMP Language Terminology
7147 // Structured block - An executable statement with a single entry at the
7148 // top and a single exit at the bottom.
7149 // The point of exit cannot be a branch out of the structured block.
7150 // longjmp() and throw() must not violate the entry/exit criteria.
7151 CS->getCapturedDecl()->setNothrow();
7152
7153 OMPLoopDirective::HelperExprs B;
7154 // In presence of clause 'collapse' with number of loops, it will
7155 // define the nested loops number.
7156 auto NestedLoopCount = CheckOpenMPLoop(
7157 OMPD_target_teams_distribute_parallel_for,
7158 getCollapseNumberExpr(Clauses),
7159 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7160 VarsWithImplicitDSA, B);
7161 if (NestedLoopCount == 0)
7162 return StmtError();
7163
7164 assert((CurContext->isDependentContext() || B.builtAll()) &&
7165 "omp target teams distribute parallel for loop exprs were not built");
7166
7167 if (!CurContext->isDependentContext()) {
7168 // Finalize the clauses that need pre-built expressions for CodeGen.
7169 for (auto C : Clauses) {
7170 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7171 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7172 B.NumIterations, *this, CurScope,
7173 DSAStack))
7174 return StmtError();
7175 }
7176 }
7177
7178 getCurFunction()->setHasBranchProtectedScope();
7179 return OMPTargetTeamsDistributeParallelForDirective::Create(
7180 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7181}
7182
Kelvin Li1851df52017-01-03 05:23:48 +00007183StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7184 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7185 SourceLocation EndLoc,
7186 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7187 if (!AStmt)
7188 return StmtError();
7189
7190 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7191 // 1.2.2 OpenMP Language Terminology
7192 // Structured block - An executable statement with a single entry at the
7193 // top and a single exit at the bottom.
7194 // The point of exit cannot be a branch out of the structured block.
7195 // longjmp() and throw() must not violate the entry/exit criteria.
7196 CS->getCapturedDecl()->setNothrow();
7197
7198 OMPLoopDirective::HelperExprs B;
7199 // In presence of clause 'collapse' with number of loops, it will
7200 // define the nested loops number.
7201 auto NestedLoopCount = CheckOpenMPLoop(
7202 OMPD_target_teams_distribute_parallel_for_simd,
7203 getCollapseNumberExpr(Clauses),
7204 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7205 VarsWithImplicitDSA, B);
7206 if (NestedLoopCount == 0)
7207 return StmtError();
7208
7209 assert((CurContext->isDependentContext() || B.builtAll()) &&
7210 "omp target teams distribute parallel for simd loop exprs were not "
7211 "built");
7212
7213 if (!CurContext->isDependentContext()) {
7214 // Finalize the clauses that need pre-built expressions for CodeGen.
7215 for (auto C : Clauses) {
7216 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7217 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7218 B.NumIterations, *this, CurScope,
7219 DSAStack))
7220 return StmtError();
7221 }
7222 }
7223
7224 getCurFunction()->setHasBranchProtectedScope();
7225 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7226 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7227}
7228
Kelvin Lida681182017-01-10 18:08:18 +00007229StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7230 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7231 SourceLocation EndLoc,
7232 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7233 if (!AStmt)
7234 return StmtError();
7235
7236 auto *CS = cast<CapturedStmt>(AStmt);
7237 // 1.2.2 OpenMP Language Terminology
7238 // Structured block - An executable statement with a single entry at the
7239 // top and a single exit at the bottom.
7240 // The point of exit cannot be a branch out of the structured block.
7241 // longjmp() and throw() must not violate the entry/exit criteria.
7242 CS->getCapturedDecl()->setNothrow();
7243
7244 OMPLoopDirective::HelperExprs B;
7245 // In presence of clause 'collapse' with number of loops, it will
7246 // define the nested loops number.
7247 auto NestedLoopCount = CheckOpenMPLoop(
7248 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7249 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7250 VarsWithImplicitDSA, B);
7251 if (NestedLoopCount == 0)
7252 return StmtError();
7253
7254 assert((CurContext->isDependentContext() || B.builtAll()) &&
7255 "omp target teams distribute simd loop exprs were not built");
7256
7257 getCurFunction()->setHasBranchProtectedScope();
7258 return OMPTargetTeamsDistributeSimdDirective::Create(
7259 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7260}
7261
Alexey Bataeved09d242014-05-28 05:53:51 +00007262OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007263 SourceLocation StartLoc,
7264 SourceLocation LParenLoc,
7265 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007266 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007267 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007268 case OMPC_final:
7269 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7270 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007271 case OMPC_num_threads:
7272 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7273 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007274 case OMPC_safelen:
7275 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7276 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007277 case OMPC_simdlen:
7278 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7279 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007280 case OMPC_collapse:
7281 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7282 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007283 case OMPC_ordered:
7284 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7285 break;
Michael Wonge710d542015-08-07 16:16:36 +00007286 case OMPC_device:
7287 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7288 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007289 case OMPC_num_teams:
7290 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7291 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007292 case OMPC_thread_limit:
7293 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7294 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007295 case OMPC_priority:
7296 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7297 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007298 case OMPC_grainsize:
7299 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7300 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007301 case OMPC_num_tasks:
7302 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7303 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007304 case OMPC_hint:
7305 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7306 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007307 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007308 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007309 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007310 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007311 case OMPC_private:
7312 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007313 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007314 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007315 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007316 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007317 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007318 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007319 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007320 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007321 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007322 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007323 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007324 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007325 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007326 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007327 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007328 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007329 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007330 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007331 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007332 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007333 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007334 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007335 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007336 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007337 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007338 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007339 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007340 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007341 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007342 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007343 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007344 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007345 llvm_unreachable("Clause is not allowed.");
7346 }
7347 return Res;
7348}
7349
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007350// An OpenMP directive such as 'target parallel' has two captured regions:
7351// for the 'target' and 'parallel' respectively. This function returns
7352// the region in which to capture expressions associated with a clause.
7353// A return value of OMPD_unknown signifies that the expression should not
7354// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007355static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7356 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7357 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007358 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7359
7360 switch (CKind) {
7361 case OMPC_if:
7362 switch (DKind) {
7363 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007364 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007365 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007366 // If this clause applies to the nested 'parallel' region, capture within
7367 // the 'target' region, otherwise do not capture.
7368 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7369 CaptureRegion = OMPD_target;
7370 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007371 case OMPD_teams_distribute_parallel_for:
7372 CaptureRegion = OMPD_teams;
7373 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007374 case OMPD_cancel:
7375 case OMPD_parallel:
7376 case OMPD_parallel_sections:
7377 case OMPD_parallel_for:
7378 case OMPD_parallel_for_simd:
7379 case OMPD_target:
7380 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007381 case OMPD_target_teams:
7382 case OMPD_target_teams_distribute:
7383 case OMPD_target_teams_distribute_simd:
7384 case OMPD_target_teams_distribute_parallel_for:
7385 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007386 case OMPD_teams_distribute_parallel_for_simd:
7387 case OMPD_distribute_parallel_for:
7388 case OMPD_distribute_parallel_for_simd:
7389 case OMPD_task:
7390 case OMPD_taskloop:
7391 case OMPD_taskloop_simd:
7392 case OMPD_target_data:
7393 case OMPD_target_enter_data:
7394 case OMPD_target_exit_data:
7395 case OMPD_target_update:
7396 // Do not capture if-clause expressions.
7397 break;
7398 case OMPD_threadprivate:
7399 case OMPD_taskyield:
7400 case OMPD_barrier:
7401 case OMPD_taskwait:
7402 case OMPD_cancellation_point:
7403 case OMPD_flush:
7404 case OMPD_declare_reduction:
7405 case OMPD_declare_simd:
7406 case OMPD_declare_target:
7407 case OMPD_end_declare_target:
7408 case OMPD_teams:
7409 case OMPD_simd:
7410 case OMPD_for:
7411 case OMPD_for_simd:
7412 case OMPD_sections:
7413 case OMPD_section:
7414 case OMPD_single:
7415 case OMPD_master:
7416 case OMPD_critical:
7417 case OMPD_taskgroup:
7418 case OMPD_distribute:
7419 case OMPD_ordered:
7420 case OMPD_atomic:
7421 case OMPD_distribute_simd:
7422 case OMPD_teams_distribute:
7423 case OMPD_teams_distribute_simd:
7424 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7425 case OMPD_unknown:
7426 llvm_unreachable("Unknown OpenMP directive");
7427 }
7428 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007429 case OMPC_num_threads:
7430 switch (DKind) {
7431 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007432 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007433 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007434 CaptureRegion = OMPD_target;
7435 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007436 case OMPD_teams_distribute_parallel_for:
7437 CaptureRegion = OMPD_teams;
7438 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007439 case OMPD_cancel:
7440 case OMPD_parallel:
7441 case OMPD_parallel_sections:
7442 case OMPD_parallel_for:
7443 case OMPD_parallel_for_simd:
7444 case OMPD_target:
7445 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007446 case OMPD_target_teams:
7447 case OMPD_target_teams_distribute:
7448 case OMPD_target_teams_distribute_simd:
7449 case OMPD_target_teams_distribute_parallel_for:
7450 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007451 case OMPD_teams_distribute_parallel_for_simd:
7452 case OMPD_distribute_parallel_for:
7453 case OMPD_distribute_parallel_for_simd:
7454 case OMPD_task:
7455 case OMPD_taskloop:
7456 case OMPD_taskloop_simd:
7457 case OMPD_target_data:
7458 case OMPD_target_enter_data:
7459 case OMPD_target_exit_data:
7460 case OMPD_target_update:
7461 // Do not capture num_threads-clause expressions.
7462 break;
7463 case OMPD_threadprivate:
7464 case OMPD_taskyield:
7465 case OMPD_barrier:
7466 case OMPD_taskwait:
7467 case OMPD_cancellation_point:
7468 case OMPD_flush:
7469 case OMPD_declare_reduction:
7470 case OMPD_declare_simd:
7471 case OMPD_declare_target:
7472 case OMPD_end_declare_target:
7473 case OMPD_teams:
7474 case OMPD_simd:
7475 case OMPD_for:
7476 case OMPD_for_simd:
7477 case OMPD_sections:
7478 case OMPD_section:
7479 case OMPD_single:
7480 case OMPD_master:
7481 case OMPD_critical:
7482 case OMPD_taskgroup:
7483 case OMPD_distribute:
7484 case OMPD_ordered:
7485 case OMPD_atomic:
7486 case OMPD_distribute_simd:
7487 case OMPD_teams_distribute:
7488 case OMPD_teams_distribute_simd:
7489 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7490 case OMPD_unknown:
7491 llvm_unreachable("Unknown OpenMP directive");
7492 }
7493 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007494 case OMPC_num_teams:
7495 switch (DKind) {
7496 case OMPD_target_teams:
7497 CaptureRegion = OMPD_target;
7498 break;
7499 case OMPD_cancel:
7500 case OMPD_parallel:
7501 case OMPD_parallel_sections:
7502 case OMPD_parallel_for:
7503 case OMPD_parallel_for_simd:
7504 case OMPD_target:
7505 case OMPD_target_simd:
7506 case OMPD_target_parallel:
7507 case OMPD_target_parallel_for:
7508 case OMPD_target_parallel_for_simd:
7509 case OMPD_target_teams_distribute:
7510 case OMPD_target_teams_distribute_simd:
7511 case OMPD_target_teams_distribute_parallel_for:
7512 case OMPD_target_teams_distribute_parallel_for_simd:
7513 case OMPD_teams_distribute_parallel_for:
7514 case OMPD_teams_distribute_parallel_for_simd:
7515 case OMPD_distribute_parallel_for:
7516 case OMPD_distribute_parallel_for_simd:
7517 case OMPD_task:
7518 case OMPD_taskloop:
7519 case OMPD_taskloop_simd:
7520 case OMPD_target_data:
7521 case OMPD_target_enter_data:
7522 case OMPD_target_exit_data:
7523 case OMPD_target_update:
7524 case OMPD_teams:
7525 case OMPD_teams_distribute:
7526 case OMPD_teams_distribute_simd:
7527 // Do not capture num_teams-clause expressions.
7528 break;
7529 case OMPD_threadprivate:
7530 case OMPD_taskyield:
7531 case OMPD_barrier:
7532 case OMPD_taskwait:
7533 case OMPD_cancellation_point:
7534 case OMPD_flush:
7535 case OMPD_declare_reduction:
7536 case OMPD_declare_simd:
7537 case OMPD_declare_target:
7538 case OMPD_end_declare_target:
7539 case OMPD_simd:
7540 case OMPD_for:
7541 case OMPD_for_simd:
7542 case OMPD_sections:
7543 case OMPD_section:
7544 case OMPD_single:
7545 case OMPD_master:
7546 case OMPD_critical:
7547 case OMPD_taskgroup:
7548 case OMPD_distribute:
7549 case OMPD_ordered:
7550 case OMPD_atomic:
7551 case OMPD_distribute_simd:
7552 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7553 case OMPD_unknown:
7554 llvm_unreachable("Unknown OpenMP directive");
7555 }
7556 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007557 case OMPC_thread_limit:
7558 switch (DKind) {
7559 case OMPD_target_teams:
7560 CaptureRegion = OMPD_target;
7561 break;
7562 case OMPD_cancel:
7563 case OMPD_parallel:
7564 case OMPD_parallel_sections:
7565 case OMPD_parallel_for:
7566 case OMPD_parallel_for_simd:
7567 case OMPD_target:
7568 case OMPD_target_simd:
7569 case OMPD_target_parallel:
7570 case OMPD_target_parallel_for:
7571 case OMPD_target_parallel_for_simd:
7572 case OMPD_target_teams_distribute:
7573 case OMPD_target_teams_distribute_simd:
7574 case OMPD_target_teams_distribute_parallel_for:
7575 case OMPD_target_teams_distribute_parallel_for_simd:
7576 case OMPD_teams_distribute_parallel_for:
7577 case OMPD_teams_distribute_parallel_for_simd:
7578 case OMPD_distribute_parallel_for:
7579 case OMPD_distribute_parallel_for_simd:
7580 case OMPD_task:
7581 case OMPD_taskloop:
7582 case OMPD_taskloop_simd:
7583 case OMPD_target_data:
7584 case OMPD_target_enter_data:
7585 case OMPD_target_exit_data:
7586 case OMPD_target_update:
7587 case OMPD_teams:
7588 case OMPD_teams_distribute:
7589 case OMPD_teams_distribute_simd:
7590 // Do not capture thread_limit-clause expressions.
7591 break;
7592 case OMPD_threadprivate:
7593 case OMPD_taskyield:
7594 case OMPD_barrier:
7595 case OMPD_taskwait:
7596 case OMPD_cancellation_point:
7597 case OMPD_flush:
7598 case OMPD_declare_reduction:
7599 case OMPD_declare_simd:
7600 case OMPD_declare_target:
7601 case OMPD_end_declare_target:
7602 case OMPD_simd:
7603 case OMPD_for:
7604 case OMPD_for_simd:
7605 case OMPD_sections:
7606 case OMPD_section:
7607 case OMPD_single:
7608 case OMPD_master:
7609 case OMPD_critical:
7610 case OMPD_taskgroup:
7611 case OMPD_distribute:
7612 case OMPD_ordered:
7613 case OMPD_atomic:
7614 case OMPD_distribute_simd:
7615 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7616 case OMPD_unknown:
7617 llvm_unreachable("Unknown OpenMP directive");
7618 }
7619 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007620 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007621 switch (DKind) {
7622 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007623 case OMPD_target_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007624 CaptureRegion = OMPD_target;
7625 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007626 case OMPD_teams_distribute_parallel_for:
7627 CaptureRegion = OMPD_teams;
7628 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007629 case OMPD_parallel_for:
7630 case OMPD_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007631 case OMPD_target_teams_distribute_parallel_for:
7632 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007633 case OMPD_teams_distribute_parallel_for_simd:
7634 case OMPD_distribute_parallel_for:
7635 case OMPD_distribute_parallel_for_simd:
7636 // Do not capture thread_limit-clause expressions.
7637 break;
7638 case OMPD_task:
7639 case OMPD_taskloop:
7640 case OMPD_taskloop_simd:
7641 case OMPD_target_data:
7642 case OMPD_target_enter_data:
7643 case OMPD_target_exit_data:
7644 case OMPD_target_update:
7645 case OMPD_teams:
7646 case OMPD_teams_distribute:
7647 case OMPD_teams_distribute_simd:
7648 case OMPD_target_teams_distribute:
7649 case OMPD_target_teams_distribute_simd:
7650 case OMPD_target:
7651 case OMPD_target_simd:
7652 case OMPD_target_parallel:
7653 case OMPD_cancel:
7654 case OMPD_parallel:
7655 case OMPD_parallel_sections:
7656 case OMPD_threadprivate:
7657 case OMPD_taskyield:
7658 case OMPD_barrier:
7659 case OMPD_taskwait:
7660 case OMPD_cancellation_point:
7661 case OMPD_flush:
7662 case OMPD_declare_reduction:
7663 case OMPD_declare_simd:
7664 case OMPD_declare_target:
7665 case OMPD_end_declare_target:
7666 case OMPD_simd:
7667 case OMPD_for:
7668 case OMPD_for_simd:
7669 case OMPD_sections:
7670 case OMPD_section:
7671 case OMPD_single:
7672 case OMPD_master:
7673 case OMPD_critical:
7674 case OMPD_taskgroup:
7675 case OMPD_distribute:
7676 case OMPD_ordered:
7677 case OMPD_atomic:
7678 case OMPD_distribute_simd:
7679 case OMPD_target_teams:
7680 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7681 case OMPD_unknown:
7682 llvm_unreachable("Unknown OpenMP directive");
7683 }
7684 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007685 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007686 switch (DKind) {
7687 case OMPD_teams_distribute_parallel_for:
7688 CaptureRegion = OMPD_teams;
7689 break;
7690 case OMPD_target_teams_distribute_parallel_for:
7691 case OMPD_target_teams_distribute_parallel_for_simd:
7692 case OMPD_teams_distribute_parallel_for_simd:
7693 case OMPD_distribute_parallel_for:
7694 case OMPD_distribute_parallel_for_simd:
7695 case OMPD_teams_distribute:
7696 case OMPD_teams_distribute_simd:
7697 case OMPD_target_teams_distribute:
7698 case OMPD_target_teams_distribute_simd:
7699 case OMPD_distribute_simd:
7700 // Do not capture thread_limit-clause expressions.
7701 break;
7702 case OMPD_parallel_for:
7703 case OMPD_parallel_for_simd:
7704 case OMPD_target_parallel_for_simd:
7705 case OMPD_target_parallel_for:
7706 case OMPD_task:
7707 case OMPD_taskloop:
7708 case OMPD_taskloop_simd:
7709 case OMPD_target_data:
7710 case OMPD_target_enter_data:
7711 case OMPD_target_exit_data:
7712 case OMPD_target_update:
7713 case OMPD_teams:
7714 case OMPD_target:
7715 case OMPD_target_simd:
7716 case OMPD_target_parallel:
7717 case OMPD_cancel:
7718 case OMPD_parallel:
7719 case OMPD_parallel_sections:
7720 case OMPD_threadprivate:
7721 case OMPD_taskyield:
7722 case OMPD_barrier:
7723 case OMPD_taskwait:
7724 case OMPD_cancellation_point:
7725 case OMPD_flush:
7726 case OMPD_declare_reduction:
7727 case OMPD_declare_simd:
7728 case OMPD_declare_target:
7729 case OMPD_end_declare_target:
7730 case OMPD_simd:
7731 case OMPD_for:
7732 case OMPD_for_simd:
7733 case OMPD_sections:
7734 case OMPD_section:
7735 case OMPD_single:
7736 case OMPD_master:
7737 case OMPD_critical:
7738 case OMPD_taskgroup:
7739 case OMPD_distribute:
7740 case OMPD_ordered:
7741 case OMPD_atomic:
7742 case OMPD_target_teams:
7743 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7744 case OMPD_unknown:
7745 llvm_unreachable("Unknown OpenMP directive");
7746 }
7747 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007748 case OMPC_firstprivate:
7749 case OMPC_lastprivate:
7750 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007751 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007752 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007753 case OMPC_linear:
7754 case OMPC_default:
7755 case OMPC_proc_bind:
7756 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007757 case OMPC_safelen:
7758 case OMPC_simdlen:
7759 case OMPC_collapse:
7760 case OMPC_private:
7761 case OMPC_shared:
7762 case OMPC_aligned:
7763 case OMPC_copyin:
7764 case OMPC_copyprivate:
7765 case OMPC_ordered:
7766 case OMPC_nowait:
7767 case OMPC_untied:
7768 case OMPC_mergeable:
7769 case OMPC_threadprivate:
7770 case OMPC_flush:
7771 case OMPC_read:
7772 case OMPC_write:
7773 case OMPC_update:
7774 case OMPC_capture:
7775 case OMPC_seq_cst:
7776 case OMPC_depend:
7777 case OMPC_device:
7778 case OMPC_threads:
7779 case OMPC_simd:
7780 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007781 case OMPC_priority:
7782 case OMPC_grainsize:
7783 case OMPC_nogroup:
7784 case OMPC_num_tasks:
7785 case OMPC_hint:
7786 case OMPC_defaultmap:
7787 case OMPC_unknown:
7788 case OMPC_uniform:
7789 case OMPC_to:
7790 case OMPC_from:
7791 case OMPC_use_device_ptr:
7792 case OMPC_is_device_ptr:
7793 llvm_unreachable("Unexpected OpenMP clause.");
7794 }
7795 return CaptureRegion;
7796}
7797
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007798OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7799 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007800 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007801 SourceLocation NameModifierLoc,
7802 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007803 SourceLocation EndLoc) {
7804 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007805 Stmt *HelperValStmt = nullptr;
7806 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007807 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7808 !Condition->isInstantiationDependent() &&
7809 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007810 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007811 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007812 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007813
Richard Smith03a4aa32016-06-23 19:02:52 +00007814 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007815
7816 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7817 CaptureRegion =
7818 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7819 if (CaptureRegion != OMPD_unknown) {
7820 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7821 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7822 HelperValStmt = buildPreInits(Context, Captures);
7823 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007824 }
7825
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007826 return new (Context)
7827 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7828 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007829}
7830
Alexey Bataev3778b602014-07-17 07:32:53 +00007831OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7832 SourceLocation StartLoc,
7833 SourceLocation LParenLoc,
7834 SourceLocation EndLoc) {
7835 Expr *ValExpr = Condition;
7836 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7837 !Condition->isInstantiationDependent() &&
7838 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007839 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007840 if (Val.isInvalid())
7841 return nullptr;
7842
Richard Smith03a4aa32016-06-23 19:02:52 +00007843 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007844 }
7845
7846 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7847}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007848ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7849 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007850 if (!Op)
7851 return ExprError();
7852
7853 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7854 public:
7855 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007856 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007857 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7858 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007859 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7860 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007861 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7862 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007863 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7864 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007865 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7866 QualType T,
7867 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007868 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7869 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007870 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7871 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007872 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007873 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007874 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007875 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7876 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007877 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7878 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007879 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7880 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007881 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007882 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007883 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007884 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7885 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007886 llvm_unreachable("conversion functions are permitted");
7887 }
7888 } ConvertDiagnoser;
7889 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7890}
7891
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007892static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007893 OpenMPClauseKind CKind,
7894 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007895 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7896 !ValExpr->isInstantiationDependent()) {
7897 SourceLocation Loc = ValExpr->getExprLoc();
7898 ExprResult Value =
7899 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7900 if (Value.isInvalid())
7901 return false;
7902
7903 ValExpr = Value.get();
7904 // The expression must evaluate to a non-negative integer value.
7905 llvm::APSInt Result;
7906 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007907 Result.isSigned() &&
7908 !((!StrictlyPositive && Result.isNonNegative()) ||
7909 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007910 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007911 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7912 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007913 return false;
7914 }
7915 }
7916 return true;
7917}
7918
Alexey Bataev568a8332014-03-06 06:15:19 +00007919OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7920 SourceLocation StartLoc,
7921 SourceLocation LParenLoc,
7922 SourceLocation EndLoc) {
7923 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007924 Stmt *HelperValStmt = nullptr;
7925 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007926
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007927 // OpenMP [2.5, Restrictions]
7928 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007929 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7930 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007931 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007932
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007933 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7934 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7935 if (CaptureRegion != OMPD_unknown) {
7936 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7937 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7938 HelperValStmt = buildPreInits(Context, Captures);
7939 }
7940
7941 return new (Context) OMPNumThreadsClause(
7942 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007943}
7944
Alexey Bataev62c87d22014-03-21 04:51:18 +00007945ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007946 OpenMPClauseKind CKind,
7947 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007948 if (!E)
7949 return ExprError();
7950 if (E->isValueDependent() || E->isTypeDependent() ||
7951 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007952 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007953 llvm::APSInt Result;
7954 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7955 if (ICE.isInvalid())
7956 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007957 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7958 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007959 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007960 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7961 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007962 return ExprError();
7963 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007964 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7965 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7966 << E->getSourceRange();
7967 return ExprError();
7968 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007969 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7970 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007971 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007972 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007973 return ICE;
7974}
7975
7976OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7977 SourceLocation LParenLoc,
7978 SourceLocation EndLoc) {
7979 // OpenMP [2.8.1, simd construct, Description]
7980 // The parameter of the safelen clause must be a constant
7981 // positive integer expression.
7982 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7983 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007984 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007985 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007986 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007987}
7988
Alexey Bataev66b15b52015-08-21 11:14:16 +00007989OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7990 SourceLocation LParenLoc,
7991 SourceLocation EndLoc) {
7992 // OpenMP [2.8.1, simd construct, Description]
7993 // The parameter of the simdlen clause must be a constant
7994 // positive integer expression.
7995 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7996 if (Simdlen.isInvalid())
7997 return nullptr;
7998 return new (Context)
7999 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8000}
8001
Alexander Musman64d33f12014-06-04 07:53:32 +00008002OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8003 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008004 SourceLocation LParenLoc,
8005 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008006 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008007 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008008 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008009 // The parameter of the collapse clause must be a constant
8010 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008011 ExprResult NumForLoopsResult =
8012 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8013 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008014 return nullptr;
8015 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008016 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008017}
8018
Alexey Bataev10e775f2015-07-30 11:36:16 +00008019OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8020 SourceLocation EndLoc,
8021 SourceLocation LParenLoc,
8022 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008023 // OpenMP [2.7.1, loop construct, Description]
8024 // OpenMP [2.8.1, simd construct, Description]
8025 // OpenMP [2.9.6, distribute construct, Description]
8026 // The parameter of the ordered clause must be a constant
8027 // positive integer expression if any.
8028 if (NumForLoops && LParenLoc.isValid()) {
8029 ExprResult NumForLoopsResult =
8030 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8031 if (NumForLoopsResult.isInvalid())
8032 return nullptr;
8033 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008034 } else
8035 NumForLoops = nullptr;
8036 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008037 return new (Context)
8038 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8039}
8040
Alexey Bataeved09d242014-05-28 05:53:51 +00008041OMPClause *Sema::ActOnOpenMPSimpleClause(
8042 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8043 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008044 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008045 switch (Kind) {
8046 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008047 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008048 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8049 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008050 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008051 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008052 Res = ActOnOpenMPProcBindClause(
8053 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8054 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008055 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008056 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008057 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008058 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008059 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008060 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008061 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008062 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008063 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008064 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008065 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008066 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008067 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008068 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008069 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008070 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008071 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008072 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008073 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008074 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008075 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008076 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008077 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008078 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008079 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008080 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008081 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008082 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008083 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008084 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008085 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008086 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008087 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008088 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008089 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008090 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008091 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008092 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008093 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008094 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008095 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008096 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008097 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008098 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008099 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008100 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008101 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008102 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008103 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008104 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008105 llvm_unreachable("Clause is not allowed.");
8106 }
8107 return Res;
8108}
8109
Alexey Bataev6402bca2015-12-28 07:25:51 +00008110static std::string
8111getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8112 ArrayRef<unsigned> Exclude = llvm::None) {
8113 std::string Values;
8114 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8115 unsigned Skipped = Exclude.size();
8116 auto S = Exclude.begin(), E = Exclude.end();
8117 for (unsigned i = First; i < Last; ++i) {
8118 if (std::find(S, E, i) != E) {
8119 --Skipped;
8120 continue;
8121 }
8122 Values += "'";
8123 Values += getOpenMPSimpleClauseTypeName(K, i);
8124 Values += "'";
8125 if (i == Bound - Skipped)
8126 Values += " or ";
8127 else if (i != Bound + 1 - Skipped)
8128 Values += ", ";
8129 }
8130 return Values;
8131}
8132
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008133OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8134 SourceLocation KindKwLoc,
8135 SourceLocation StartLoc,
8136 SourceLocation LParenLoc,
8137 SourceLocation EndLoc) {
8138 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008139 static_assert(OMPC_DEFAULT_unknown > 0,
8140 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008141 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008142 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8143 /*Last=*/OMPC_DEFAULT_unknown)
8144 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008145 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008146 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008147 switch (Kind) {
8148 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008149 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008150 break;
8151 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008152 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008153 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008154 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008155 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008156 break;
8157 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008158 return new (Context)
8159 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008160}
8161
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008162OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8163 SourceLocation KindKwLoc,
8164 SourceLocation StartLoc,
8165 SourceLocation LParenLoc,
8166 SourceLocation EndLoc) {
8167 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008168 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008169 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8170 /*Last=*/OMPC_PROC_BIND_unknown)
8171 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008172 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008173 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008174 return new (Context)
8175 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008176}
8177
Alexey Bataev56dafe82014-06-20 07:16:17 +00008178OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008179 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008180 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008181 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008182 SourceLocation EndLoc) {
8183 OMPClause *Res = nullptr;
8184 switch (Kind) {
8185 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008186 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8187 assert(Argument.size() == NumberOfElements &&
8188 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008189 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008190 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8191 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8192 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8193 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8194 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008195 break;
8196 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008197 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8198 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8199 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8200 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008201 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008202 case OMPC_dist_schedule:
8203 Res = ActOnOpenMPDistScheduleClause(
8204 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8205 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8206 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008207 case OMPC_defaultmap:
8208 enum { Modifier, DefaultmapKind };
8209 Res = ActOnOpenMPDefaultmapClause(
8210 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8211 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008212 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8213 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008214 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008215 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008216 case OMPC_num_threads:
8217 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008218 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008219 case OMPC_collapse:
8220 case OMPC_default:
8221 case OMPC_proc_bind:
8222 case OMPC_private:
8223 case OMPC_firstprivate:
8224 case OMPC_lastprivate:
8225 case OMPC_shared:
8226 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008227 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008228 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008229 case OMPC_linear:
8230 case OMPC_aligned:
8231 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008232 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008233 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008234 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008235 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008236 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008237 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008238 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008239 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008240 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008241 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008242 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008243 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008244 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008245 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008246 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008247 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008248 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008249 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008250 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008251 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008252 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008253 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008254 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008255 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008256 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008257 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008258 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008259 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008260 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008261 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008262 llvm_unreachable("Clause is not allowed.");
8263 }
8264 return Res;
8265}
8266
Alexey Bataev6402bca2015-12-28 07:25:51 +00008267static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8268 OpenMPScheduleClauseModifier M2,
8269 SourceLocation M1Loc, SourceLocation M2Loc) {
8270 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8271 SmallVector<unsigned, 2> Excluded;
8272 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8273 Excluded.push_back(M2);
8274 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8275 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8276 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8277 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8278 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8279 << getListOfPossibleValues(OMPC_schedule,
8280 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8281 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8282 Excluded)
8283 << getOpenMPClauseName(OMPC_schedule);
8284 return true;
8285 }
8286 return false;
8287}
8288
Alexey Bataev56dafe82014-06-20 07:16:17 +00008289OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008290 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008291 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008292 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8293 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8294 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8295 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8296 return nullptr;
8297 // OpenMP, 2.7.1, Loop Construct, Restrictions
8298 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8299 // but not both.
8300 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8301 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8302 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8303 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8304 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8305 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8306 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8307 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8308 return nullptr;
8309 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008310 if (Kind == OMPC_SCHEDULE_unknown) {
8311 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008312 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8313 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8314 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8315 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8316 Exclude);
8317 } else {
8318 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8319 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008320 }
8321 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8322 << Values << getOpenMPClauseName(OMPC_schedule);
8323 return nullptr;
8324 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008325 // OpenMP, 2.7.1, Loop Construct, Restrictions
8326 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8327 // schedule(guided).
8328 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8329 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8330 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8331 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8332 diag::err_omp_schedule_nonmonotonic_static);
8333 return nullptr;
8334 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008335 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008336 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008337 if (ChunkSize) {
8338 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8339 !ChunkSize->isInstantiationDependent() &&
8340 !ChunkSize->containsUnexpandedParameterPack()) {
8341 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8342 ExprResult Val =
8343 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8344 if (Val.isInvalid())
8345 return nullptr;
8346
8347 ValExpr = Val.get();
8348
8349 // OpenMP [2.7.1, Restrictions]
8350 // chunk_size must be a loop invariant integer expression with a positive
8351 // value.
8352 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008353 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8354 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8355 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008356 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008357 return nullptr;
8358 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008359 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
8360 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008361 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8362 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8363 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008364 }
8365 }
8366 }
8367
Alexey Bataev6402bca2015-12-28 07:25:51 +00008368 return new (Context)
8369 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008370 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008371}
8372
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008373OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8374 SourceLocation StartLoc,
8375 SourceLocation EndLoc) {
8376 OMPClause *Res = nullptr;
8377 switch (Kind) {
8378 case OMPC_ordered:
8379 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8380 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008381 case OMPC_nowait:
8382 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8383 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008384 case OMPC_untied:
8385 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8386 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008387 case OMPC_mergeable:
8388 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8389 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008390 case OMPC_read:
8391 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8392 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008393 case OMPC_write:
8394 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8395 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008396 case OMPC_update:
8397 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8398 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008399 case OMPC_capture:
8400 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8401 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008402 case OMPC_seq_cst:
8403 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8404 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008405 case OMPC_threads:
8406 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8407 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008408 case OMPC_simd:
8409 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8410 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008411 case OMPC_nogroup:
8412 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8413 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008414 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008415 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008416 case OMPC_num_threads:
8417 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008418 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008419 case OMPC_collapse:
8420 case OMPC_schedule:
8421 case OMPC_private:
8422 case OMPC_firstprivate:
8423 case OMPC_lastprivate:
8424 case OMPC_shared:
8425 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008426 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008427 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008428 case OMPC_linear:
8429 case OMPC_aligned:
8430 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008431 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008432 case OMPC_default:
8433 case OMPC_proc_bind:
8434 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008435 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008436 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008437 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008438 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008439 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008440 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008441 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008442 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008443 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008444 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008445 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008446 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008447 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008448 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008449 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008450 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008451 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008452 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008453 llvm_unreachable("Clause is not allowed.");
8454 }
8455 return Res;
8456}
8457
Alexey Bataev236070f2014-06-20 11:19:47 +00008458OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8459 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008460 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008461 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8462}
8463
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008464OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8465 SourceLocation EndLoc) {
8466 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8467}
8468
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008469OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8470 SourceLocation EndLoc) {
8471 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8472}
8473
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008474OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8475 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008476 return new (Context) OMPReadClause(StartLoc, EndLoc);
8477}
8478
Alexey Bataevdea47612014-07-23 07:46:59 +00008479OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8480 SourceLocation EndLoc) {
8481 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8482}
8483
Alexey Bataev67a4f222014-07-23 10:25:33 +00008484OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8485 SourceLocation EndLoc) {
8486 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8487}
8488
Alexey Bataev459dec02014-07-24 06:46:57 +00008489OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8490 SourceLocation EndLoc) {
8491 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8492}
8493
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008494OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8495 SourceLocation EndLoc) {
8496 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8497}
8498
Alexey Bataev346265e2015-09-25 10:37:12 +00008499OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8500 SourceLocation EndLoc) {
8501 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8502}
8503
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008504OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8505 SourceLocation EndLoc) {
8506 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8507}
8508
Alexey Bataevb825de12015-12-07 10:51:44 +00008509OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8510 SourceLocation EndLoc) {
8511 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8512}
8513
Alexey Bataevc5e02582014-06-16 07:08:35 +00008514OMPClause *Sema::ActOnOpenMPVarListClause(
8515 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8516 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8517 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008518 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008519 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8520 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8521 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008522 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008523 switch (Kind) {
8524 case OMPC_private:
8525 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8526 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008527 case OMPC_firstprivate:
8528 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8529 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008530 case OMPC_lastprivate:
8531 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8532 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008533 case OMPC_shared:
8534 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8535 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008536 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008537 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8538 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008539 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008540 case OMPC_task_reduction:
8541 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8542 EndLoc, ReductionIdScopeSpec,
8543 ReductionId);
8544 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008545 case OMPC_in_reduction:
8546 Res =
8547 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8548 EndLoc, ReductionIdScopeSpec, ReductionId);
8549 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008550 case OMPC_linear:
8551 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008552 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008553 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008554 case OMPC_aligned:
8555 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8556 ColonLoc, EndLoc);
8557 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008558 case OMPC_copyin:
8559 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8560 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008561 case OMPC_copyprivate:
8562 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8563 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008564 case OMPC_flush:
8565 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8566 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008567 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008568 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008569 StartLoc, LParenLoc, EndLoc);
8570 break;
8571 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008572 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8573 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8574 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008575 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008576 case OMPC_to:
8577 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8578 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008579 case OMPC_from:
8580 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8581 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008582 case OMPC_use_device_ptr:
8583 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8584 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008585 case OMPC_is_device_ptr:
8586 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8587 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008588 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008589 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008590 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008591 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008592 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008593 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008594 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008595 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008596 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008597 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008598 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008599 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008600 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008601 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008602 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008603 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008604 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008605 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008606 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008607 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008608 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008609 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008610 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008611 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008612 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008613 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008614 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008615 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008616 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008617 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008618 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008619 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008620 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008621 llvm_unreachable("Clause is not allowed.");
8622 }
8623 return Res;
8624}
8625
Alexey Bataev90c228f2016-02-08 09:29:13 +00008626ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008627 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008628 ExprResult Res = BuildDeclRefExpr(
8629 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8630 if (!Res.isUsable())
8631 return ExprError();
8632 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8633 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8634 if (!Res.isUsable())
8635 return ExprError();
8636 }
8637 if (VK != VK_LValue && Res.get()->isGLValue()) {
8638 Res = DefaultLvalueConversion(Res.get());
8639 if (!Res.isUsable())
8640 return ExprError();
8641 }
8642 return Res;
8643}
8644
Alexey Bataev60da77e2016-02-29 05:54:20 +00008645static std::pair<ValueDecl *, bool>
8646getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8647 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008648 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8649 RefExpr->containsUnexpandedParameterPack())
8650 return std::make_pair(nullptr, true);
8651
Alexey Bataevd985eda2016-02-10 11:29:16 +00008652 // OpenMP [3.1, C/C++]
8653 // A list item is a variable name.
8654 // OpenMP [2.9.3.3, Restrictions, p.1]
8655 // A variable that is part of another variable (as an array or
8656 // structure element) cannot appear in a private clause.
8657 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008658 enum {
8659 NoArrayExpr = -1,
8660 ArraySubscript = 0,
8661 OMPArraySection = 1
8662 } IsArrayExpr = NoArrayExpr;
8663 if (AllowArraySection) {
8664 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8665 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8666 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8667 Base = TempASE->getBase()->IgnoreParenImpCasts();
8668 RefExpr = Base;
8669 IsArrayExpr = ArraySubscript;
8670 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8671 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8672 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8673 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8674 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8675 Base = TempASE->getBase()->IgnoreParenImpCasts();
8676 RefExpr = Base;
8677 IsArrayExpr = OMPArraySection;
8678 }
8679 }
8680 ELoc = RefExpr->getExprLoc();
8681 ERange = RefExpr->getSourceRange();
8682 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008683 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8684 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8685 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8686 (S.getCurrentThisType().isNull() || !ME ||
8687 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8688 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008689 if (IsArrayExpr != NoArrayExpr)
8690 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8691 << ERange;
8692 else {
8693 S.Diag(ELoc,
8694 AllowArraySection
8695 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8696 : diag::err_omp_expected_var_name_member_expr)
8697 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8698 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008699 return std::make_pair(nullptr, false);
8700 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008701 return std::make_pair(
8702 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008703}
8704
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008705OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8706 SourceLocation StartLoc,
8707 SourceLocation LParenLoc,
8708 SourceLocation EndLoc) {
8709 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008710 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008711 for (auto &RefExpr : VarList) {
8712 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008713 SourceLocation ELoc;
8714 SourceRange ERange;
8715 Expr *SimpleRefExpr = RefExpr;
8716 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008717 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008718 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008719 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008720 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008721 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008722 ValueDecl *D = Res.first;
8723 if (!D)
8724 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008725
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008726 QualType Type = D->getType();
8727 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008728
8729 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8730 // A variable that appears in a private clause must not have an incomplete
8731 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008732 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008733 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008734 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008735
Alexey Bataev758e55e2013-09-06 18:03:48 +00008736 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8737 // in a Construct]
8738 // Variables with the predetermined data-sharing attributes may not be
8739 // listed in data-sharing attributes clauses, except for the cases
8740 // listed below. For these exceptions only, listing a predetermined
8741 // variable in a data-sharing attribute clause is allowed and overrides
8742 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008743 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008744 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008745 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8746 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008747 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008748 continue;
8749 }
8750
Kelvin Libf594a52016-12-17 05:48:59 +00008751 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008752 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008753 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008754 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008755 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8756 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008757 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008758 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008759 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008760 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008761 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008762 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008763 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008764 continue;
8765 }
8766
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008767 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8768 // A list item cannot appear in both a map clause and a data-sharing
8769 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008770 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008771 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008772 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008773 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008774 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008775 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008776 CurrDir == OMPD_target_parallel_for_simd ||
8777 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008778 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008779 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008780 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008781 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8782 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8783 ConflictKind = WhereFoundClauseKind;
8784 return true;
8785 })) {
8786 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008787 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008788 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008789 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008790 ReportOriginalDSA(*this, DSAStack, D, DVar);
8791 continue;
8792 }
8793 }
8794
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008795 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8796 // A variable of class type (or array thereof) that appears in a private
8797 // clause requires an accessible, unambiguous default constructor for the
8798 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008799 // Generate helper private variable and initialize it with the default
8800 // value. The address of the original variable is replaced by the address of
8801 // the new private variable in CodeGen. This new variable is not added to
8802 // IdResolver, so the code in the OpenMP region uses original variable for
8803 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008804 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008805 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8806 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008807 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008808 if (VDPrivate->isInvalidDecl())
8809 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008810 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008811 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008812
Alexey Bataev90c228f2016-02-08 09:29:13 +00008813 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008814 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008815 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008816 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008817 Vars.push_back((VD || CurContext->isDependentContext())
8818 ? RefExpr->IgnoreParens()
8819 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008820 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008821 }
8822
Alexey Bataeved09d242014-05-28 05:53:51 +00008823 if (Vars.empty())
8824 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008825
Alexey Bataev03b340a2014-10-21 03:16:40 +00008826 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8827 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008828}
8829
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008830namespace {
8831class DiagsUninitializedSeveretyRAII {
8832private:
8833 DiagnosticsEngine &Diags;
8834 SourceLocation SavedLoc;
8835 bool IsIgnored;
8836
8837public:
8838 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8839 bool IsIgnored)
8840 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8841 if (!IsIgnored) {
8842 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8843 /*Map*/ diag::Severity::Ignored, Loc);
8844 }
8845 }
8846 ~DiagsUninitializedSeveretyRAII() {
8847 if (!IsIgnored)
8848 Diags.popMappings(SavedLoc);
8849 }
8850};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008851}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008852
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008853OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8854 SourceLocation StartLoc,
8855 SourceLocation LParenLoc,
8856 SourceLocation EndLoc) {
8857 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008858 SmallVector<Expr *, 8> PrivateCopies;
8859 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008860 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008861 bool IsImplicitClause =
8862 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8863 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8864
Alexey Bataeved09d242014-05-28 05:53:51 +00008865 for (auto &RefExpr : VarList) {
8866 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008867 SourceLocation ELoc;
8868 SourceRange ERange;
8869 Expr *SimpleRefExpr = RefExpr;
8870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008871 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008872 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008873 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008874 PrivateCopies.push_back(nullptr);
8875 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008876 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008877 ValueDecl *D = Res.first;
8878 if (!D)
8879 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008880
Alexey Bataev60da77e2016-02-29 05:54:20 +00008881 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008882 QualType Type = D->getType();
8883 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008884
8885 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8886 // A variable that appears in a private clause must not have an incomplete
8887 // type or a reference type.
8888 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008889 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008890 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008891 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008892
8893 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8894 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008895 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008896 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008897 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008898
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008899 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008900 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008901 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008902 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008903 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008904 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008905 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008906 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8907 // A list item that specifies a given variable may not appear in more
8908 // than one clause on the same directive, except that a variable may be
8909 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008910 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8911 // A list item may appear in a firstprivate or lastprivate clause but not
8912 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008913 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008914 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8915 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008916 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008917 << getOpenMPClauseName(DVar.CKind)
8918 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008919 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008920 continue;
8921 }
8922
8923 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8924 // in a Construct]
8925 // Variables with the predetermined data-sharing attributes may not be
8926 // listed in data-sharing attributes clauses, except for the cases
8927 // listed below. For these exceptions only, listing a predetermined
8928 // variable in a data-sharing attribute clause is allowed and overrides
8929 // the variable's predetermined data-sharing attributes.
8930 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8931 // in a Construct, C/C++, p.2]
8932 // Variables with const-qualified type having no mutable member may be
8933 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008934 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008935 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8936 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008937 << getOpenMPClauseName(DVar.CKind)
8938 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008939 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008940 continue;
8941 }
8942
8943 // OpenMP [2.9.3.4, Restrictions, p.2]
8944 // A list item that is private within a parallel region must not appear
8945 // in a firstprivate clause on a worksharing construct if any of the
8946 // worksharing regions arising from the worksharing construct ever bind
8947 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008948 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8949 // A list item that is private within a teams region must not appear in a
8950 // firstprivate clause on a distribute construct if any of the distribute
8951 // regions arising from the distribute construct ever bind to any of the
8952 // teams regions arising from the teams construct.
8953 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8954 // A list item that appears in a reduction clause of a teams construct
8955 // must not appear in a firstprivate clause on a distribute construct if
8956 // any of the distribute regions arising from the distribute construct
8957 // ever bind to any of the teams regions arising from the teams construct.
8958 if ((isOpenMPWorksharingDirective(CurrDir) ||
8959 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008960 !isOpenMPParallelDirective(CurrDir) &&
8961 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008962 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008963 if (DVar.CKind != OMPC_shared &&
8964 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008965 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008966 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008967 Diag(ELoc, diag::err_omp_required_access)
8968 << getOpenMPClauseName(OMPC_firstprivate)
8969 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008970 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008971 continue;
8972 }
8973 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008974 // OpenMP [2.9.3.4, Restrictions, p.3]
8975 // A list item that appears in a reduction clause of a parallel construct
8976 // must not appear in a firstprivate clause on a worksharing or task
8977 // construct if any of the worksharing or task regions arising from the
8978 // worksharing or task construct ever bind to any of the parallel regions
8979 // arising from the parallel construct.
8980 // OpenMP [2.9.3.4, Restrictions, p.4]
8981 // A list item that appears in a reduction clause in worksharing
8982 // construct must not appear in a firstprivate clause in a task construct
8983 // encountered during execution of any of the worksharing regions arising
8984 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008985 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008986 DVar = DSAStack->hasInnermostDSA(
8987 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8988 [](OpenMPDirectiveKind K) -> bool {
8989 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008990 isOpenMPWorksharingDirective(K) ||
8991 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008992 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008993 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008994 if (DVar.CKind == OMPC_reduction &&
8995 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008996 isOpenMPWorksharingDirective(DVar.DKind) ||
8997 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008998 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8999 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009000 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009001 continue;
9002 }
9003 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009004
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009005 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9006 // A list item cannot appear in both a map clause and a data-sharing
9007 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009008 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00009009 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009010 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009011 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009012 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009013 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009014 CurrDir == OMPD_target_parallel_for_simd ||
9015 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009016 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009017 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009018 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009019 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9020 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9021 ConflictKind = WhereFoundClauseKind;
9022 return true;
9023 })) {
9024 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009025 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009026 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009027 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9028 ReportOriginalDSA(*this, DSAStack, D, DVar);
9029 continue;
9030 }
9031 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009032 }
9033
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009034 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009035 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009036 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009037 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9038 << getOpenMPClauseName(OMPC_firstprivate) << Type
9039 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9040 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009041 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009042 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009043 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009044 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009045 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009046 continue;
9047 }
9048
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009049 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009050 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9051 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009052 // Generate helper private variable and initialize it with the value of the
9053 // original variable. The address of the original variable is replaced by
9054 // the address of the new private variable in the CodeGen. This new variable
9055 // is not added to IdResolver, so the code in the OpenMP region uses
9056 // original variable for proper diagnostics and variable capturing.
9057 Expr *VDInitRefExpr = nullptr;
9058 // For arrays generate initializer for single element and replace it by the
9059 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009060 if (Type->isArrayType()) {
9061 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009062 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009063 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009064 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009065 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009066 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009067 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009068 InitializedEntity Entity =
9069 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009070 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9071
9072 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9073 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9074 if (Result.isInvalid())
9075 VDPrivate->setInvalidDecl();
9076 else
9077 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009078 // Remove temp variable declaration.
9079 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009080 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009081 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9082 ".firstprivate.temp");
9083 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9084 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009085 AddInitializerToDecl(VDPrivate,
9086 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009087 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009088 }
9089 if (VDPrivate->isInvalidDecl()) {
9090 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009091 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009092 diag::note_omp_task_predetermined_firstprivate_here);
9093 }
9094 continue;
9095 }
9096 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009097 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009098 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9099 RefExpr->getExprLoc());
9100 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009101 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009102 if (TopDVar.CKind == OMPC_lastprivate)
9103 Ref = TopDVar.PrivateCopy;
9104 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009105 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009106 if (!IsOpenMPCapturedDecl(D))
9107 ExprCaptures.push_back(Ref->getDecl());
9108 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009109 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009110 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009111 Vars.push_back((VD || CurContext->isDependentContext())
9112 ? RefExpr->IgnoreParens()
9113 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009114 PrivateCopies.push_back(VDPrivateRefExpr);
9115 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009116 }
9117
Alexey Bataeved09d242014-05-28 05:53:51 +00009118 if (Vars.empty())
9119 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009120
9121 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009122 Vars, PrivateCopies, Inits,
9123 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009124}
9125
Alexander Musman1bb328c2014-06-04 13:06:39 +00009126OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9127 SourceLocation StartLoc,
9128 SourceLocation LParenLoc,
9129 SourceLocation EndLoc) {
9130 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009131 SmallVector<Expr *, 8> SrcExprs;
9132 SmallVector<Expr *, 8> DstExprs;
9133 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009134 SmallVector<Decl *, 4> ExprCaptures;
9135 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009136 for (auto &RefExpr : VarList) {
9137 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009138 SourceLocation ELoc;
9139 SourceRange ERange;
9140 Expr *SimpleRefExpr = RefExpr;
9141 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009142 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009143 // It will be analyzed later.
9144 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009145 SrcExprs.push_back(nullptr);
9146 DstExprs.push_back(nullptr);
9147 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009148 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009149 ValueDecl *D = Res.first;
9150 if (!D)
9151 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009152
Alexey Bataev74caaf22016-02-20 04:09:36 +00009153 QualType Type = D->getType();
9154 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009155
9156 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9157 // A variable that appears in a lastprivate clause must not have an
9158 // incomplete type or a reference type.
9159 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009160 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009161 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009162 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009163
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009164 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009165 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9166 // in a Construct]
9167 // Variables with the predetermined data-sharing attributes may not be
9168 // listed in data-sharing attributes clauses, except for the cases
9169 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009170 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9171 // A list item may appear in a firstprivate or lastprivate clause but not
9172 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009173 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009174 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009175 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009176 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9177 Diag(ELoc, diag::err_omp_wrong_dsa)
9178 << getOpenMPClauseName(DVar.CKind)
9179 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009180 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009181 continue;
9182 }
9183
Alexey Bataevf29276e2014-06-18 04:14:57 +00009184 // OpenMP [2.14.3.5, Restrictions, p.2]
9185 // A list item that is private within a parallel region, or that appears in
9186 // the reduction clause of a parallel construct, must not appear in a
9187 // lastprivate clause on a worksharing construct if any of the corresponding
9188 // worksharing regions ever binds to any of the corresponding parallel
9189 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009190 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009191 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009192 !isOpenMPParallelDirective(CurrDir) &&
9193 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009194 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009195 if (DVar.CKind != OMPC_shared) {
9196 Diag(ELoc, diag::err_omp_required_access)
9197 << getOpenMPClauseName(OMPC_lastprivate)
9198 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009199 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009200 continue;
9201 }
9202 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009203
Alexander Musman1bb328c2014-06-04 13:06:39 +00009204 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009205 // A variable of class type (or array thereof) that appears in a
9206 // lastprivate clause requires an accessible, unambiguous default
9207 // constructor for the class type, unless the list item is also specified
9208 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009209 // A variable of class type (or array thereof) that appears in a
9210 // lastprivate clause requires an accessible, unambiguous copy assignment
9211 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009212 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009213 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009214 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009215 D->hasAttrs() ? &D->getAttrs() : nullptr);
9216 auto *PseudoSrcExpr =
9217 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009218 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009219 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009220 D->hasAttrs() ? &D->getAttrs() : nullptr);
9221 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009222 // For arrays generate assignment operation for single element and replace
9223 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009224 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009225 PseudoDstExpr, PseudoSrcExpr);
9226 if (AssignmentOp.isInvalid())
9227 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009228 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009229 /*DiscardedValue=*/true);
9230 if (AssignmentOp.isInvalid())
9231 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009232
Alexey Bataev74caaf22016-02-20 04:09:36 +00009233 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009234 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009235 if (TopDVar.CKind == OMPC_firstprivate)
9236 Ref = TopDVar.PrivateCopy;
9237 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009238 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009239 if (!IsOpenMPCapturedDecl(D))
9240 ExprCaptures.push_back(Ref->getDecl());
9241 }
9242 if (TopDVar.CKind == OMPC_firstprivate ||
9243 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009244 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009245 ExprResult RefRes = DefaultLvalueConversion(Ref);
9246 if (!RefRes.isUsable())
9247 continue;
9248 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009249 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9250 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009251 if (!PostUpdateRes.isUsable())
9252 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009253 ExprPostUpdates.push_back(
9254 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009255 }
9256 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009257 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009258 Vars.push_back((VD || CurContext->isDependentContext())
9259 ? RefExpr->IgnoreParens()
9260 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009261 SrcExprs.push_back(PseudoSrcExpr);
9262 DstExprs.push_back(PseudoDstExpr);
9263 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009264 }
9265
9266 if (Vars.empty())
9267 return nullptr;
9268
9269 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009270 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009271 buildPreInits(Context, ExprCaptures),
9272 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009273}
9274
Alexey Bataev758e55e2013-09-06 18:03:48 +00009275OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9276 SourceLocation StartLoc,
9277 SourceLocation LParenLoc,
9278 SourceLocation EndLoc) {
9279 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009280 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009281 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009282 SourceLocation ELoc;
9283 SourceRange ERange;
9284 Expr *SimpleRefExpr = RefExpr;
9285 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009286 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009287 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009288 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009289 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009290 ValueDecl *D = Res.first;
9291 if (!D)
9292 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009293
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009294 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009295 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9296 // in a Construct]
9297 // Variables with the predetermined data-sharing attributes may not be
9298 // listed in data-sharing attributes clauses, except for the cases
9299 // listed below. For these exceptions only, listing a predetermined
9300 // variable in a data-sharing attribute clause is allowed and overrides
9301 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009302 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009303 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9304 DVar.RefExpr) {
9305 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9306 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009307 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009308 continue;
9309 }
9310
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009311 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009312 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009313 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009314 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009315 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9316 ? RefExpr->IgnoreParens()
9317 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009318 }
9319
Alexey Bataeved09d242014-05-28 05:53:51 +00009320 if (Vars.empty())
9321 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009322
9323 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9324}
9325
Alexey Bataevc5e02582014-06-16 07:08:35 +00009326namespace {
9327class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9328 DSAStackTy *Stack;
9329
9330public:
9331 bool VisitDeclRefExpr(DeclRefExpr *E) {
9332 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009333 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009334 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9335 return false;
9336 if (DVar.CKind != OMPC_unknown)
9337 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009338 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9339 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009340 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009341 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009342 return true;
9343 return false;
9344 }
9345 return false;
9346 }
9347 bool VisitStmt(Stmt *S) {
9348 for (auto Child : S->children()) {
9349 if (Child && Visit(Child))
9350 return true;
9351 }
9352 return false;
9353 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009354 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009355};
Alexey Bataev23b69422014-06-18 07:08:49 +00009356} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009357
Alexey Bataev60da77e2016-02-29 05:54:20 +00009358namespace {
9359// Transform MemberExpression for specified FieldDecl of current class to
9360// DeclRefExpr to specified OMPCapturedExprDecl.
9361class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9362 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9363 ValueDecl *Field;
9364 DeclRefExpr *CapturedExpr;
9365
9366public:
9367 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9368 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9369
9370 ExprResult TransformMemberExpr(MemberExpr *E) {
9371 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9372 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009373 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009374 return CapturedExpr;
9375 }
9376 return BaseTransform::TransformMemberExpr(E);
9377 }
9378 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9379};
9380} // namespace
9381
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009382template <typename T>
9383static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9384 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9385 for (auto &Set : Lookups) {
9386 for (auto *D : Set) {
9387 if (auto Res = Gen(cast<ValueDecl>(D)))
9388 return Res;
9389 }
9390 }
9391 return T();
9392}
9393
9394static ExprResult
9395buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9396 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9397 const DeclarationNameInfo &ReductionId, QualType Ty,
9398 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9399 if (ReductionIdScopeSpec.isInvalid())
9400 return ExprError();
9401 SmallVector<UnresolvedSet<8>, 4> Lookups;
9402 if (S) {
9403 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9404 Lookup.suppressDiagnostics();
9405 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9406 auto *D = Lookup.getRepresentativeDecl();
9407 do {
9408 S = S->getParent();
9409 } while (S && !S->isDeclScope(D));
9410 if (S)
9411 S = S->getParent();
9412 Lookups.push_back(UnresolvedSet<8>());
9413 Lookups.back().append(Lookup.begin(), Lookup.end());
9414 Lookup.clear();
9415 }
9416 } else if (auto *ULE =
9417 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9418 Lookups.push_back(UnresolvedSet<8>());
9419 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009420 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009421 if (D == PrevD)
9422 Lookups.push_back(UnresolvedSet<8>());
9423 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9424 Lookups.back().addDecl(DRD);
9425 PrevD = D;
9426 }
9427 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009428 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9429 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009430 Ty->containsUnexpandedParameterPack() ||
9431 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9432 return !D->isInvalidDecl() &&
9433 (D->getType()->isDependentType() ||
9434 D->getType()->isInstantiationDependentType() ||
9435 D->getType()->containsUnexpandedParameterPack());
9436 })) {
9437 UnresolvedSet<8> ResSet;
9438 for (auto &Set : Lookups) {
9439 ResSet.append(Set.begin(), Set.end());
9440 // The last item marks the end of all declarations at the specified scope.
9441 ResSet.addDecl(Set[Set.size() - 1]);
9442 }
9443 return UnresolvedLookupExpr::Create(
9444 SemaRef.Context, /*NamingClass=*/nullptr,
9445 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9446 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9447 }
9448 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9449 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9450 if (!D->isInvalidDecl() &&
9451 SemaRef.Context.hasSameType(D->getType(), Ty))
9452 return D;
9453 return nullptr;
9454 }))
9455 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9456 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9457 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9458 if (!D->isInvalidDecl() &&
9459 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9460 !Ty.isMoreQualifiedThan(D->getType()))
9461 return D;
9462 return nullptr;
9463 })) {
9464 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9465 /*DetectVirtual=*/false);
9466 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9467 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9468 VD->getType().getUnqualifiedType()))) {
9469 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9470 /*DiagID=*/0) !=
9471 Sema::AR_inaccessible) {
9472 SemaRef.BuildBasePathArray(Paths, BasePath);
9473 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9474 }
9475 }
9476 }
9477 }
9478 if (ReductionIdScopeSpec.isSet()) {
9479 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9480 return ExprError();
9481 }
9482 return ExprEmpty();
9483}
9484
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009485namespace {
9486/// Data for the reduction-based clauses.
9487struct ReductionData {
9488 /// List of original reduction items.
9489 SmallVector<Expr *, 8> Vars;
9490 /// List of private copies of the reduction items.
9491 SmallVector<Expr *, 8> Privates;
9492 /// LHS expressions for the reduction_op expressions.
9493 SmallVector<Expr *, 8> LHSs;
9494 /// RHS expressions for the reduction_op expressions.
9495 SmallVector<Expr *, 8> RHSs;
9496 /// Reduction operation expression.
9497 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009498 /// Taskgroup descriptors for the corresponding reduction items in
9499 /// in_reduction clauses.
9500 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009501 /// List of captures for clause.
9502 SmallVector<Decl *, 4> ExprCaptures;
9503 /// List of postupdate expressions.
9504 SmallVector<Expr *, 4> ExprPostUpdates;
9505 ReductionData() = delete;
9506 /// Reserves required memory for the reduction data.
9507 ReductionData(unsigned Size) {
9508 Vars.reserve(Size);
9509 Privates.reserve(Size);
9510 LHSs.reserve(Size);
9511 RHSs.reserve(Size);
9512 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009513 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009514 ExprCaptures.reserve(Size);
9515 ExprPostUpdates.reserve(Size);
9516 }
9517 /// Stores reduction item and reduction operation only (required for dependent
9518 /// reduction item).
9519 void push(Expr *Item, Expr *ReductionOp) {
9520 Vars.emplace_back(Item);
9521 Privates.emplace_back(nullptr);
9522 LHSs.emplace_back(nullptr);
9523 RHSs.emplace_back(nullptr);
9524 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009525 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009526 }
9527 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009528 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9529 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009530 Vars.emplace_back(Item);
9531 Privates.emplace_back(Private);
9532 LHSs.emplace_back(LHS);
9533 RHSs.emplace_back(RHS);
9534 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009535 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009536 }
9537};
9538} // namespace
9539
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009540static bool CheckOMPArraySectionConstantForReduction(
9541 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9542 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9543 const Expr *Length = OASE->getLength();
9544 if (Length == nullptr) {
9545 // For array sections of the form [1:] or [:], we would need to analyze
9546 // the lower bound...
9547 if (OASE->getColonLoc().isValid())
9548 return false;
9549
9550 // This is an array subscript which has implicit length 1!
9551 SingleElement = true;
9552 ArraySizes.push_back(llvm::APSInt::get(1));
9553 } else {
9554 llvm::APSInt ConstantLengthValue;
9555 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9556 return false;
9557
9558 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9559 ArraySizes.push_back(ConstantLengthValue);
9560 }
9561
9562 // Get the base of this array section and walk up from there.
9563 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9564
9565 // We require length = 1 for all array sections except the right-most to
9566 // guarantee that the memory region is contiguous and has no holes in it.
9567 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9568 Length = TempOASE->getLength();
9569 if (Length == nullptr) {
9570 // For array sections of the form [1:] or [:], we would need to analyze
9571 // the lower bound...
9572 if (OASE->getColonLoc().isValid())
9573 return false;
9574
9575 // This is an array subscript which has implicit length 1!
9576 ArraySizes.push_back(llvm::APSInt::get(1));
9577 } else {
9578 llvm::APSInt ConstantLengthValue;
9579 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9580 ConstantLengthValue.getSExtValue() != 1)
9581 return false;
9582
9583 ArraySizes.push_back(ConstantLengthValue);
9584 }
9585 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9586 }
9587
9588 // If we have a single element, we don't need to add the implicit lengths.
9589 if (!SingleElement) {
9590 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9591 // Has implicit length 1!
9592 ArraySizes.push_back(llvm::APSInt::get(1));
9593 Base = TempASE->getBase()->IgnoreParenImpCasts();
9594 }
9595 }
9596
9597 // This array section can be privatized as a single value or as a constant
9598 // sized array.
9599 return true;
9600}
9601
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009602static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009603 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9604 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9605 SourceLocation ColonLoc, SourceLocation EndLoc,
9606 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009607 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009608 auto DN = ReductionId.getName();
9609 auto OOK = DN.getCXXOverloadedOperator();
9610 BinaryOperatorKind BOK = BO_Comma;
9611
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009612 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009613 // OpenMP [2.14.3.6, reduction clause]
9614 // C
9615 // reduction-identifier is either an identifier or one of the following
9616 // operators: +, -, *, &, |, ^, && and ||
9617 // C++
9618 // reduction-identifier is either an id-expression or one of the following
9619 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009620 switch (OOK) {
9621 case OO_Plus:
9622 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009623 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009624 break;
9625 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009626 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009627 break;
9628 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009629 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009630 break;
9631 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009632 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009633 break;
9634 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009635 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009636 break;
9637 case OO_AmpAmp:
9638 BOK = BO_LAnd;
9639 break;
9640 case OO_PipePipe:
9641 BOK = BO_LOr;
9642 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009643 case OO_New:
9644 case OO_Delete:
9645 case OO_Array_New:
9646 case OO_Array_Delete:
9647 case OO_Slash:
9648 case OO_Percent:
9649 case OO_Tilde:
9650 case OO_Exclaim:
9651 case OO_Equal:
9652 case OO_Less:
9653 case OO_Greater:
9654 case OO_LessEqual:
9655 case OO_GreaterEqual:
9656 case OO_PlusEqual:
9657 case OO_MinusEqual:
9658 case OO_StarEqual:
9659 case OO_SlashEqual:
9660 case OO_PercentEqual:
9661 case OO_CaretEqual:
9662 case OO_AmpEqual:
9663 case OO_PipeEqual:
9664 case OO_LessLess:
9665 case OO_GreaterGreater:
9666 case OO_LessLessEqual:
9667 case OO_GreaterGreaterEqual:
9668 case OO_EqualEqual:
9669 case OO_ExclaimEqual:
9670 case OO_PlusPlus:
9671 case OO_MinusMinus:
9672 case OO_Comma:
9673 case OO_ArrowStar:
9674 case OO_Arrow:
9675 case OO_Call:
9676 case OO_Subscript:
9677 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009678 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009679 case NUM_OVERLOADED_OPERATORS:
9680 llvm_unreachable("Unexpected reduction identifier");
9681 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009682 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009683 if (II->isStr("max"))
9684 BOK = BO_GT;
9685 else if (II->isStr("min"))
9686 BOK = BO_LT;
9687 }
9688 break;
9689 }
9690 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009691 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009692 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009693 else
9694 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009695 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009696
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009697 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9698 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009699 for (auto RefExpr : VarList) {
9700 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009701 // OpenMP [2.1, C/C++]
9702 // A list item is a variable or array section, subject to the restrictions
9703 // specified in Section 2.4 on page 42 and in each of the sections
9704 // describing clauses and directives for which a list appears.
9705 // OpenMP [2.14.3.3, Restrictions, p.1]
9706 // A variable that is part of another variable (as an array or
9707 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009708 if (!FirstIter && IR != ER)
9709 ++IR;
9710 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009711 SourceLocation ELoc;
9712 SourceRange ERange;
9713 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009714 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009715 /*AllowArraySection=*/true);
9716 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009717 // Try to find 'declare reduction' corresponding construct before using
9718 // builtin/overloaded operators.
9719 QualType Type = Context.DependentTy;
9720 CXXCastPath BasePath;
9721 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009722 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009723 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009724 Expr *ReductionOp = nullptr;
9725 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009726 (DeclareReductionRef.isUnset() ||
9727 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009728 ReductionOp = DeclareReductionRef.get();
9729 // It will be analyzed later.
9730 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009731 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009732 ValueDecl *D = Res.first;
9733 if (!D)
9734 continue;
9735
Alexey Bataev88202be2017-07-27 13:20:36 +00009736 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009737 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009738 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9739 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9740 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009741 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009742 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009743 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9744 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9745 Type = ATy->getElementType();
9746 else
9747 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009748 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009749 } else
9750 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9751 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009752
Alexey Bataevc5e02582014-06-16 07:08:35 +00009753 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9754 // A variable that appears in a private clause must not have an incomplete
9755 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009756 if (S.RequireCompleteType(ELoc, Type,
9757 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009758 continue;
9759 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009760 // A list item that appears in a reduction clause must not be
9761 // const-qualified.
9762 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009763 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009764 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009765 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9766 VarDecl::DeclarationOnly;
9767 S.Diag(D->getLocation(),
9768 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009769 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009770 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009771 continue;
9772 }
9773 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9774 // If a list-item is a reference type then it must bind to the same object
9775 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009776 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009777 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009778 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009779 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009780 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009781 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9782 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009783 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009784 continue;
9785 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009786 }
9787 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009788
Alexey Bataevc5e02582014-06-16 07:08:35 +00009789 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9790 // in a Construct]
9791 // Variables with the predetermined data-sharing attributes may not be
9792 // listed in data-sharing attributes clauses, except for the cases
9793 // listed below. For these exceptions only, listing a predetermined
9794 // variable in a data-sharing attribute clause is allowed and overrides
9795 // the variable's predetermined data-sharing attributes.
9796 // OpenMP [2.14.3.6, Restrictions, p.3]
9797 // Any number of reduction clauses can be specified on the directive,
9798 // but a list item can appear only once in the reduction clauses for that
9799 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009800 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009801 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009802 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009803 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009804 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009805 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009806 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009807 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009808 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009809 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009810 << getOpenMPClauseName(DVar.CKind)
9811 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009812 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009813 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009814 }
9815
9816 // OpenMP [2.14.3.6, Restrictions, p.1]
9817 // A list item that appears in a reduction clause of a worksharing
9818 // construct must be shared in the parallel regions to which any of the
9819 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009820 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009821 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009822 !isOpenMPParallelDirective(CurrDir) &&
9823 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009824 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009825 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009826 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009827 << getOpenMPClauseName(OMPC_reduction)
9828 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009829 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009830 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009831 }
9832 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009833
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009834 // Try to find 'declare reduction' corresponding construct before using
9835 // builtin/overloaded operators.
9836 CXXCastPath BasePath;
9837 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009838 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009839 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9840 if (DeclareReductionRef.isInvalid())
9841 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009842 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009843 (DeclareReductionRef.isUnset() ||
9844 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009845 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009846 continue;
9847 }
9848 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9849 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009850 S.Diag(ReductionId.getLocStart(),
9851 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009852 << Type << ReductionIdRange;
9853 continue;
9854 }
9855
9856 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9857 // The type of a list item that appears in a reduction clause must be valid
9858 // for the reduction-identifier. For a max or min reduction in C, the type
9859 // of the list item must be an allowed arithmetic data type: char, int,
9860 // float, double, or _Bool, possibly modified with long, short, signed, or
9861 // unsigned. For a max or min reduction in C++, the type of the list item
9862 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9863 // double, or bool, possibly modified with long, short, signed, or unsigned.
9864 if (DeclareReductionRef.isUnset()) {
9865 if ((BOK == BO_GT || BOK == BO_LT) &&
9866 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009867 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9868 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009869 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009870 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009871 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9872 VarDecl::DeclarationOnly;
9873 S.Diag(D->getLocation(),
9874 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009875 << D;
9876 }
9877 continue;
9878 }
9879 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009880 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009881 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9882 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009883 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009884 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9885 VarDecl::DeclarationOnly;
9886 S.Diag(D->getLocation(),
9887 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009888 << D;
9889 }
9890 continue;
9891 }
9892 }
9893
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009894 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009895 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009896 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009897 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009898 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009899 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009900
9901 // Try if we can determine constant lengths for all array sections and avoid
9902 // the VLA.
9903 bool ConstantLengthOASE = false;
9904 if (OASE) {
9905 bool SingleElement;
9906 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
9907 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
9908 Context, OASE, SingleElement, ArraySizes);
9909
9910 // If we don't have a single element, we must emit a constant array type.
9911 if (ConstantLengthOASE && !SingleElement) {
9912 for (auto &Size : ArraySizes) {
9913 PrivateTy = Context.getConstantArrayType(
9914 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
9915 }
9916 }
9917 }
9918
9919 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +00009920 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +00009921 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00009922 if (!Context.getTargetInfo().isVLASupported() &&
9923 S.shouldDiagnoseTargetSupportFromOpenMP()) {
9924 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
9925 S.Diag(ELoc, diag::note_vla_unsupported);
9926 continue;
9927 }
David Majnemer9d168222016-08-05 17:44:54 +00009928 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009929 // Create pseudo array type for private copy. The size for this array will
9930 // be generated during codegen.
9931 // For array subscripts or single variables Private Ty is the same as Type
9932 // (type of the variable or single array element).
9933 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009934 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +00009935 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009936 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009937 } else if (!ASE && !OASE &&
9938 Context.getAsArrayType(D->getType().getNonReferenceType()))
9939 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009940 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009941 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009942 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009943 // Add initializer for private variable.
9944 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009945 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9946 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009947 if (DeclareReductionRef.isUsable()) {
9948 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9949 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9950 if (DRD->getInitializer()) {
9951 Init = DRDRef;
9952 RHSVD->setInit(DRDRef);
9953 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009954 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009955 } else {
9956 switch (BOK) {
9957 case BO_Add:
9958 case BO_Xor:
9959 case BO_Or:
9960 case BO_LOr:
9961 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9962 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009963 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009964 break;
9965 case BO_Mul:
9966 case BO_LAnd:
9967 if (Type->isScalarType() || Type->isAnyComplexType()) {
9968 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009969 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009970 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009971 break;
9972 case BO_And: {
9973 // '&' reduction op - initializer is '~0'.
9974 QualType OrigType = Type;
9975 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9976 Type = ComplexTy->getElementType();
9977 if (Type->isRealFloatingType()) {
9978 llvm::APFloat InitValue =
9979 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9980 /*isIEEE=*/true);
9981 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9982 Type, ELoc);
9983 } else if (Type->isScalarType()) {
9984 auto Size = Context.getTypeSize(Type);
9985 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9986 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9987 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9988 }
9989 if (Init && OrigType->isAnyComplexType()) {
9990 // Init = 0xFFFF + 0xFFFFi;
9991 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009992 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009993 }
9994 Type = OrigType;
9995 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009996 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009997 case BO_LT:
9998 case BO_GT: {
9999 // 'min' reduction op - initializer is 'Largest representable number in
10000 // the reduction list item type'.
10001 // 'max' reduction op - initializer is 'Least representable number in
10002 // the reduction list item type'.
10003 if (Type->isIntegerType() || Type->isPointerType()) {
10004 bool IsSigned = Type->hasSignedIntegerRepresentation();
10005 auto Size = Context.getTypeSize(Type);
10006 QualType IntTy =
10007 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10008 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010009 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10010 : llvm::APInt::getMinValue(Size)
10011 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10012 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010013 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10014 if (Type->isPointerType()) {
10015 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010016 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010017 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010018 if (CastExpr.isInvalid())
10019 continue;
10020 Init = CastExpr.get();
10021 }
10022 } else if (Type->isRealFloatingType()) {
10023 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10024 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10025 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10026 Type, ELoc);
10027 }
10028 break;
10029 }
10030 case BO_PtrMemD:
10031 case BO_PtrMemI:
10032 case BO_MulAssign:
10033 case BO_Div:
10034 case BO_Rem:
10035 case BO_Sub:
10036 case BO_Shl:
10037 case BO_Shr:
10038 case BO_LE:
10039 case BO_GE:
10040 case BO_EQ:
10041 case BO_NE:
10042 case BO_AndAssign:
10043 case BO_XorAssign:
10044 case BO_OrAssign:
10045 case BO_Assign:
10046 case BO_AddAssign:
10047 case BO_SubAssign:
10048 case BO_DivAssign:
10049 case BO_RemAssign:
10050 case BO_ShlAssign:
10051 case BO_ShrAssign:
10052 case BO_Comma:
10053 llvm_unreachable("Unexpected reduction operation");
10054 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010055 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010056 if (Init && DeclareReductionRef.isUnset())
10057 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10058 else if (!Init)
10059 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010060 if (RHSVD->isInvalidDecl())
10061 continue;
10062 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010063 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10064 << Type << ReductionIdRange;
10065 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10066 VarDecl::DeclarationOnly;
10067 S.Diag(D->getLocation(),
10068 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010069 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010070 continue;
10071 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010072 // Store initializer for single element in private copy. Will be used during
10073 // codegen.
10074 PrivateVD->setInit(RHSVD->getInit());
10075 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010076 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010077 ExprResult ReductionOp;
10078 if (DeclareReductionRef.isUsable()) {
10079 QualType RedTy = DeclareReductionRef.get()->getType();
10080 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010081 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10082 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010083 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010084 LHS = S.DefaultLvalueConversion(LHS.get());
10085 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010086 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10087 CK_UncheckedDerivedToBase, LHS.get(),
10088 &BasePath, LHS.get()->getValueKind());
10089 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10090 CK_UncheckedDerivedToBase, RHS.get(),
10091 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010092 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010093 FunctionProtoType::ExtProtoInfo EPI;
10094 QualType Params[] = {PtrRedTy, PtrRedTy};
10095 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10096 auto *OVE = new (Context) OpaqueValueExpr(
10097 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010098 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010099 Expr *Args[] = {LHS.get(), RHS.get()};
10100 ReductionOp = new (Context)
10101 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10102 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010103 ReductionOp = S.BuildBinOp(
10104 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010105 if (ReductionOp.isUsable()) {
10106 if (BOK != BO_LT && BOK != BO_GT) {
10107 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010108 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10109 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010110 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010111 auto *ConditionalOp = new (Context)
10112 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10113 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010114 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010115 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10116 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010117 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010118 if (ReductionOp.isUsable())
10119 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010120 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010121 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010122 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010123 }
10124
Alexey Bataevfa312f32017-07-21 18:48:21 +000010125 // OpenMP [2.15.4.6, Restrictions, p.2]
10126 // A list item that appears in an in_reduction clause of a task construct
10127 // must appear in a task_reduction clause of a construct associated with a
10128 // taskgroup region that includes the participating task in its taskgroup
10129 // set. The construct associated with the innermost region that meets this
10130 // condition must specify the same reduction-identifier as the in_reduction
10131 // clause.
10132 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010133 SourceRange ParentSR;
10134 BinaryOperatorKind ParentBOK;
10135 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010136 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010137 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010138 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10139 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010140 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010141 Stack->getTopMostTaskgroupReductionData(
10142 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010143 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10144 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10145 if (!IsParentBOK && !IsParentReductionOp) {
10146 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10147 continue;
10148 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010149 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10150 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10151 IsParentReductionOp) {
10152 bool EmitError = true;
10153 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10154 llvm::FoldingSetNodeID RedId, ParentRedId;
10155 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10156 DeclareReductionRef.get()->Profile(RedId, Context,
10157 /*Canonical=*/true);
10158 EmitError = RedId != ParentRedId;
10159 }
10160 if (EmitError) {
10161 S.Diag(ReductionId.getLocStart(),
10162 diag::err_omp_reduction_identifier_mismatch)
10163 << ReductionIdRange << RefExpr->getSourceRange();
10164 S.Diag(ParentSR.getBegin(),
10165 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010166 << ParentSR
10167 << (IsParentBOK ? ParentBOKDSA.RefExpr
10168 : ParentReductionOpDSA.RefExpr)
10169 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010170 continue;
10171 }
10172 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010173 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10174 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010175 }
10176
Alexey Bataev60da77e2016-02-29 05:54:20 +000010177 DeclRefExpr *Ref = nullptr;
10178 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010179 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010180 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010181 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010182 VarsExpr =
10183 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10184 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010185 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010186 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010187 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010188 if (!S.IsOpenMPCapturedDecl(D)) {
10189 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010190 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010191 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010192 if (!RefRes.isUsable())
10193 continue;
10194 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010195 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10196 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010197 if (!PostUpdateRes.isUsable())
10198 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010199 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10200 Stack->getCurrentDirective() == OMPD_taskgroup) {
10201 S.Diag(RefExpr->getExprLoc(),
10202 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010203 << RefExpr->getSourceRange();
10204 continue;
10205 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010206 RD.ExprPostUpdates.emplace_back(
10207 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010208 }
10209 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010210 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010211 // All reduction items are still marked as reduction (to do not increase
10212 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010213 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010214 if (CurrDir == OMPD_taskgroup) {
10215 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010216 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10217 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010218 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010219 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010220 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010221 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10222 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010223 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010224 return RD.Vars.empty();
10225}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010226
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010227OMPClause *Sema::ActOnOpenMPReductionClause(
10228 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10229 SourceLocation ColonLoc, SourceLocation EndLoc,
10230 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10231 ArrayRef<Expr *> UnresolvedReductions) {
10232 ReductionData RD(VarList.size());
10233
Alexey Bataev169d96a2017-07-18 20:17:46 +000010234 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10235 StartLoc, LParenLoc, ColonLoc, EndLoc,
10236 ReductionIdScopeSpec, ReductionId,
10237 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010238 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010239
Alexey Bataevc5e02582014-06-16 07:08:35 +000010240 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010241 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10242 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10243 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10244 buildPreInits(Context, RD.ExprCaptures),
10245 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010246}
10247
Alexey Bataev169d96a2017-07-18 20:17:46 +000010248OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10249 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10250 SourceLocation ColonLoc, SourceLocation EndLoc,
10251 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10252 ArrayRef<Expr *> UnresolvedReductions) {
10253 ReductionData RD(VarList.size());
10254
10255 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10256 VarList, StartLoc, LParenLoc, ColonLoc,
10257 EndLoc, ReductionIdScopeSpec, ReductionId,
10258 UnresolvedReductions, RD))
10259 return nullptr;
10260
10261 return OMPTaskReductionClause::Create(
10262 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10263 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10264 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10265 buildPreInits(Context, RD.ExprCaptures),
10266 buildPostUpdate(*this, RD.ExprPostUpdates));
10267}
10268
Alexey Bataevfa312f32017-07-21 18:48:21 +000010269OMPClause *Sema::ActOnOpenMPInReductionClause(
10270 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10271 SourceLocation ColonLoc, SourceLocation EndLoc,
10272 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10273 ArrayRef<Expr *> UnresolvedReductions) {
10274 ReductionData RD(VarList.size());
10275
10276 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10277 StartLoc, LParenLoc, ColonLoc, EndLoc,
10278 ReductionIdScopeSpec, ReductionId,
10279 UnresolvedReductions, RD))
10280 return nullptr;
10281
10282 return OMPInReductionClause::Create(
10283 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10284 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010285 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010286 buildPreInits(Context, RD.ExprCaptures),
10287 buildPostUpdate(*this, RD.ExprPostUpdates));
10288}
10289
Alexey Bataevecba70f2016-04-12 11:02:11 +000010290bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10291 SourceLocation LinLoc) {
10292 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10293 LinKind == OMPC_LINEAR_unknown) {
10294 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10295 return true;
10296 }
10297 return false;
10298}
10299
10300bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10301 OpenMPLinearClauseKind LinKind,
10302 QualType Type) {
10303 auto *VD = dyn_cast_or_null<VarDecl>(D);
10304 // A variable must not have an incomplete type or a reference type.
10305 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10306 return true;
10307 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10308 !Type->isReferenceType()) {
10309 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10310 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10311 return true;
10312 }
10313 Type = Type.getNonReferenceType();
10314
10315 // A list item must not be const-qualified.
10316 if (Type.isConstant(Context)) {
10317 Diag(ELoc, diag::err_omp_const_variable)
10318 << getOpenMPClauseName(OMPC_linear);
10319 if (D) {
10320 bool IsDecl =
10321 !VD ||
10322 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10323 Diag(D->getLocation(),
10324 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10325 << D;
10326 }
10327 return true;
10328 }
10329
10330 // A list item must be of integral or pointer type.
10331 Type = Type.getUnqualifiedType().getCanonicalType();
10332 const auto *Ty = Type.getTypePtrOrNull();
10333 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10334 !Ty->isPointerType())) {
10335 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10336 if (D) {
10337 bool IsDecl =
10338 !VD ||
10339 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10340 Diag(D->getLocation(),
10341 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10342 << D;
10343 }
10344 return true;
10345 }
10346 return false;
10347}
10348
Alexey Bataev182227b2015-08-20 10:54:39 +000010349OMPClause *Sema::ActOnOpenMPLinearClause(
10350 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10351 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10352 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010353 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010354 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010355 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010356 SmallVector<Decl *, 4> ExprCaptures;
10357 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010358 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010359 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010360 for (auto &RefExpr : VarList) {
10361 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010362 SourceLocation ELoc;
10363 SourceRange ERange;
10364 Expr *SimpleRefExpr = RefExpr;
10365 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10366 /*AllowArraySection=*/false);
10367 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010368 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010369 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010370 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010371 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010372 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010373 ValueDecl *D = Res.first;
10374 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010375 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010376
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010377 QualType Type = D->getType();
10378 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010379
10380 // OpenMP [2.14.3.7, linear clause]
10381 // A list-item cannot appear in more than one linear clause.
10382 // A list-item that appears in a linear clause cannot appear in any
10383 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010384 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010385 if (DVar.RefExpr) {
10386 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10387 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010388 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010389 continue;
10390 }
10391
Alexey Bataevecba70f2016-04-12 11:02:11 +000010392 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010393 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010394 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010395
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010396 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010397 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10398 D->hasAttrs() ? &D->getAttrs() : nullptr);
10399 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010400 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010401 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010402 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010403 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010404 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010405 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10406 if (!IsOpenMPCapturedDecl(D)) {
10407 ExprCaptures.push_back(Ref->getDecl());
10408 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10409 ExprResult RefRes = DefaultLvalueConversion(Ref);
10410 if (!RefRes.isUsable())
10411 continue;
10412 ExprResult PostUpdateRes =
10413 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10414 SimpleRefExpr, RefRes.get());
10415 if (!PostUpdateRes.isUsable())
10416 continue;
10417 ExprPostUpdates.push_back(
10418 IgnoredValueConversions(PostUpdateRes.get()).get());
10419 }
10420 }
10421 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010422 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010423 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010424 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010425 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010426 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010427 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010428 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10429
10430 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010431 Vars.push_back((VD || CurContext->isDependentContext())
10432 ? RefExpr->IgnoreParens()
10433 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010434 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010435 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010436 }
10437
10438 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010439 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010440
10441 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010442 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010443 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10444 !Step->isInstantiationDependent() &&
10445 !Step->containsUnexpandedParameterPack()) {
10446 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010447 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010448 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010449 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010450 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010451
Alexander Musman3276a272015-03-21 10:12:56 +000010452 // Build var to save the step value.
10453 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010454 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010455 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010456 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010457 ExprResult CalcStep =
10458 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010459 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010460
Alexander Musman8dba6642014-04-22 13:09:42 +000010461 // Warn about zero linear step (it would be probably better specified as
10462 // making corresponding variables 'const').
10463 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010464 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10465 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010466 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10467 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010468 if (!IsConstant && CalcStep.isUsable()) {
10469 // Calculate the step beforehand instead of doing this on each iteration.
10470 // (This is not used if the number of iterations may be kfold-ed).
10471 CalcStepExpr = CalcStep.get();
10472 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010473 }
10474
Alexey Bataev182227b2015-08-20 10:54:39 +000010475 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10476 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010477 StepExpr, CalcStepExpr,
10478 buildPreInits(Context, ExprCaptures),
10479 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010480}
10481
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010482static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10483 Expr *NumIterations, Sema &SemaRef,
10484 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010485 // Walk the vars and build update/final expressions for the CodeGen.
10486 SmallVector<Expr *, 8> Updates;
10487 SmallVector<Expr *, 8> Finals;
10488 Expr *Step = Clause.getStep();
10489 Expr *CalcStep = Clause.getCalcStep();
10490 // OpenMP [2.14.3.7, linear clause]
10491 // If linear-step is not specified it is assumed to be 1.
10492 if (Step == nullptr)
10493 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010494 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010495 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010496 }
Alexander Musman3276a272015-03-21 10:12:56 +000010497 bool HasErrors = false;
10498 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010499 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010500 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010501 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010502 SourceLocation ELoc;
10503 SourceRange ERange;
10504 Expr *SimpleRefExpr = RefExpr;
10505 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10506 /*AllowArraySection=*/false);
10507 ValueDecl *D = Res.first;
10508 if (Res.second || !D) {
10509 Updates.push_back(nullptr);
10510 Finals.push_back(nullptr);
10511 HasErrors = true;
10512 continue;
10513 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010514 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010515 Expr *InitExpr = *CurInit;
10516
10517 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010518 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010519 Expr *CapturedRef;
10520 if (LinKind == OMPC_LINEAR_uval)
10521 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10522 else
10523 CapturedRef =
10524 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10525 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10526 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010527
10528 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010529 ExprResult Update;
10530 if (!Info.first) {
10531 Update =
10532 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10533 InitExpr, IV, Step, /* Subtract */ false);
10534 } else
10535 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010536 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10537 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010538
10539 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010540 ExprResult Final;
10541 if (!Info.first) {
10542 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10543 InitExpr, NumIterations, Step,
10544 /* Subtract */ false);
10545 } else
10546 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010547 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10548 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010549
Alexander Musman3276a272015-03-21 10:12:56 +000010550 if (!Update.isUsable() || !Final.isUsable()) {
10551 Updates.push_back(nullptr);
10552 Finals.push_back(nullptr);
10553 HasErrors = true;
10554 } else {
10555 Updates.push_back(Update.get());
10556 Finals.push_back(Final.get());
10557 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010558 ++CurInit;
10559 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010560 }
10561 Clause.setUpdates(Updates);
10562 Clause.setFinals(Finals);
10563 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010564}
10565
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010566OMPClause *Sema::ActOnOpenMPAlignedClause(
10567 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10568 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10569
10570 SmallVector<Expr *, 8> Vars;
10571 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010572 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10573 SourceLocation ELoc;
10574 SourceRange ERange;
10575 Expr *SimpleRefExpr = RefExpr;
10576 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10577 /*AllowArraySection=*/false);
10578 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010579 // It will be analyzed later.
10580 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010581 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010582 ValueDecl *D = Res.first;
10583 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010584 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010585
Alexey Bataev1efd1662016-03-29 10:59:56 +000010586 QualType QType = D->getType();
10587 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010588
10589 // OpenMP [2.8.1, simd construct, Restrictions]
10590 // The type of list items appearing in the aligned clause must be
10591 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010592 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010593 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010594 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010595 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010596 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010597 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010598 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010599 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010600 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010601 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010602 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010603 continue;
10604 }
10605
10606 // OpenMP [2.8.1, simd construct, Restrictions]
10607 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010608 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010609 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010610 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10611 << getOpenMPClauseName(OMPC_aligned);
10612 continue;
10613 }
10614
Alexey Bataev1efd1662016-03-29 10:59:56 +000010615 DeclRefExpr *Ref = nullptr;
10616 if (!VD && IsOpenMPCapturedDecl(D))
10617 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10618 Vars.push_back(DefaultFunctionArrayConversion(
10619 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10620 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010621 }
10622
10623 // OpenMP [2.8.1, simd construct, Description]
10624 // The parameter of the aligned clause, alignment, must be a constant
10625 // positive integer expression.
10626 // If no optional parameter is specified, implementation-defined default
10627 // alignments for SIMD instructions on the target platforms are assumed.
10628 if (Alignment != nullptr) {
10629 ExprResult AlignResult =
10630 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10631 if (AlignResult.isInvalid())
10632 return nullptr;
10633 Alignment = AlignResult.get();
10634 }
10635 if (Vars.empty())
10636 return nullptr;
10637
10638 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10639 EndLoc, Vars, Alignment);
10640}
10641
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010642OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10643 SourceLocation StartLoc,
10644 SourceLocation LParenLoc,
10645 SourceLocation EndLoc) {
10646 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010647 SmallVector<Expr *, 8> SrcExprs;
10648 SmallVector<Expr *, 8> DstExprs;
10649 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010650 for (auto &RefExpr : VarList) {
10651 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10652 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010653 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010654 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010655 SrcExprs.push_back(nullptr);
10656 DstExprs.push_back(nullptr);
10657 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010658 continue;
10659 }
10660
Alexey Bataeved09d242014-05-28 05:53:51 +000010661 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010662 // OpenMP [2.1, C/C++]
10663 // A list item is a variable name.
10664 // OpenMP [2.14.4.1, Restrictions, p.1]
10665 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010666 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010667 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010668 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10669 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010670 continue;
10671 }
10672
10673 Decl *D = DE->getDecl();
10674 VarDecl *VD = cast<VarDecl>(D);
10675
10676 QualType Type = VD->getType();
10677 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10678 // It will be analyzed later.
10679 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010680 SrcExprs.push_back(nullptr);
10681 DstExprs.push_back(nullptr);
10682 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010683 continue;
10684 }
10685
10686 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10687 // A list item that appears in a copyin clause must be threadprivate.
10688 if (!DSAStack->isThreadPrivate(VD)) {
10689 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010690 << getOpenMPClauseName(OMPC_copyin)
10691 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010692 continue;
10693 }
10694
10695 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10696 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010697 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010698 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010699 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010700 auto *SrcVD =
10701 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10702 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010703 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010704 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10705 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010706 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10707 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010708 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010709 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010710 // For arrays generate assignment operation for single element and replace
10711 // it by the original array element in CodeGen.
10712 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10713 PseudoDstExpr, PseudoSrcExpr);
10714 if (AssignmentOp.isInvalid())
10715 continue;
10716 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10717 /*DiscardedValue=*/true);
10718 if (AssignmentOp.isInvalid())
10719 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010720
10721 DSAStack->addDSA(VD, DE, OMPC_copyin);
10722 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010723 SrcExprs.push_back(PseudoSrcExpr);
10724 DstExprs.push_back(PseudoDstExpr);
10725 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010726 }
10727
Alexey Bataeved09d242014-05-28 05:53:51 +000010728 if (Vars.empty())
10729 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010730
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010731 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10732 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010733}
10734
Alexey Bataevbae9a792014-06-27 10:37:06 +000010735OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10736 SourceLocation StartLoc,
10737 SourceLocation LParenLoc,
10738 SourceLocation EndLoc) {
10739 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010740 SmallVector<Expr *, 8> SrcExprs;
10741 SmallVector<Expr *, 8> DstExprs;
10742 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010743 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010744 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10745 SourceLocation ELoc;
10746 SourceRange ERange;
10747 Expr *SimpleRefExpr = RefExpr;
10748 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10749 /*AllowArraySection=*/false);
10750 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010751 // It will be analyzed later.
10752 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010753 SrcExprs.push_back(nullptr);
10754 DstExprs.push_back(nullptr);
10755 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010756 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010757 ValueDecl *D = Res.first;
10758 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010759 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010760
Alexey Bataeve122da12016-03-17 10:50:17 +000010761 QualType Type = D->getType();
10762 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010763
10764 // OpenMP [2.14.4.2, Restrictions, p.2]
10765 // A list item that appears in a copyprivate clause may not appear in a
10766 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010767 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10768 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010769 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10770 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010771 Diag(ELoc, diag::err_omp_wrong_dsa)
10772 << getOpenMPClauseName(DVar.CKind)
10773 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010774 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010775 continue;
10776 }
10777
10778 // OpenMP [2.11.4.2, Restrictions, p.1]
10779 // All list items that appear in a copyprivate clause must be either
10780 // threadprivate or private in the enclosing context.
10781 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010782 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010783 if (DVar.CKind == OMPC_shared) {
10784 Diag(ELoc, diag::err_omp_required_access)
10785 << getOpenMPClauseName(OMPC_copyprivate)
10786 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010787 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010788 continue;
10789 }
10790 }
10791 }
10792
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010793 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010794 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010795 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010796 << getOpenMPClauseName(OMPC_copyprivate) << Type
10797 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010798 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010799 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010800 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010801 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010802 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010803 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010804 continue;
10805 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010806
Alexey Bataevbae9a792014-06-27 10:37:06 +000010807 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10808 // A variable of class type (or array thereof) that appears in a
10809 // copyin clause requires an accessible, unambiguous copy assignment
10810 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010811 Type = Context.getBaseElementType(Type.getNonReferenceType())
10812 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010813 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010814 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10815 D->hasAttrs() ? &D->getAttrs() : nullptr);
10816 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010817 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010818 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10819 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010820 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010821 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010822 PseudoDstExpr, PseudoSrcExpr);
10823 if (AssignmentOp.isInvalid())
10824 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010825 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010826 /*DiscardedValue=*/true);
10827 if (AssignmentOp.isInvalid())
10828 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010829
10830 // No need to mark vars as copyprivate, they are already threadprivate or
10831 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010832 assert(VD || IsOpenMPCapturedDecl(D));
10833 Vars.push_back(
10834 VD ? RefExpr->IgnoreParens()
10835 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010836 SrcExprs.push_back(PseudoSrcExpr);
10837 DstExprs.push_back(PseudoDstExpr);
10838 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010839 }
10840
10841 if (Vars.empty())
10842 return nullptr;
10843
Alexey Bataeva63048e2015-03-23 06:18:07 +000010844 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10845 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010846}
10847
Alexey Bataev6125da92014-07-21 11:26:11 +000010848OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10849 SourceLocation StartLoc,
10850 SourceLocation LParenLoc,
10851 SourceLocation EndLoc) {
10852 if (VarList.empty())
10853 return nullptr;
10854
10855 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10856}
Alexey Bataevdea47612014-07-23 07:46:59 +000010857
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010858OMPClause *
10859Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10860 SourceLocation DepLoc, SourceLocation ColonLoc,
10861 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10862 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010863 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010864 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010865 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010866 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010867 return nullptr;
10868 }
10869 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010870 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10871 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010872 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010873 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010874 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10875 /*Last=*/OMPC_DEPEND_unknown, Except)
10876 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010877 return nullptr;
10878 }
10879 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010880 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010881 llvm::APSInt DepCounter(/*BitWidth=*/32);
10882 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10883 if (DepKind == OMPC_DEPEND_sink) {
10884 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10885 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10886 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010887 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010888 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010889 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10890 DSAStack->getParentOrderedRegionParam()) {
10891 for (auto &RefExpr : VarList) {
10892 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010893 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010894 // It will be analyzed later.
10895 Vars.push_back(RefExpr);
10896 continue;
10897 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010898
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010899 SourceLocation ELoc = RefExpr->getExprLoc();
10900 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10901 if (DepKind == OMPC_DEPEND_sink) {
10902 if (DepCounter >= TotalDepCount) {
10903 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10904 continue;
10905 }
10906 ++DepCounter;
10907 // OpenMP [2.13.9, Summary]
10908 // depend(dependence-type : vec), where dependence-type is:
10909 // 'sink' and where vec is the iteration vector, which has the form:
10910 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10911 // where n is the value specified by the ordered clause in the loop
10912 // directive, xi denotes the loop iteration variable of the i-th nested
10913 // loop associated with the loop directive, and di is a constant
10914 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010915 if (CurContext->isDependentContext()) {
10916 // It will be analyzed later.
10917 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010918 continue;
10919 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010920 SimpleExpr = SimpleExpr->IgnoreImplicit();
10921 OverloadedOperatorKind OOK = OO_None;
10922 SourceLocation OOLoc;
10923 Expr *LHS = SimpleExpr;
10924 Expr *RHS = nullptr;
10925 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10926 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10927 OOLoc = BO->getOperatorLoc();
10928 LHS = BO->getLHS()->IgnoreParenImpCasts();
10929 RHS = BO->getRHS()->IgnoreParenImpCasts();
10930 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10931 OOK = OCE->getOperator();
10932 OOLoc = OCE->getOperatorLoc();
10933 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10934 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10935 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10936 OOK = MCE->getMethodDecl()
10937 ->getNameInfo()
10938 .getName()
10939 .getCXXOverloadedOperator();
10940 OOLoc = MCE->getCallee()->getExprLoc();
10941 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10942 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10943 }
10944 SourceLocation ELoc;
10945 SourceRange ERange;
10946 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10947 /*AllowArraySection=*/false);
10948 if (Res.second) {
10949 // It will be analyzed later.
10950 Vars.push_back(RefExpr);
10951 }
10952 ValueDecl *D = Res.first;
10953 if (!D)
10954 continue;
10955
10956 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10957 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10958 continue;
10959 }
10960 if (RHS) {
10961 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10962 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10963 if (RHSRes.isInvalid())
10964 continue;
10965 }
10966 if (!CurContext->isDependentContext() &&
10967 DSAStack->getParentOrderedRegionParam() &&
10968 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000010969 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
10970 DepCounter.getZExtValue());
10971 if (VD) {
10972 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10973 << 1 << VD;
10974 } else {
10975 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
10976 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010977 continue;
10978 }
10979 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010980 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010981 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010982 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010983 (ASE &&
10984 !ASE->getBase()
10985 ->getType()
10986 .getNonReferenceType()
10987 ->isPointerType() &&
10988 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000010989 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10990 << RefExpr->getSourceRange();
10991 continue;
10992 }
10993 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
10994 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000010995 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000010996 RefExpr->IgnoreParenImpCasts());
10997 getDiagnostics().setSuppressAllDiagnostics(Suppress);
10998 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
10999 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11000 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011001 continue;
11002 }
11003 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011004 Vars.push_back(RefExpr->IgnoreParenImpCasts());
11005 }
11006
11007 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11008 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000011009 DSAStack->getParentOrderedRegionParam() &&
11010 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11011 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011012 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11013 }
11014 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11015 Vars.empty())
11016 return nullptr;
11017 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011018 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11019 DepKind, DepLoc, ColonLoc, Vars);
11020 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11021 DSAStack->addDoacrossDependClause(C, OpsOffs);
11022 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011023}
Michael Wonge710d542015-08-07 16:16:36 +000011024
11025OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11026 SourceLocation LParenLoc,
11027 SourceLocation EndLoc) {
11028 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011029 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011030
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011031 // OpenMP [2.9.1, Restrictions]
11032 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011033 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11034 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011035 return nullptr;
11036
Alexey Bataev931e19b2017-10-02 16:32:39 +000011037 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11038 if (isOpenMPTargetExecutionDirective(DKind) &&
11039 !CurContext->isDependentContext()) {
11040 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11041 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11042 HelperValStmt = buildPreInits(Context, Captures);
11043 }
11044
11045 return new (Context)
11046 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011047}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011048
Kelvin Li0bff7af2015-11-23 05:32:03 +000011049static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11050 DSAStackTy *Stack, QualType QTy) {
11051 NamedDecl *ND;
11052 if (QTy->isIncompleteType(&ND)) {
11053 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11054 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011055 }
11056 return true;
11057}
11058
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011059/// \brief Return true if it can be proven that the provided array expression
11060/// (array section or array subscript) does NOT specify the whole size of the
11061/// array whose base type is \a BaseQTy.
11062static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11063 const Expr *E,
11064 QualType BaseQTy) {
11065 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11066
11067 // If this is an array subscript, it refers to the whole size if the size of
11068 // the dimension is constant and equals 1. Also, an array section assumes the
11069 // format of an array subscript if no colon is used.
11070 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11071 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11072 return ATy->getSize().getSExtValue() != 1;
11073 // Size can't be evaluated statically.
11074 return false;
11075 }
11076
11077 assert(OASE && "Expecting array section if not an array subscript.");
11078 auto *LowerBound = OASE->getLowerBound();
11079 auto *Length = OASE->getLength();
11080
11081 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011082 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011083 if (LowerBound) {
11084 llvm::APSInt ConstLowerBound;
11085 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11086 return false; // Can't get the integer value as a constant.
11087 if (ConstLowerBound.getSExtValue())
11088 return true;
11089 }
11090
11091 // If we don't have a length we covering the whole dimension.
11092 if (!Length)
11093 return false;
11094
11095 // If the base is a pointer, we don't have a way to get the size of the
11096 // pointee.
11097 if (BaseQTy->isPointerType())
11098 return false;
11099
11100 // We can only check if the length is the same as the size of the dimension
11101 // if we have a constant array.
11102 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11103 if (!CATy)
11104 return false;
11105
11106 llvm::APSInt ConstLength;
11107 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11108 return false; // Can't get the integer value as a constant.
11109
11110 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11111}
11112
11113// Return true if it can be proven that the provided array expression (array
11114// section or array subscript) does NOT specify a single element of the array
11115// whose base type is \a BaseQTy.
11116static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011117 const Expr *E,
11118 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011119 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11120
11121 // An array subscript always refer to a single element. Also, an array section
11122 // assumes the format of an array subscript if no colon is used.
11123 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11124 return false;
11125
11126 assert(OASE && "Expecting array section if not an array subscript.");
11127 auto *Length = OASE->getLength();
11128
11129 // If we don't have a length we have to check if the array has unitary size
11130 // for this dimension. Also, we should always expect a length if the base type
11131 // is pointer.
11132 if (!Length) {
11133 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11134 return ATy->getSize().getSExtValue() != 1;
11135 // We cannot assume anything.
11136 return false;
11137 }
11138
11139 // Check if the length evaluates to 1.
11140 llvm::APSInt ConstLength;
11141 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11142 return false; // Can't get the integer value as a constant.
11143
11144 return ConstLength.getSExtValue() != 1;
11145}
11146
Samuel Antao661c0902016-05-26 17:39:58 +000011147// Return the expression of the base of the mappable expression or null if it
11148// cannot be determined and do all the necessary checks to see if the expression
11149// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011150// components of the expression.
11151static Expr *CheckMapClauseExpressionBase(
11152 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011153 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11154 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011155 SourceLocation ELoc = E->getExprLoc();
11156 SourceRange ERange = E->getSourceRange();
11157
11158 // The base of elements of list in a map clause have to be either:
11159 // - a reference to variable or field.
11160 // - a member expression.
11161 // - an array expression.
11162 //
11163 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11164 // reference to 'r'.
11165 //
11166 // If we have:
11167 //
11168 // struct SS {
11169 // Bla S;
11170 // foo() {
11171 // #pragma omp target map (S.Arr[:12]);
11172 // }
11173 // }
11174 //
11175 // We want to retrieve the member expression 'this->S';
11176
11177 Expr *RelevantExpr = nullptr;
11178
Samuel Antao5de996e2016-01-22 20:21:36 +000011179 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11180 // If a list item is an array section, it must specify contiguous storage.
11181 //
11182 // For this restriction it is sufficient that we make sure only references
11183 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011184 // exist except in the rightmost expression (unless they cover the whole
11185 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011186 //
11187 // r.ArrS[3:5].Arr[6:7]
11188 //
11189 // r.ArrS[3:5].x
11190 //
11191 // but these would be valid:
11192 // r.ArrS[3].Arr[6:7]
11193 //
11194 // r.ArrS[3].x
11195
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011196 bool AllowUnitySizeArraySection = true;
11197 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011198
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011199 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011200 E = E->IgnoreParenImpCasts();
11201
11202 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11203 if (!isa<VarDecl>(CurE->getDecl()))
11204 break;
11205
11206 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011207
11208 // If we got a reference to a declaration, we should not expect any array
11209 // section before that.
11210 AllowUnitySizeArraySection = false;
11211 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011212
11213 // Record the component.
11214 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
11215 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000011216 continue;
11217 }
11218
11219 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11220 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11221
11222 if (isa<CXXThisExpr>(BaseE))
11223 // We found a base expression: this->Val.
11224 RelevantExpr = CurE;
11225 else
11226 E = BaseE;
11227
11228 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11229 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11230 << CurE->getSourceRange();
11231 break;
11232 }
11233
11234 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11235
11236 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11237 // A bit-field cannot appear in a map clause.
11238 //
11239 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011240 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11241 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011242 break;
11243 }
11244
11245 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11246 // If the type of a list item is a reference to a type T then the type
11247 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011248 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011249
11250 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11251 // A list item cannot be a variable that is a member of a structure with
11252 // a union type.
11253 //
11254 if (auto *RT = CurType->getAs<RecordType>())
11255 if (RT->isUnionType()) {
11256 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11257 << CurE->getSourceRange();
11258 break;
11259 }
11260
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011261 // If we got a member expression, we should not expect any array section
11262 // before that:
11263 //
11264 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11265 // If a list item is an element of a structure, only the rightmost symbol
11266 // of the variable reference can be an array section.
11267 //
11268 AllowUnitySizeArraySection = false;
11269 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011270
11271 // Record the component.
11272 CurComponents.push_back(
11273 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000011274 continue;
11275 }
11276
11277 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11278 E = CurE->getBase()->IgnoreParenImpCasts();
11279
11280 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11281 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11282 << 0 << CurE->getSourceRange();
11283 break;
11284 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011285
11286 // If we got an array subscript that express the whole dimension we
11287 // can have any array expressions before. If it only expressing part of
11288 // the dimension, we can only have unitary-size array expressions.
11289 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11290 E->getType()))
11291 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011292
11293 // Record the component - we don't have any declaration associated.
11294 CurComponents.push_back(
11295 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011296 continue;
11297 }
11298
11299 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011300 E = CurE->getBase()->IgnoreParenImpCasts();
11301
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011302 auto CurType =
11303 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11304
Samuel Antao5de996e2016-01-22 20:21:36 +000011305 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11306 // If the type of a list item is a reference to a type T then the type
11307 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011308 if (CurType->isReferenceType())
11309 CurType = CurType->getPointeeType();
11310
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011311 bool IsPointer = CurType->isAnyPointerType();
11312
11313 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011314 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11315 << 0 << CurE->getSourceRange();
11316 break;
11317 }
11318
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011319 bool NotWhole =
11320 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11321 bool NotUnity =
11322 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11323
Samuel Antaodab51bb2016-07-18 23:22:11 +000011324 if (AllowWholeSizeArraySection) {
11325 // Any array section is currently allowed. Allowing a whole size array
11326 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011327 //
11328 // If this array section refers to the whole dimension we can still
11329 // accept other array sections before this one, except if the base is a
11330 // pointer. Otherwise, only unitary sections are accepted.
11331 if (NotWhole || IsPointer)
11332 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011333 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011334 // A unity or whole array section is not allowed and that is not
11335 // compatible with the properties of the current array section.
11336 SemaRef.Diag(
11337 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11338 << CurE->getSourceRange();
11339 break;
11340 }
Samuel Antao90927002016-04-26 14:54:23 +000011341
11342 // Record the component - we don't have any declaration associated.
11343 CurComponents.push_back(
11344 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011345 continue;
11346 }
11347
11348 // If nothing else worked, this is not a valid map clause expression.
11349 SemaRef.Diag(ELoc,
11350 diag::err_omp_expected_named_var_member_or_array_expression)
11351 << ERange;
11352 break;
11353 }
11354
11355 return RelevantExpr;
11356}
11357
11358// Return true if expression E associated with value VD has conflicts with other
11359// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011360static bool CheckMapConflicts(
11361 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11362 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011363 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11364 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011365 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011366 SourceLocation ELoc = E->getExprLoc();
11367 SourceRange ERange = E->getSourceRange();
11368
11369 // In order to easily check the conflicts we need to match each component of
11370 // the expression under test with the components of the expressions that are
11371 // already in the stack.
11372
Samuel Antao5de996e2016-01-22 20:21:36 +000011373 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011374 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011375 "Map clause expression with unexpected base!");
11376
11377 // Variables to help detecting enclosing problems in data environment nests.
11378 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011379 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011380
Samuel Antao90927002016-04-26 14:54:23 +000011381 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11382 VD, CurrentRegionOnly,
11383 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011384 StackComponents,
11385 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011386
Samuel Antao5de996e2016-01-22 20:21:36 +000011387 assert(!StackComponents.empty() &&
11388 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011389 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011390 "Map clause expression with unexpected base!");
11391
Samuel Antao90927002016-04-26 14:54:23 +000011392 // The whole expression in the stack.
11393 auto *RE = StackComponents.front().getAssociatedExpression();
11394
Samuel Antao5de996e2016-01-22 20:21:36 +000011395 // Expressions must start from the same base. Here we detect at which
11396 // point both expressions diverge from each other and see if we can
11397 // detect if the memory referred to both expressions is contiguous and
11398 // do not overlap.
11399 auto CI = CurComponents.rbegin();
11400 auto CE = CurComponents.rend();
11401 auto SI = StackComponents.rbegin();
11402 auto SE = StackComponents.rend();
11403 for (; CI != CE && SI != SE; ++CI, ++SI) {
11404
11405 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11406 // At most one list item can be an array item derived from a given
11407 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011408 if (CurrentRegionOnly &&
11409 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11410 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11411 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11412 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11413 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011414 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011415 << CI->getAssociatedExpression()->getSourceRange();
11416 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11417 diag::note_used_here)
11418 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011419 return true;
11420 }
11421
11422 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011423 if (CI->getAssociatedExpression()->getStmtClass() !=
11424 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011425 break;
11426
11427 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011428 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011429 break;
11430 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011431 // Check if the extra components of the expressions in the enclosing
11432 // data environment are redundant for the current base declaration.
11433 // If they are, the maps completely overlap, which is legal.
11434 for (; SI != SE; ++SI) {
11435 QualType Type;
11436 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011437 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011438 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011439 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11440 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011441 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11442 Type =
11443 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11444 }
11445 if (Type.isNull() || Type->isAnyPointerType() ||
11446 CheckArrayExpressionDoesNotReferToWholeSize(
11447 SemaRef, SI->getAssociatedExpression(), Type))
11448 break;
11449 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011450
11451 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11452 // List items of map clauses in the same construct must not share
11453 // original storage.
11454 //
11455 // If the expressions are exactly the same or one is a subset of the
11456 // other, it means they are sharing storage.
11457 if (CI == CE && SI == SE) {
11458 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011459 if (CKind == OMPC_map)
11460 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11461 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011462 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011463 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11464 << ERange;
11465 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011466 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11467 << RE->getSourceRange();
11468 return true;
11469 } else {
11470 // If we find the same expression in the enclosing data environment,
11471 // that is legal.
11472 IsEnclosedByDataEnvironmentExpr = true;
11473 return false;
11474 }
11475 }
11476
Samuel Antao90927002016-04-26 14:54:23 +000011477 QualType DerivedType =
11478 std::prev(CI)->getAssociatedDeclaration()->getType();
11479 SourceLocation DerivedLoc =
11480 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011481
11482 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11483 // If the type of a list item is a reference to a type T then the type
11484 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011485 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011486
11487 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11488 // A variable for which the type is pointer and an array section
11489 // derived from that variable must not appear as list items of map
11490 // clauses of the same construct.
11491 //
11492 // Also, cover one of the cases in:
11493 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11494 // If any part of the original storage of a list item has corresponding
11495 // storage in the device data environment, all of the original storage
11496 // must have corresponding storage in the device data environment.
11497 //
11498 if (DerivedType->isAnyPointerType()) {
11499 if (CI == CE || SI == SE) {
11500 SemaRef.Diag(
11501 DerivedLoc,
11502 diag::err_omp_pointer_mapped_along_with_derived_section)
11503 << DerivedLoc;
11504 } else {
11505 assert(CI != CE && SI != SE);
11506 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11507 << DerivedLoc;
11508 }
11509 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11510 << RE->getSourceRange();
11511 return true;
11512 }
11513
11514 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11515 // List items of map clauses in the same construct must not share
11516 // original storage.
11517 //
11518 // An expression is a subset of the other.
11519 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011520 if (CKind == OMPC_map)
11521 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11522 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011523 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011524 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11525 << ERange;
11526 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011527 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11528 << RE->getSourceRange();
11529 return true;
11530 }
11531
11532 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011533 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011534 if (!CurrentRegionOnly && SI != SE)
11535 EnclosingExpr = RE;
11536
11537 // The current expression is a subset of the expression in the data
11538 // environment.
11539 IsEnclosedByDataEnvironmentExpr |=
11540 (!CurrentRegionOnly && CI != CE && SI == SE);
11541
11542 return false;
11543 });
11544
11545 if (CurrentRegionOnly)
11546 return FoundError;
11547
11548 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11549 // If any part of the original storage of a list item has corresponding
11550 // storage in the device data environment, all of the original storage must
11551 // have corresponding storage in the device data environment.
11552 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11553 // If a list item is an element of a structure, and a different element of
11554 // the structure has a corresponding list item in the device data environment
11555 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011556 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011557 // data environment prior to the task encountering the construct.
11558 //
11559 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11560 SemaRef.Diag(ELoc,
11561 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11562 << ERange;
11563 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11564 << EnclosingExpr->getSourceRange();
11565 return true;
11566 }
11567
11568 return FoundError;
11569}
11570
Samuel Antao661c0902016-05-26 17:39:58 +000011571namespace {
11572// Utility struct that gathers all the related lists associated with a mappable
11573// expression.
11574struct MappableVarListInfo final {
11575 // The list of expressions.
11576 ArrayRef<Expr *> VarList;
11577 // The list of processed expressions.
11578 SmallVector<Expr *, 16> ProcessedVarList;
11579 // The mappble components for each expression.
11580 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11581 // The base declaration of the variable.
11582 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11583
11584 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11585 // We have a list of components and base declarations for each entry in the
11586 // variable list.
11587 VarComponents.reserve(VarList.size());
11588 VarBaseDeclarations.reserve(VarList.size());
11589 }
11590};
11591}
11592
11593// Check the validity of the provided variable list for the provided clause kind
11594// \a CKind. In the check process the valid expressions, and mappable expression
11595// components and variables are extracted and used to fill \a Vars,
11596// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11597// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11598static void
11599checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11600 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11601 SourceLocation StartLoc,
11602 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11603 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011604 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11605 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011606 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011607
Samuel Antao90927002016-04-26 14:54:23 +000011608 // Keep track of the mappable components and base declarations in this clause.
11609 // Each entry in the list is going to have a list of components associated. We
11610 // record each set of the components so that we can build the clause later on.
11611 // In the end we should have the same amount of declarations and component
11612 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011613
Samuel Antao661c0902016-05-26 17:39:58 +000011614 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011615 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011616 SourceLocation ELoc = RE->getExprLoc();
11617
Kelvin Li0bff7af2015-11-23 05:32:03 +000011618 auto *VE = RE->IgnoreParenLValueCasts();
11619
11620 if (VE->isValueDependent() || VE->isTypeDependent() ||
11621 VE->isInstantiationDependent() ||
11622 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011623 // We can only analyze this information once the missing information is
11624 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011625 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011626 continue;
11627 }
11628
11629 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011630
Samuel Antao5de996e2016-01-22 20:21:36 +000011631 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011632 SemaRef.Diag(ELoc,
11633 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011634 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011635 continue;
11636 }
11637
Samuel Antao90927002016-04-26 14:54:23 +000011638 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11639 ValueDecl *CurDeclaration = nullptr;
11640
11641 // Obtain the array or member expression bases if required. Also, fill the
11642 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011643 auto *BE =
11644 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011645 if (!BE)
11646 continue;
11647
Samuel Antao90927002016-04-26 14:54:23 +000011648 assert(!CurComponents.empty() &&
11649 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011650
Samuel Antao90927002016-04-26 14:54:23 +000011651 // For the following checks, we rely on the base declaration which is
11652 // expected to be associated with the last component. The declaration is
11653 // expected to be a variable or a field (if 'this' is being mapped).
11654 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11655 assert(CurDeclaration && "Null decl on map clause.");
11656 assert(
11657 CurDeclaration->isCanonicalDecl() &&
11658 "Expecting components to have associated only canonical declarations.");
11659
11660 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11661 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011662
11663 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011664 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011665
11666 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011667 // threadprivate variables cannot appear in a map clause.
11668 // OpenMP 4.5 [2.10.5, target update Construct]
11669 // threadprivate variables cannot appear in a from clause.
11670 if (VD && DSAS->isThreadPrivate(VD)) {
11671 auto DVar = DSAS->getTopDSA(VD, false);
11672 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11673 << getOpenMPClauseName(CKind);
11674 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011675 continue;
11676 }
11677
Samuel Antao5de996e2016-01-22 20:21:36 +000011678 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11679 // A list item cannot appear in both a map clause and a data-sharing
11680 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011681
Samuel Antao5de996e2016-01-22 20:21:36 +000011682 // Check conflicts with other map clause expressions. We check the conflicts
11683 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011684 // environment, because the restrictions are different. We only have to
11685 // check conflicts across regions for the map clauses.
11686 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11687 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011688 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011689 if (CKind == OMPC_map &&
11690 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11691 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011692 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011693
Samuel Antao661c0902016-05-26 17:39:58 +000011694 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011695 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11696 // If the type of a list item is a reference to a type T then the type will
11697 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011698 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011699
Samuel Antao661c0902016-05-26 17:39:58 +000011700 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11701 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011702 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011703 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011704 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11705 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011706 continue;
11707
Samuel Antao661c0902016-05-26 17:39:58 +000011708 if (CKind == OMPC_map) {
11709 // target enter data
11710 // OpenMP [2.10.2, Restrictions, p. 99]
11711 // A map-type must be specified in all map clauses and must be either
11712 // to or alloc.
11713 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11714 if (DKind == OMPD_target_enter_data &&
11715 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11716 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11717 << (IsMapTypeImplicit ? 1 : 0)
11718 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11719 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011720 continue;
11721 }
Samuel Antao661c0902016-05-26 17:39:58 +000011722
11723 // target exit_data
11724 // OpenMP [2.10.3, Restrictions, p. 102]
11725 // A map-type must be specified in all map clauses and must be either
11726 // from, release, or delete.
11727 if (DKind == OMPD_target_exit_data &&
11728 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11729 MapType == OMPC_MAP_delete)) {
11730 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11731 << (IsMapTypeImplicit ? 1 : 0)
11732 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11733 << getOpenMPDirectiveName(DKind);
11734 continue;
11735 }
11736
11737 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11738 // A list item cannot appear in both a map clause and a data-sharing
11739 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011740 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011741 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011742 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011743 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11744 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011745 auto DVar = DSAS->getTopDSA(VD, false);
11746 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011747 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011748 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011749 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011750 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11751 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11752 continue;
11753 }
11754 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011755 }
11756
Samuel Antao90927002016-04-26 14:54:23 +000011757 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011758 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011759
11760 // Store the components in the stack so that they can be used to check
11761 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011762 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11763 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011764
11765 // Save the components and declaration to create the clause. For purposes of
11766 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011767 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011768 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11769 MVLI.VarComponents.back().append(CurComponents.begin(),
11770 CurComponents.end());
11771 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11772 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011773 }
Samuel Antao661c0902016-05-26 17:39:58 +000011774}
11775
11776OMPClause *
11777Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11778 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11779 SourceLocation MapLoc, SourceLocation ColonLoc,
11780 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11781 SourceLocation LParenLoc, SourceLocation EndLoc) {
11782 MappableVarListInfo MVLI(VarList);
11783 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11784 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011785
Samuel Antao5de996e2016-01-22 20:21:36 +000011786 // We need to produce a map clause even if we don't have variables so that
11787 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011788 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11789 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11790 MVLI.VarComponents, MapTypeModifier, MapType,
11791 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011792}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011793
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011794QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11795 TypeResult ParsedType) {
11796 assert(ParsedType.isUsable());
11797
11798 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11799 if (ReductionType.isNull())
11800 return QualType();
11801
11802 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11803 // A type name in a declare reduction directive cannot be a function type, an
11804 // array type, a reference type, or a type qualified with const, volatile or
11805 // restrict.
11806 if (ReductionType.hasQualifiers()) {
11807 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11808 return QualType();
11809 }
11810
11811 if (ReductionType->isFunctionType()) {
11812 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11813 return QualType();
11814 }
11815 if (ReductionType->isReferenceType()) {
11816 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11817 return QualType();
11818 }
11819 if (ReductionType->isArrayType()) {
11820 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11821 return QualType();
11822 }
11823 return ReductionType;
11824}
11825
11826Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11827 Scope *S, DeclContext *DC, DeclarationName Name,
11828 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11829 AccessSpecifier AS, Decl *PrevDeclInScope) {
11830 SmallVector<Decl *, 8> Decls;
11831 Decls.reserve(ReductionTypes.size());
11832
11833 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000011834 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011835 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11836 // A reduction-identifier may not be re-declared in the current scope for the
11837 // same type or for a type that is compatible according to the base language
11838 // rules.
11839 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11840 OMPDeclareReductionDecl *PrevDRD = nullptr;
11841 bool InCompoundScope = true;
11842 if (S != nullptr) {
11843 // Find previous declaration with the same name not referenced in other
11844 // declarations.
11845 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11846 InCompoundScope =
11847 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11848 LookupName(Lookup, S);
11849 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11850 /*AllowInlineNamespace=*/false);
11851 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11852 auto Filter = Lookup.makeFilter();
11853 while (Filter.hasNext()) {
11854 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11855 if (InCompoundScope) {
11856 auto I = UsedAsPrevious.find(PrevDecl);
11857 if (I == UsedAsPrevious.end())
11858 UsedAsPrevious[PrevDecl] = false;
11859 if (auto *D = PrevDecl->getPrevDeclInScope())
11860 UsedAsPrevious[D] = true;
11861 }
11862 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11863 PrevDecl->getLocation();
11864 }
11865 Filter.done();
11866 if (InCompoundScope) {
11867 for (auto &PrevData : UsedAsPrevious) {
11868 if (!PrevData.second) {
11869 PrevDRD = PrevData.first;
11870 break;
11871 }
11872 }
11873 }
11874 } else if (PrevDeclInScope != nullptr) {
11875 auto *PrevDRDInScope = PrevDRD =
11876 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11877 do {
11878 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11879 PrevDRDInScope->getLocation();
11880 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11881 } while (PrevDRDInScope != nullptr);
11882 }
11883 for (auto &TyData : ReductionTypes) {
11884 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11885 bool Invalid = false;
11886 if (I != PreviousRedeclTypes.end()) {
11887 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11888 << TyData.first;
11889 Diag(I->second, diag::note_previous_definition);
11890 Invalid = true;
11891 }
11892 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11893 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11894 Name, TyData.first, PrevDRD);
11895 DC->addDecl(DRD);
11896 DRD->setAccess(AS);
11897 Decls.push_back(DRD);
11898 if (Invalid)
11899 DRD->setInvalidDecl();
11900 else
11901 PrevDRD = DRD;
11902 }
11903
11904 return DeclGroupPtrTy::make(
11905 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11906}
11907
11908void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11909 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11910
11911 // Enter new function scope.
11912 PushFunctionScope();
11913 getCurFunction()->setHasBranchProtectedScope();
11914 getCurFunction()->setHasOMPDeclareReductionCombiner();
11915
11916 if (S != nullptr)
11917 PushDeclContext(S, DRD);
11918 else
11919 CurContext = DRD;
11920
Faisal Valid143a0c2017-04-01 21:30:49 +000011921 PushExpressionEvaluationContext(
11922 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011923
11924 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011925 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11926 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11927 // uses semantics of argument handles by value, but it should be passed by
11928 // reference. C lang does not support references, so pass all parameters as
11929 // pointers.
11930 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011931 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011932 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011933 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11934 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11935 // uses semantics of argument handles by value, but it should be passed by
11936 // reference. C lang does not support references, so pass all parameters as
11937 // pointers.
11938 // Create 'T omp_out;' variable.
11939 auto *OmpOutParm =
11940 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11941 if (S != nullptr) {
11942 PushOnScopeChains(OmpInParm, S);
11943 PushOnScopeChains(OmpOutParm, S);
11944 } else {
11945 DRD->addDecl(OmpInParm);
11946 DRD->addDecl(OmpOutParm);
11947 }
11948}
11949
11950void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11951 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11952 DiscardCleanupsInEvaluationContext();
11953 PopExpressionEvaluationContext();
11954
11955 PopDeclContext();
11956 PopFunctionScopeInfo();
11957
11958 if (Combiner != nullptr)
11959 DRD->setCombiner(Combiner);
11960 else
11961 DRD->setInvalidDecl();
11962}
11963
Alexey Bataev070f43a2017-09-06 14:49:58 +000011964VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011965 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11966
11967 // Enter new function scope.
11968 PushFunctionScope();
11969 getCurFunction()->setHasBranchProtectedScope();
11970
11971 if (S != nullptr)
11972 PushDeclContext(S, DRD);
11973 else
11974 CurContext = DRD;
11975
Faisal Valid143a0c2017-04-01 21:30:49 +000011976 PushExpressionEvaluationContext(
11977 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011978
11979 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011980 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11981 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11982 // uses semantics of argument handles by value, but it should be passed by
11983 // reference. C lang does not support references, so pass all parameters as
11984 // pointers.
11985 // Create 'T omp_priv;' variable.
11986 auto *OmpPrivParm =
11987 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011988 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11989 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11990 // uses semantics of argument handles by value, but it should be passed by
11991 // reference. C lang does not support references, so pass all parameters as
11992 // pointers.
11993 // Create 'T omp_orig;' variable.
11994 auto *OmpOrigParm =
11995 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011996 if (S != nullptr) {
11997 PushOnScopeChains(OmpPrivParm, S);
11998 PushOnScopeChains(OmpOrigParm, S);
11999 } else {
12000 DRD->addDecl(OmpPrivParm);
12001 DRD->addDecl(OmpOrigParm);
12002 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012003 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012004}
12005
Alexey Bataev070f43a2017-09-06 14:49:58 +000012006void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12007 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012008 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12009 DiscardCleanupsInEvaluationContext();
12010 PopExpressionEvaluationContext();
12011
12012 PopDeclContext();
12013 PopFunctionScopeInfo();
12014
Alexey Bataev070f43a2017-09-06 14:49:58 +000012015 if (Initializer != nullptr) {
12016 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12017 } else if (OmpPrivParm->hasInit()) {
12018 DRD->setInitializer(OmpPrivParm->getInit(),
12019 OmpPrivParm->isDirectInit()
12020 ? OMPDeclareReductionDecl::DirectInit
12021 : OMPDeclareReductionDecl::CopyInit);
12022 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012023 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012024 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012025}
12026
12027Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12028 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12029 for (auto *D : DeclReductions.get()) {
12030 if (IsValid) {
12031 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12032 if (S != nullptr)
12033 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12034 } else
12035 D->setInvalidDecl();
12036 }
12037 return DeclReductions;
12038}
12039
David Majnemer9d168222016-08-05 17:44:54 +000012040OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012041 SourceLocation StartLoc,
12042 SourceLocation LParenLoc,
12043 SourceLocation EndLoc) {
12044 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012045 Stmt *HelperValStmt = nullptr;
12046 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012047
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012048 // OpenMP [teams Constrcut, Restrictions]
12049 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012050 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12051 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012052 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012053
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012054 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12055 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12056 if (CaptureRegion != OMPD_unknown) {
12057 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12058 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12059 HelperValStmt = buildPreInits(Context, Captures);
12060 }
12061
12062 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12063 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012064}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012065
12066OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12067 SourceLocation StartLoc,
12068 SourceLocation LParenLoc,
12069 SourceLocation EndLoc) {
12070 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012071 Stmt *HelperValStmt = nullptr;
12072 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012073
12074 // OpenMP [teams Constrcut, Restrictions]
12075 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012076 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12077 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012078 return nullptr;
12079
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012080 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12081 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12082 if (CaptureRegion != OMPD_unknown) {
12083 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12084 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12085 HelperValStmt = buildPreInits(Context, Captures);
12086 }
12087
12088 return new (Context) OMPThreadLimitClause(
12089 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012090}
Alexey Bataeva0569352015-12-01 10:17:31 +000012091
12092OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12093 SourceLocation StartLoc,
12094 SourceLocation LParenLoc,
12095 SourceLocation EndLoc) {
12096 Expr *ValExpr = Priority;
12097
12098 // OpenMP [2.9.1, task Constrcut]
12099 // The priority-value is a non-negative numerical scalar expression.
12100 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12101 /*StrictlyPositive=*/false))
12102 return nullptr;
12103
12104 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12105}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012106
12107OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12108 SourceLocation StartLoc,
12109 SourceLocation LParenLoc,
12110 SourceLocation EndLoc) {
12111 Expr *ValExpr = Grainsize;
12112
12113 // OpenMP [2.9.2, taskloop Constrcut]
12114 // The parameter of the grainsize clause must be a positive integer
12115 // expression.
12116 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12117 /*StrictlyPositive=*/true))
12118 return nullptr;
12119
12120 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12121}
Alexey Bataev382967a2015-12-08 12:06:20 +000012122
12123OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12124 SourceLocation StartLoc,
12125 SourceLocation LParenLoc,
12126 SourceLocation EndLoc) {
12127 Expr *ValExpr = NumTasks;
12128
12129 // OpenMP [2.9.2, taskloop Constrcut]
12130 // The parameter of the num_tasks clause must be a positive integer
12131 // expression.
12132 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12133 /*StrictlyPositive=*/true))
12134 return nullptr;
12135
12136 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12137}
12138
Alexey Bataev28c75412015-12-15 08:19:24 +000012139OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12140 SourceLocation LParenLoc,
12141 SourceLocation EndLoc) {
12142 // OpenMP [2.13.2, critical construct, Description]
12143 // ... where hint-expression is an integer constant expression that evaluates
12144 // to a valid lock hint.
12145 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12146 if (HintExpr.isInvalid())
12147 return nullptr;
12148 return new (Context)
12149 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12150}
12151
Carlo Bertollib4adf552016-01-15 18:50:31 +000012152OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12153 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12154 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12155 SourceLocation EndLoc) {
12156 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12157 std::string Values;
12158 Values += "'";
12159 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12160 Values += "'";
12161 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12162 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12163 return nullptr;
12164 }
12165 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012166 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012167 if (ChunkSize) {
12168 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12169 !ChunkSize->isInstantiationDependent() &&
12170 !ChunkSize->containsUnexpandedParameterPack()) {
12171 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12172 ExprResult Val =
12173 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12174 if (Val.isInvalid())
12175 return nullptr;
12176
12177 ValExpr = Val.get();
12178
12179 // OpenMP [2.7.1, Restrictions]
12180 // chunk_size must be a loop invariant integer expression with a positive
12181 // value.
12182 llvm::APSInt Result;
12183 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12184 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12185 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12186 << "dist_schedule" << ChunkSize->getSourceRange();
12187 return nullptr;
12188 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012189 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
12190 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000012191 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12192 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12193 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012194 }
12195 }
12196 }
12197
12198 return new (Context)
12199 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012200 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012201}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012202
12203OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12204 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12205 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12206 SourceLocation KindLoc, SourceLocation EndLoc) {
12207 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012208 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012209 std::string Value;
12210 SourceLocation Loc;
12211 Value += "'";
12212 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12213 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012214 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012215 Loc = MLoc;
12216 } else {
12217 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012218 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012219 Loc = KindLoc;
12220 }
12221 Value += "'";
12222 Diag(Loc, diag::err_omp_unexpected_clause_value)
12223 << Value << getOpenMPClauseName(OMPC_defaultmap);
12224 return nullptr;
12225 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012226 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012227
12228 return new (Context)
12229 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12230}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012231
12232bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12233 DeclContext *CurLexicalContext = getCurLexicalContext();
12234 if (!CurLexicalContext->isFileContext() &&
12235 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012236 !CurLexicalContext->isExternCXXContext() &&
12237 !isa<CXXRecordDecl>(CurLexicalContext) &&
12238 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12239 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12240 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012241 Diag(Loc, diag::err_omp_region_not_file_context);
12242 return false;
12243 }
12244 if (IsInOpenMPDeclareTargetContext) {
12245 Diag(Loc, diag::err_omp_enclosed_declare_target);
12246 return false;
12247 }
12248
12249 IsInOpenMPDeclareTargetContext = true;
12250 return true;
12251}
12252
12253void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12254 assert(IsInOpenMPDeclareTargetContext &&
12255 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12256
12257 IsInOpenMPDeclareTargetContext = false;
12258}
12259
David Majnemer9d168222016-08-05 17:44:54 +000012260void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12261 CXXScopeSpec &ScopeSpec,
12262 const DeclarationNameInfo &Id,
12263 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12264 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012265 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12266 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12267
12268 if (Lookup.isAmbiguous())
12269 return;
12270 Lookup.suppressDiagnostics();
12271
12272 if (!Lookup.isSingleResult()) {
12273 if (TypoCorrection Corrected =
12274 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12275 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12276 CTK_ErrorRecovery)) {
12277 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12278 << Id.getName());
12279 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12280 return;
12281 }
12282
12283 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12284 return;
12285 }
12286
12287 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12288 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12289 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12290 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12291
12292 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12293 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12294 ND->addAttr(A);
12295 if (ASTMutationListener *ML = Context.getASTMutationListener())
12296 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12297 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12298 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12299 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12300 << Id.getName();
12301 }
12302 } else
12303 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12304}
12305
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012306static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12307 Sema &SemaRef, Decl *D) {
12308 if (!D)
12309 return;
12310 Decl *LD = nullptr;
12311 if (isa<TagDecl>(D)) {
12312 LD = cast<TagDecl>(D)->getDefinition();
12313 } else if (isa<VarDecl>(D)) {
12314 LD = cast<VarDecl>(D)->getDefinition();
12315
12316 // If this is an implicit variable that is legal and we do not need to do
12317 // anything.
12318 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012319 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12320 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12321 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012322 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012323 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012324 return;
12325 }
12326
12327 } else if (isa<FunctionDecl>(D)) {
12328 const FunctionDecl *FD = nullptr;
12329 if (cast<FunctionDecl>(D)->hasBody(FD))
12330 LD = const_cast<FunctionDecl *>(FD);
12331
12332 // If the definition is associated with the current declaration in the
12333 // target region (it can be e.g. a lambda) that is legal and we do not need
12334 // to do anything else.
12335 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012336 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12337 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12338 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012339 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012340 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012341 return;
12342 }
12343 }
12344 if (!LD)
12345 LD = D;
12346 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12347 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12348 // Outlined declaration is not declared target.
12349 if (LD->isOutOfLine()) {
12350 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12351 SemaRef.Diag(SL, diag::note_used_here) << SR;
12352 } else {
12353 DeclContext *DC = LD->getDeclContext();
12354 while (DC) {
12355 if (isa<FunctionDecl>(DC) &&
12356 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12357 break;
12358 DC = DC->getParent();
12359 }
12360 if (DC)
12361 return;
12362
12363 // Is not declared in target context.
12364 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12365 SemaRef.Diag(SL, diag::note_used_here) << SR;
12366 }
12367 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012368 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12369 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12370 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012371 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012372 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012373 }
12374}
12375
12376static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12377 Sema &SemaRef, DSAStackTy *Stack,
12378 ValueDecl *VD) {
12379 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12380 return true;
12381 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12382 return false;
12383 return true;
12384}
12385
12386void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12387 if (!D || D->isInvalidDecl())
12388 return;
12389 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12390 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12391 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12392 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12393 if (DSAStack->isThreadPrivate(VD)) {
12394 Diag(SL, diag::err_omp_threadprivate_in_target);
12395 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12396 return;
12397 }
12398 }
12399 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12400 // Problem if any with var declared with incomplete type will be reported
12401 // as normal, so no need to check it here.
12402 if ((E || !VD->getType()->isIncompleteType()) &&
12403 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12404 // Mark decl as declared target to prevent further diagnostic.
12405 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012406 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12407 Context, OMPDeclareTargetDeclAttr::MT_To);
12408 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012409 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012410 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012411 }
12412 return;
12413 }
12414 }
12415 if (!E) {
12416 // Checking declaration inside declare target region.
12417 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12418 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012419 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12420 Context, OMPDeclareTargetDeclAttr::MT_To);
12421 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012422 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012423 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012424 }
12425 return;
12426 }
12427 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12428}
Samuel Antao661c0902016-05-26 17:39:58 +000012429
12430OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12431 SourceLocation StartLoc,
12432 SourceLocation LParenLoc,
12433 SourceLocation EndLoc) {
12434 MappableVarListInfo MVLI(VarList);
12435 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12436 if (MVLI.ProcessedVarList.empty())
12437 return nullptr;
12438
12439 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12440 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12441 MVLI.VarComponents);
12442}
Samuel Antaoec172c62016-05-26 17:49:04 +000012443
12444OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12445 SourceLocation StartLoc,
12446 SourceLocation LParenLoc,
12447 SourceLocation EndLoc) {
12448 MappableVarListInfo MVLI(VarList);
12449 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12450 if (MVLI.ProcessedVarList.empty())
12451 return nullptr;
12452
12453 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12454 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12455 MVLI.VarComponents);
12456}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012457
12458OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12459 SourceLocation StartLoc,
12460 SourceLocation LParenLoc,
12461 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012462 MappableVarListInfo MVLI(VarList);
12463 SmallVector<Expr *, 8> PrivateCopies;
12464 SmallVector<Expr *, 8> Inits;
12465
Carlo Bertolli2404b172016-07-13 15:37:16 +000012466 for (auto &RefExpr : VarList) {
12467 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12468 SourceLocation ELoc;
12469 SourceRange ERange;
12470 Expr *SimpleRefExpr = RefExpr;
12471 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12472 if (Res.second) {
12473 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012474 MVLI.ProcessedVarList.push_back(RefExpr);
12475 PrivateCopies.push_back(nullptr);
12476 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012477 }
12478 ValueDecl *D = Res.first;
12479 if (!D)
12480 continue;
12481
12482 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012483 Type = Type.getNonReferenceType().getUnqualifiedType();
12484
12485 auto *VD = dyn_cast<VarDecl>(D);
12486
12487 // Item should be a pointer or reference to pointer.
12488 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012489 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12490 << 0 << RefExpr->getSourceRange();
12491 continue;
12492 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012493
12494 // Build the private variable and the expression that refers to it.
12495 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12496 D->hasAttrs() ? &D->getAttrs() : nullptr);
12497 if (VDPrivate->isInvalidDecl())
12498 continue;
12499
12500 CurContext->addDecl(VDPrivate);
12501 auto VDPrivateRefExpr = buildDeclRefExpr(
12502 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12503
12504 // Add temporary variable to initialize the private copy of the pointer.
12505 auto *VDInit =
12506 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12507 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12508 RefExpr->getExprLoc());
12509 AddInitializerToDecl(VDPrivate,
12510 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012511 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012512
12513 // If required, build a capture to implement the privatization initialized
12514 // with the current list item value.
12515 DeclRefExpr *Ref = nullptr;
12516 if (!VD)
12517 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12518 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12519 PrivateCopies.push_back(VDPrivateRefExpr);
12520 Inits.push_back(VDInitRefExpr);
12521
12522 // We need to add a data sharing attribute for this variable to make sure it
12523 // is correctly captured. A variable that shows up in a use_device_ptr has
12524 // similar properties of a first private variable.
12525 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12526
12527 // Create a mappable component for the list item. List items in this clause
12528 // only need a component.
12529 MVLI.VarBaseDeclarations.push_back(D);
12530 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12531 MVLI.VarComponents.back().push_back(
12532 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012533 }
12534
Samuel Antaocc10b852016-07-28 14:23:26 +000012535 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012536 return nullptr;
12537
Samuel Antaocc10b852016-07-28 14:23:26 +000012538 return OMPUseDevicePtrClause::Create(
12539 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12540 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012541}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012542
12543OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12544 SourceLocation StartLoc,
12545 SourceLocation LParenLoc,
12546 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012547 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012548 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012549 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012550 SourceLocation ELoc;
12551 SourceRange ERange;
12552 Expr *SimpleRefExpr = RefExpr;
12553 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12554 if (Res.second) {
12555 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012556 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012557 }
12558 ValueDecl *D = Res.first;
12559 if (!D)
12560 continue;
12561
12562 QualType Type = D->getType();
12563 // item should be a pointer or array or reference to pointer or array
12564 if (!Type.getNonReferenceType()->isPointerType() &&
12565 !Type.getNonReferenceType()->isArrayType()) {
12566 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12567 << 0 << RefExpr->getSourceRange();
12568 continue;
12569 }
Samuel Antao6890b092016-07-28 14:25:09 +000012570
12571 // Check if the declaration in the clause does not show up in any data
12572 // sharing attribute.
12573 auto DVar = DSAStack->getTopDSA(D, false);
12574 if (isOpenMPPrivate(DVar.CKind)) {
12575 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12576 << getOpenMPClauseName(DVar.CKind)
12577 << getOpenMPClauseName(OMPC_is_device_ptr)
12578 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12579 ReportOriginalDSA(*this, DSAStack, D, DVar);
12580 continue;
12581 }
12582
12583 Expr *ConflictExpr;
12584 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012585 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012586 [&ConflictExpr](
12587 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12588 OpenMPClauseKind) -> bool {
12589 ConflictExpr = R.front().getAssociatedExpression();
12590 return true;
12591 })) {
12592 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12593 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12594 << ConflictExpr->getSourceRange();
12595 continue;
12596 }
12597
12598 // Store the components in the stack so that they can be used to check
12599 // against other clauses later on.
12600 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12601 DSAStack->addMappableExpressionComponents(
12602 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12603
12604 // Record the expression we've just processed.
12605 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12606
12607 // Create a mappable component for the list item. List items in this clause
12608 // only need a component. We use a null declaration to signal fields in
12609 // 'this'.
12610 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12611 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12612 "Unexpected device pointer expression!");
12613 MVLI.VarBaseDeclarations.push_back(
12614 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12615 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12616 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012617 }
12618
Samuel Antao6890b092016-07-28 14:25:09 +000012619 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012620 return nullptr;
12621
Samuel Antao6890b092016-07-28 14:25:09 +000012622 return OMPIsDevicePtrClause::Create(
12623 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12624 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012625}