blob: 1c127c602f82d8ac0f6aa4a0c02a7864d3f6bfde [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
Alexey Bataev90c228f2016-02-08 09:29:13 +00001306VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001307 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001308 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001309
1310 // If we are attempting to capture a global variable in a directive with
1311 // 'target' we return true so that this global is also mapped to the device.
1312 //
1313 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1314 // then it should not be captured. Therefore, an extra check has to be
1315 // inserted here once support for 'declare target' is added.
1316 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001317 auto *VD = dyn_cast<VarDecl>(D);
1318 if (VD && !VD->hasLocalStorage()) {
Alexey Bataev61498fb2017-08-29 19:30:57 +00001319 if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001320 !DSAStack->isClauseParsingMode())
1321 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001322 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001323 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1324 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001325 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001326 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001327 false))
1328 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001329 }
1330
Alexey Bataev48977c32015-08-04 08:10:48 +00001331 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1332 (!DSAStack->isClauseParsingMode() ||
1333 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001334 auto &&Info = DSAStack->isLoopControlVariable(D);
1335 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001336 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001337 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001338 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001339 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001340 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001341 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001342 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001343 DVarPrivate = DSAStack->hasDSA(
1344 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1345 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001346 if (DVarPrivate.CKind != OMPC_unknown)
1347 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001348 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001349 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001350}
1351
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001352bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001353 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1354 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001355 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1356 Level) ||
1357 // Consider taskgroup reduction descriptor variable a private to avoid
1358 // possible capture in the region.
1359 (DSAStack->hasExplicitDirective(
1360 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1361 Level) &&
1362 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001363}
1364
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001365void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1366 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1367 D = getCanonicalDecl(D);
1368 OpenMPClauseKind OMPC = OMPC_unknown;
1369 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1370 const unsigned NewLevel = I - 1;
1371 if (DSAStack->hasExplicitDSA(D,
1372 [&OMPC](const OpenMPClauseKind K) {
1373 if (isOpenMPPrivate(K)) {
1374 OMPC = K;
1375 return true;
1376 }
1377 return false;
1378 },
1379 NewLevel))
1380 break;
1381 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1382 D, NewLevel,
1383 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1384 OpenMPClauseKind) { return true; })) {
1385 OMPC = OMPC_map;
1386 break;
1387 }
1388 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1389 NewLevel)) {
1390 OMPC = OMPC_firstprivate;
1391 break;
1392 }
1393 }
1394 if (OMPC != OMPC_unknown)
1395 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1396}
1397
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001398bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001399 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1400 // Return true if the current level is no longer enclosed in a target region.
1401
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001402 auto *VD = dyn_cast<VarDecl>(D);
1403 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001404 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1405 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001406}
1407
Alexey Bataeved09d242014-05-28 05:53:51 +00001408void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001409
1410void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1411 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001412 Scope *CurScope, SourceLocation Loc) {
1413 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001414 PushExpressionEvaluationContext(
1415 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001416}
1417
Alexey Bataevaac108a2015-06-23 04:51:00 +00001418void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1419 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001420}
1421
Alexey Bataevaac108a2015-06-23 04:51:00 +00001422void Sema::EndOpenMPClause() {
1423 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001424}
1425
Alexey Bataev758e55e2013-09-06 18:03:48 +00001426void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001427 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1428 // A variable of class type (or array thereof) that appears in a lastprivate
1429 // clause requires an accessible, unambiguous default constructor for the
1430 // class type, unless the list item is also specified in a firstprivate
1431 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001432 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001433 for (auto *C : D->clauses()) {
1434 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1435 SmallVector<Expr *, 8> PrivateCopies;
1436 for (auto *DE : Clause->varlists()) {
1437 if (DE->isValueDependent() || DE->isTypeDependent()) {
1438 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001439 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001440 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001441 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001442 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1443 QualType Type = VD->getType().getNonReferenceType();
1444 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001445 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001446 // Generate helper private variable and initialize it with the
1447 // default value. The address of the original variable is replaced
1448 // by the address of the new private variable in CodeGen. This new
1449 // variable is not added to IdResolver, so the code in the OpenMP
1450 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001451 auto *VDPrivate = buildVarDecl(
1452 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001453 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001454 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001455 if (VDPrivate->isInvalidDecl())
1456 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001457 PrivateCopies.push_back(buildDeclRefExpr(
1458 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001459 } else {
1460 // The variable is also a firstprivate, so initialization sequence
1461 // for private copy is generated already.
1462 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001463 }
1464 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001465 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001466 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001467 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001468 }
1469 }
1470 }
1471
Alexey Bataev758e55e2013-09-06 18:03:48 +00001472 DSAStack->pop();
1473 DiscardCleanupsInEvaluationContext();
1474 PopExpressionEvaluationContext();
1475}
1476
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001477static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1478 Expr *NumIterations, Sema &SemaRef,
1479 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001480
Alexey Bataeva769e072013-03-22 06:34:35 +00001481namespace {
1482
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001483class VarDeclFilterCCC : public CorrectionCandidateCallback {
1484private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001485 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001486
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001487public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001488 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001489 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001490 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001491 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001492 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001493 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1494 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001495 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001496 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001497 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001498};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001499
1500class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1501private:
1502 Sema &SemaRef;
1503
1504public:
1505 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1506 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1507 NamedDecl *ND = Candidate.getCorrectionDecl();
1508 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1509 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1510 SemaRef.getCurScope());
1511 }
1512 return false;
1513 }
1514};
1515
Alexey Bataeved09d242014-05-28 05:53:51 +00001516} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001517
1518ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1519 CXXScopeSpec &ScopeSpec,
1520 const DeclarationNameInfo &Id) {
1521 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1522 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1523
1524 if (Lookup.isAmbiguous())
1525 return ExprError();
1526
1527 VarDecl *VD;
1528 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001529 if (TypoCorrection Corrected = CorrectTypo(
1530 Id, LookupOrdinaryName, CurScope, nullptr,
1531 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001532 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001533 PDiag(Lookup.empty()
1534 ? diag::err_undeclared_var_use_suggest
1535 : diag::err_omp_expected_var_arg_suggest)
1536 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001537 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001538 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001539 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1540 : diag::err_omp_expected_var_arg)
1541 << Id.getName();
1542 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001543 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001544 } else {
1545 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001546 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001547 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1548 return ExprError();
1549 }
1550 }
1551 Lookup.suppressDiagnostics();
1552
1553 // OpenMP [2.9.2, Syntax, C/C++]
1554 // Variables must be file-scope, namespace-scope, or static block-scope.
1555 if (!VD->hasGlobalStorage()) {
1556 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001557 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1558 bool IsDecl =
1559 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001560 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001561 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1562 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001563 return ExprError();
1564 }
1565
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001566 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1567 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001568 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1569 // A threadprivate directive for file-scope variables must appear outside
1570 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001571 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1572 !getCurLexicalContext()->isTranslationUnit()) {
1573 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001574 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1575 bool IsDecl =
1576 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1577 Diag(VD->getLocation(),
1578 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1579 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001580 return ExprError();
1581 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001582 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1583 // A threadprivate directive for static class member variables must appear
1584 // in the class definition, in the same scope in which the member
1585 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001586 if (CanonicalVD->isStaticDataMember() &&
1587 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1588 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001589 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1590 bool IsDecl =
1591 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1592 Diag(VD->getLocation(),
1593 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1594 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001595 return ExprError();
1596 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001597 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1598 // A threadprivate directive for namespace-scope variables must appear
1599 // outside any definition or declaration other than the namespace
1600 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001601 if (CanonicalVD->getDeclContext()->isNamespace() &&
1602 (!getCurLexicalContext()->isFileContext() ||
1603 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1604 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001605 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1606 bool IsDecl =
1607 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1608 Diag(VD->getLocation(),
1609 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1610 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001611 return ExprError();
1612 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001613 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1614 // A threadprivate directive for static block-scope variables must appear
1615 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001616 if (CanonicalVD->isStaticLocal() && CurScope &&
1617 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001618 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001619 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1620 bool IsDecl =
1621 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1622 Diag(VD->getLocation(),
1623 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1624 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001625 return ExprError();
1626 }
1627
1628 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1629 // A threadprivate directive must lexically precede all references to any
1630 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001631 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001632 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001633 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001634 return ExprError();
1635 }
1636
1637 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001638 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1639 SourceLocation(), VD,
1640 /*RefersToEnclosingVariableOrCapture=*/false,
1641 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001642}
1643
Alexey Bataeved09d242014-05-28 05:53:51 +00001644Sema::DeclGroupPtrTy
1645Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1646 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001647 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001648 CurContext->addDecl(D);
1649 return DeclGroupPtrTy::make(DeclGroupRef(D));
1650 }
David Blaikie0403cb12016-01-15 23:43:25 +00001651 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001652}
1653
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001654namespace {
1655class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1656 Sema &SemaRef;
1657
1658public:
1659 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001660 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001661 if (VD->hasLocalStorage()) {
1662 SemaRef.Diag(E->getLocStart(),
1663 diag::err_omp_local_var_in_threadprivate_init)
1664 << E->getSourceRange();
1665 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1666 << VD << VD->getSourceRange();
1667 return true;
1668 }
1669 }
1670 return false;
1671 }
1672 bool VisitStmt(const Stmt *S) {
1673 for (auto Child : S->children()) {
1674 if (Child && Visit(Child))
1675 return true;
1676 }
1677 return false;
1678 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001679 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001680};
1681} // namespace
1682
Alexey Bataeved09d242014-05-28 05:53:51 +00001683OMPThreadPrivateDecl *
1684Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001685 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001686 for (auto &RefExpr : VarList) {
1687 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001688 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1689 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001690
Alexey Bataev376b4a42016-02-09 09:41:09 +00001691 // Mark variable as used.
1692 VD->setReferenced();
1693 VD->markUsed(Context);
1694
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001695 QualType QType = VD->getType();
1696 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1697 // It will be analyzed later.
1698 Vars.push_back(DE);
1699 continue;
1700 }
1701
Alexey Bataeva769e072013-03-22 06:34:35 +00001702 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1703 // A threadprivate variable must not have an incomplete type.
1704 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001705 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001706 continue;
1707 }
1708
1709 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1710 // A threadprivate variable must not have a reference type.
1711 if (VD->getType()->isReferenceType()) {
1712 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001713 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1714 bool IsDecl =
1715 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1716 Diag(VD->getLocation(),
1717 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1718 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001719 continue;
1720 }
1721
Samuel Antaof8b50122015-07-13 22:54:53 +00001722 // Check if this is a TLS variable. If TLS is not being supported, produce
1723 // the corresponding diagnostic.
1724 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1725 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1726 getLangOpts().OpenMPUseTLS &&
1727 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001728 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1729 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001730 Diag(ILoc, diag::err_omp_var_thread_local)
1731 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001732 bool IsDecl =
1733 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1734 Diag(VD->getLocation(),
1735 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1736 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001737 continue;
1738 }
1739
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001740 // Check if initial value of threadprivate variable reference variable with
1741 // local storage (it is not supported by runtime).
1742 if (auto Init = VD->getAnyInitializer()) {
1743 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001744 if (Checker.Visit(Init))
1745 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001746 }
1747
Alexey Bataeved09d242014-05-28 05:53:51 +00001748 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001749 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001750 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1751 Context, SourceRange(Loc, Loc)));
1752 if (auto *ML = Context.getASTMutationListener())
1753 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001754 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001755 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001756 if (!Vars.empty()) {
1757 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1758 Vars);
1759 D->setAccess(AS_public);
1760 }
1761 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001762}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001763
Alexey Bataev7ff55242014-06-19 09:13:45 +00001764static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001765 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001766 bool IsLoopIterVar = false) {
1767 if (DVar.RefExpr) {
1768 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1769 << getOpenMPClauseName(DVar.CKind);
1770 return;
1771 }
1772 enum {
1773 PDSA_StaticMemberShared,
1774 PDSA_StaticLocalVarShared,
1775 PDSA_LoopIterVarPrivate,
1776 PDSA_LoopIterVarLinear,
1777 PDSA_LoopIterVarLastprivate,
1778 PDSA_ConstVarShared,
1779 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001780 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001781 PDSA_LocalVarPrivate,
1782 PDSA_Implicit
1783 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001784 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001785 auto ReportLoc = D->getLocation();
1786 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001787 if (IsLoopIterVar) {
1788 if (DVar.CKind == OMPC_private)
1789 Reason = PDSA_LoopIterVarPrivate;
1790 else if (DVar.CKind == OMPC_lastprivate)
1791 Reason = PDSA_LoopIterVarLastprivate;
1792 else
1793 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001794 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1795 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001796 Reason = PDSA_TaskVarFirstprivate;
1797 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001798 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001799 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001800 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001801 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001802 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001803 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001804 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001805 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001806 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001807 ReportHint = true;
1808 Reason = PDSA_LocalVarPrivate;
1809 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001810 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001811 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001812 << Reason << ReportHint
1813 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1814 } else if (DVar.ImplicitDSALoc.isValid()) {
1815 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1816 << getOpenMPClauseName(DVar.CKind);
1817 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001818}
1819
Alexey Bataev758e55e2013-09-06 18:03:48 +00001820namespace {
1821class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1822 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001823 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001824 bool ErrorFound;
1825 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001826 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001827 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001828 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001829 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001830
Alexey Bataev758e55e2013-09-06 18:03:48 +00001831public:
1832 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001833 if (E->isTypeDependent() || E->isValueDependent() ||
1834 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1835 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001836 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001837 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001838 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001839 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001840 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001841
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001842 auto DVar = Stack->getTopDSA(VD, false);
1843 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001844 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001845 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001846
Alexey Bataevafe50572017-10-06 17:00:28 +00001847 // Skip internally declared static variables.
1848 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1849 return;
1850
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001851 auto ELoc = E->getExprLoc();
1852 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001853 // The default(none) clause requires that each variable that is referenced
1854 // in the construct, and does not have a predetermined data-sharing
1855 // attribute, must have its data-sharing attribute explicitly determined
1856 // by being listed in a data-sharing attribute clause.
1857 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001858 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001859 VarsWithInheritedDSA.count(VD) == 0) {
1860 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001861 return;
1862 }
1863
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001864 if (isOpenMPTargetExecutionDirective(DKind) &&
1865 !Stack->isLoopControlVariable(VD).first) {
1866 if (!Stack->checkMappableExprComponentListsForDecl(
1867 VD, /*CurrentRegionOnly=*/true,
1868 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1869 StackComponents,
1870 OpenMPClauseKind) {
1871 // Variable is used if it has been marked as an array, array
1872 // section or the variable iself.
1873 return StackComponents.size() == 1 ||
1874 std::all_of(
1875 std::next(StackComponents.rbegin()),
1876 StackComponents.rend(),
1877 [](const OMPClauseMappableExprCommon::
1878 MappableComponent &MC) {
1879 return MC.getAssociatedDeclaration() ==
1880 nullptr &&
1881 (isa<OMPArraySectionExpr>(
1882 MC.getAssociatedExpression()) ||
1883 isa<ArraySubscriptExpr>(
1884 MC.getAssociatedExpression()));
1885 });
1886 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001887 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001888 // By default lambdas are captured as firstprivates.
1889 if (const auto *RD =
1890 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001891 IsFirstprivate = RD->isLambda();
1892 IsFirstprivate =
1893 IsFirstprivate ||
1894 (VD->getType().getNonReferenceType()->isScalarType() &&
1895 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1896 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001897 ImplicitFirstprivate.emplace_back(E);
1898 else
1899 ImplicitMap.emplace_back(E);
1900 return;
1901 }
1902 }
1903
Alexey Bataev758e55e2013-09-06 18:03:48 +00001904 // OpenMP [2.9.3.6, Restrictions, p.2]
1905 // A list item that appears in a reduction clause of the innermost
1906 // enclosing worksharing or parallel construct may not be accessed in an
1907 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001908 DVar = Stack->hasInnermostDSA(
1909 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1910 [](OpenMPDirectiveKind K) -> bool {
1911 return isOpenMPParallelDirective(K) ||
1912 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1913 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001914 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001915 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001916 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001917 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1918 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001919 return;
1920 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001921
1922 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001923 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001924 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1925 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001926 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001927 }
1928 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001929 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001930 if (E->isTypeDependent() || E->isValueDependent() ||
1931 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1932 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001933 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1934 if (!FD)
1935 return;
1936 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001937 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001938 auto DVar = Stack->getTopDSA(FD, false);
1939 // Check if the variable has explicit DSA set and stop analysis if it
1940 // so.
1941 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1942 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001943
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001944 if (isOpenMPTargetExecutionDirective(DKind) &&
1945 !Stack->isLoopControlVariable(FD).first &&
1946 !Stack->checkMappableExprComponentListsForDecl(
1947 FD, /*CurrentRegionOnly=*/true,
1948 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1949 StackComponents,
1950 OpenMPClauseKind) {
1951 return isa<CXXThisExpr>(
1952 cast<MemberExpr>(
1953 StackComponents.back().getAssociatedExpression())
1954 ->getBase()
1955 ->IgnoreParens());
1956 })) {
1957 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1958 // A bit-field cannot appear in a map clause.
1959 //
1960 if (FD->isBitField()) {
1961 SemaRef.Diag(E->getMemberLoc(),
1962 diag::err_omp_bit_fields_forbidden_in_clause)
1963 << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001964 return;
1965 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001966 ImplicitMap.emplace_back(E);
1967 return;
1968 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001969
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001970 auto ELoc = E->getExprLoc();
1971 // OpenMP [2.9.3.6, Restrictions, p.2]
1972 // A list item that appears in a reduction clause of the innermost
1973 // enclosing worksharing or parallel construct may not be accessed in
1974 // an explicit task.
1975 DVar = Stack->hasInnermostDSA(
1976 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1977 [](OpenMPDirectiveKind K) -> bool {
1978 return isOpenMPParallelDirective(K) ||
1979 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1980 },
1981 /*FromParent=*/true);
1982 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1983 ErrorFound = true;
1984 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1985 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1986 return;
1987 }
1988
1989 // Define implicit data-sharing attributes for task.
1990 DVar = Stack->getImplicitDSA(FD, false);
1991 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1992 !Stack->isLoopControlVariable(FD).first)
1993 ImplicitFirstprivate.push_back(E);
1994 return;
1995 }
1996 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
1997 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
1998 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
1999 auto *VD = cast<ValueDecl>(
2000 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2001 if (!Stack->checkMappableExprComponentListsForDecl(
2002 VD, /*CurrentRegionOnly=*/true,
2003 [&CurComponents](
2004 OMPClauseMappableExprCommon::MappableExprComponentListRef
2005 StackComponents,
2006 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002007 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002008 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002009 for (const auto &SC : llvm::reverse(StackComponents)) {
2010 // Do both expressions have the same kind?
2011 if (CCI->getAssociatedExpression()->getStmtClass() !=
2012 SC.getAssociatedExpression()->getStmtClass())
2013 if (!(isa<OMPArraySectionExpr>(
2014 SC.getAssociatedExpression()) &&
2015 isa<ArraySubscriptExpr>(
2016 CCI->getAssociatedExpression())))
2017 return false;
2018
2019 Decl *CCD = CCI->getAssociatedDeclaration();
2020 Decl *SCD = SC.getAssociatedDeclaration();
2021 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2022 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2023 if (SCD != CCD)
2024 return false;
2025 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002026 if (CCI == CCE)
2027 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002028 }
2029 return true;
2030 })) {
2031 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002032 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002033 } else
2034 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002035 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002036 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002037 for (auto *C : S->clauses()) {
2038 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002039 // for task|target directives.
2040 // Skip analysis of arguments of implicitly defined map clause for target
2041 // directives.
2042 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2043 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002044 for (auto *CC : C->children()) {
2045 if (CC)
2046 Visit(CC);
2047 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002048 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002049 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002050 }
2051 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002052 for (auto *C : S->children()) {
2053 if (C && !isa<OMPExecutableDirective>(C))
2054 Visit(C);
2055 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002056 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002057
2058 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002059 ArrayRef<Expr *> getImplicitFirstprivate() const {
2060 return ImplicitFirstprivate;
2061 }
2062 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002063 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002064 return VarsWithInheritedDSA;
2065 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002066
Alexey Bataev7ff55242014-06-19 09:13:45 +00002067 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2068 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002069};
Alexey Bataeved09d242014-05-28 05:53:51 +00002070} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002071
Alexey Bataevbae9a792014-06-27 10:37:06 +00002072void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002073 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002074 case OMPD_parallel:
2075 case OMPD_parallel_for:
2076 case OMPD_parallel_for_simd:
2077 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002078 case OMPD_teams:
2079 case OMPD_teams_distribute: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002080 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002081 QualType KmpInt32PtrTy =
2082 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002083 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002084 std::make_pair(".global_tid.", KmpInt32PtrTy),
2085 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2086 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002087 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002088 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2089 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002090 break;
2091 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002092 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002093 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002094 case OMPD_target_parallel_for:
2095 case OMPD_target_parallel_for_simd: {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002096 Sema::CapturedParamNameType ParamsTarget[] = {
2097 std::make_pair(StringRef(), QualType()) // __context with shared vars
2098 };
2099 // Start a captured region for 'target' with no implicit parameters.
2100 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2101 ParamsTarget);
2102 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2103 QualType KmpInt32PtrTy =
2104 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002105 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002106 std::make_pair(".global_tid.", KmpInt32PtrTy),
2107 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2108 std::make_pair(StringRef(), QualType()) // __context with shared vars
2109 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002110 // Start a captured region for 'teams' or 'parallel'. Both regions have
2111 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002112 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002113 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002114 break;
2115 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002116 case OMPD_simd:
2117 case OMPD_for:
2118 case OMPD_for_simd:
2119 case OMPD_sections:
2120 case OMPD_section:
2121 case OMPD_single:
2122 case OMPD_master:
2123 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002124 case OMPD_taskgroup:
2125 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00002126 case OMPD_ordered:
2127 case OMPD_atomic:
2128 case OMPD_target_data:
2129 case OMPD_target:
Kelvin Li986330c2016-07-20 22:57:10 +00002130 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002131 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002132 std::make_pair(StringRef(), QualType()) // __context with shared vars
2133 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002134 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2135 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002136 break;
2137 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002138 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002139 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002140 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2141 FunctionProtoType::ExtProtoInfo EPI;
2142 EPI.Variadic = true;
2143 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002144 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002145 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002146 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2147 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2148 std::make_pair(".copy_fn.",
2149 Context.getPointerType(CopyFnType).withConst()),
2150 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002151 std::make_pair(StringRef(), QualType()) // __context with shared vars
2152 };
2153 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2154 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002155 // Mark this captured region as inlined, because we don't use outlined
2156 // function directly.
2157 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2158 AlwaysInlineAttr::CreateImplicit(
2159 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002160 break;
2161 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002162 case OMPD_taskloop:
2163 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002164 QualType KmpInt32Ty =
2165 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2166 QualType KmpUInt64Ty =
2167 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2168 QualType KmpInt64Ty =
2169 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2170 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2171 FunctionProtoType::ExtProtoInfo EPI;
2172 EPI.Variadic = true;
2173 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002174 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002175 std::make_pair(".global_tid.", KmpInt32Ty),
2176 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2177 std::make_pair(".privates.",
2178 Context.VoidPtrTy.withConst().withRestrict()),
2179 std::make_pair(
2180 ".copy_fn.",
2181 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2182 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2183 std::make_pair(".lb.", KmpUInt64Ty),
2184 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2185 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002186 std::make_pair(".reductions.",
2187 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002188 std::make_pair(StringRef(), QualType()) // __context with shared vars
2189 };
2190 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2191 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002192 // Mark this captured region as inlined, because we don't use outlined
2193 // function directly.
2194 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2195 AlwaysInlineAttr::CreateImplicit(
2196 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002197 break;
2198 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002199 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00002200 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00002201 case OMPD_distribute_parallel_for:
Kelvin Li579e41c2016-11-30 23:51:03 +00002202 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00002203 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00002204 case OMPD_teams_distribute_parallel_for:
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 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002223 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002224 case OMPD_taskyield:
2225 case OMPD_barrier:
2226 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002227 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002228 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002229 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00002230 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00002231 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002232 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002233 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002234 case OMPD_declare_target:
2235 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00002236 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00002237 llvm_unreachable("OpenMP Directive is not allowed");
2238 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002239 llvm_unreachable("Unknown OpenMP directive");
2240 }
2241}
2242
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002243int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2244 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2245 getOpenMPCaptureRegions(CaptureRegions, DKind);
2246 return CaptureRegions.size();
2247}
2248
Alexey Bataev3392d762016-02-16 11:18:12 +00002249static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002250 Expr *CaptureExpr, bool WithInit,
2251 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002252 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002253 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002254 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002255 QualType Ty = Init->getType();
2256 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2257 if (S.getLangOpts().CPlusPlus)
2258 Ty = C.getLValueReferenceType(Ty);
2259 else {
2260 Ty = C.getPointerType(Ty);
2261 ExprResult Res =
2262 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2263 if (!Res.isUsable())
2264 return nullptr;
2265 Init = Res.get();
2266 }
Alexey Bataev61205072016-03-02 04:57:40 +00002267 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002268 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002269 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2270 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002271 if (!WithInit)
2272 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002273 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002274 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002275 return CED;
2276}
2277
Alexey Bataev61205072016-03-02 04:57:40 +00002278static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2279 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002280 OMPCapturedExprDecl *CD;
2281 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2282 CD = cast<OMPCapturedExprDecl>(VD);
2283 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002284 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2285 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002286 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002287 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002288}
2289
Alexey Bataev5a3af132016-03-29 08:58:54 +00002290static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2291 if (!Ref) {
2292 auto *CD =
2293 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2294 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2295 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2296 CaptureExpr->getExprLoc());
2297 }
2298 ExprResult Res = Ref;
2299 if (!S.getLangOpts().CPlusPlus &&
2300 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2301 Ref->getType()->isPointerType())
2302 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2303 if (!Res.isUsable())
2304 return ExprError();
2305 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002306}
2307
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002308namespace {
2309// OpenMP directives parsed in this section are represented as a
2310// CapturedStatement with an associated statement. If a syntax error
2311// is detected during the parsing of the associated statement, the
2312// compiler must abort processing and close the CapturedStatement.
2313//
2314// Combined directives such as 'target parallel' have more than one
2315// nested CapturedStatements. This RAII ensures that we unwind out
2316// of all the nested CapturedStatements when an error is found.
2317class CaptureRegionUnwinderRAII {
2318private:
2319 Sema &S;
2320 bool &ErrorFound;
2321 OpenMPDirectiveKind DKind;
2322
2323public:
2324 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2325 OpenMPDirectiveKind DKind)
2326 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2327 ~CaptureRegionUnwinderRAII() {
2328 if (ErrorFound) {
2329 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2330 while (--ThisCaptureLevel >= 0)
2331 S.ActOnCapturedRegionError();
2332 }
2333 }
2334};
2335} // namespace
2336
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002337StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2338 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002339 bool ErrorFound = false;
2340 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2341 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002342 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002343 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002344 return StmtError();
2345 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002346
2347 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002348 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002349 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002350 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002351 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002352 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002353 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2354 Clause->getClauseKind() == OMPC_in_reduction) {
2355 // Capture taskgroup task_reduction descriptors inside the tasking regions
2356 // with the corresponding in_reduction items.
2357 auto *IRC = cast<OMPInReductionClause>(Clause);
2358 for (auto *E : IRC->taskgroup_descriptors())
2359 if (E)
2360 MarkDeclarationsReferencedInExpr(E);
2361 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002362 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002363 Clause->getClauseKind() == OMPC_copyprivate ||
2364 (getLangOpts().OpenMPUseTLS &&
2365 getASTContext().getTargetInfo().isTLSSupported() &&
2366 Clause->getClauseKind() == OMPC_copyin)) {
2367 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002368 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002369 for (auto *VarRef : Clause->children()) {
2370 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002371 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002372 }
2373 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002374 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002375 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002376 if (auto *C = OMPClauseWithPreInit::get(Clause))
2377 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002378 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2379 if (auto *E = C->getPostUpdateExpr())
2380 MarkDeclarationsReferencedInExpr(E);
2381 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002382 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002383 if (Clause->getClauseKind() == OMPC_schedule)
2384 SC = cast<OMPScheduleClause>(Clause);
2385 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002386 OC = cast<OMPOrderedClause>(Clause);
2387 else if (Clause->getClauseKind() == OMPC_linear)
2388 LCs.push_back(cast<OMPLinearClause>(Clause));
2389 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002390 // OpenMP, 2.7.1 Loop Construct, Restrictions
2391 // The nonmonotonic modifier cannot be specified if an ordered clause is
2392 // specified.
2393 if (SC &&
2394 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2395 SC->getSecondScheduleModifier() ==
2396 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2397 OC) {
2398 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2399 ? SC->getFirstScheduleModifierLoc()
2400 : SC->getSecondScheduleModifierLoc(),
2401 diag::err_omp_schedule_nonmonotonic_ordered)
2402 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2403 ErrorFound = true;
2404 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002405 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2406 for (auto *C : LCs) {
2407 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2408 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2409 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002410 ErrorFound = true;
2411 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002412 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2413 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2414 OC->getNumForLoops()) {
2415 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2416 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2417 ErrorFound = true;
2418 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002419 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002420 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002421 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002422 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002423 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2424 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2425 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2426 // Mark all variables in private list clauses as used in inner region.
2427 // Required for proper codegen of combined directives.
2428 // TODO: add processing for other clauses.
2429 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2430 for (auto *C : PICs) {
2431 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2432 // Find the particular capture region for the clause if the
2433 // directive is a combined one with multiple capture regions.
2434 // If the directive is not a combined one, the capture region
2435 // associated with the clause is OMPD_unknown and is generated
2436 // only once.
2437 if (CaptureRegion == ThisCaptureRegion ||
2438 CaptureRegion == OMPD_unknown) {
2439 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2440 for (auto *D : DS->decls())
2441 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2442 }
2443 }
2444 }
2445 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002446 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002447 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002448 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002449}
2450
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002451static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2452 OpenMPDirectiveKind CancelRegion,
2453 SourceLocation StartLoc) {
2454 // CancelRegion is only needed for cancel and cancellation_point.
2455 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2456 return false;
2457
2458 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2459 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2460 return false;
2461
2462 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2463 << getOpenMPDirectiveName(CancelRegion);
2464 return true;
2465}
2466
2467static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002468 OpenMPDirectiveKind CurrentRegion,
2469 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002470 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002471 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002472 if (Stack->getCurScope()) {
2473 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002474 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002475 bool NestingProhibited = false;
2476 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002477 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002478 enum {
2479 NoRecommend,
2480 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002481 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002482 ShouldBeInTargetRegion,
2483 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002484 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002485 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002486 // OpenMP [2.16, Nesting of Regions]
2487 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002488 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002489 // An ordered construct with the simd clause is the only OpenMP
2490 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002491 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002492 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2493 // message.
2494 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2495 ? diag::err_omp_prohibited_region_simd
2496 : diag::warn_omp_nesting_simd);
2497 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002498 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002499 if (ParentRegion == OMPD_atomic) {
2500 // OpenMP [2.16, Nesting of Regions]
2501 // OpenMP constructs may not be nested inside an atomic region.
2502 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2503 return true;
2504 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002505 if (CurrentRegion == OMPD_section) {
2506 // OpenMP [2.7.2, sections Construct, Restrictions]
2507 // Orphaned section directives are prohibited. That is, the section
2508 // directives must appear within the sections construct and must not be
2509 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002510 if (ParentRegion != OMPD_sections &&
2511 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002512 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2513 << (ParentRegion != OMPD_unknown)
2514 << getOpenMPDirectiveName(ParentRegion);
2515 return true;
2516 }
2517 return false;
2518 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002519 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002520 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002521 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002522 if (ParentRegion == OMPD_unknown &&
2523 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002524 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002525 if (CurrentRegion == OMPD_cancellation_point ||
2526 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002527 // OpenMP [2.16, Nesting of Regions]
2528 // A cancellation point construct for which construct-type-clause is
2529 // taskgroup must be nested inside a task construct. A cancellation
2530 // point construct for which construct-type-clause is not taskgroup must
2531 // be closely nested inside an OpenMP construct that matches the type
2532 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002533 // A cancel construct for which construct-type-clause is taskgroup must be
2534 // nested inside a task construct. A cancel construct for which
2535 // construct-type-clause is not taskgroup must be closely nested inside an
2536 // OpenMP construct that matches the type specified in
2537 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002538 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002539 !((CancelRegion == OMPD_parallel &&
2540 (ParentRegion == OMPD_parallel ||
2541 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002542 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002543 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2544 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002545 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2546 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002547 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2548 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002549 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002550 // OpenMP [2.16, Nesting of Regions]
2551 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002552 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002553 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002554 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002555 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2556 // OpenMP [2.16, Nesting of Regions]
2557 // A critical region may not be nested (closely or otherwise) inside a
2558 // critical region with the same name. Note that this restriction is not
2559 // sufficient to prevent deadlock.
2560 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002561 bool DeadLock = Stack->hasDirective(
2562 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2563 const DeclarationNameInfo &DNI,
2564 SourceLocation Loc) -> bool {
2565 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2566 PreviousCriticalLoc = Loc;
2567 return true;
2568 } else
2569 return false;
2570 },
2571 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002572 if (DeadLock) {
2573 SemaRef.Diag(StartLoc,
2574 diag::err_omp_prohibited_region_critical_same_name)
2575 << CurrentName.getName();
2576 if (PreviousCriticalLoc.isValid())
2577 SemaRef.Diag(PreviousCriticalLoc,
2578 diag::note_omp_previous_critical_region);
2579 return true;
2580 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002581 } else if (CurrentRegion == OMPD_barrier) {
2582 // OpenMP [2.16, Nesting of Regions]
2583 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002584 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002585 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2586 isOpenMPTaskingDirective(ParentRegion) ||
2587 ParentRegion == OMPD_master ||
2588 ParentRegion == OMPD_critical ||
2589 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002590 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002591 !isOpenMPParallelDirective(CurrentRegion) &&
2592 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002593 // OpenMP [2.16, Nesting of Regions]
2594 // A worksharing region may not be closely nested inside a worksharing,
2595 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002596 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2597 isOpenMPTaskingDirective(ParentRegion) ||
2598 ParentRegion == OMPD_master ||
2599 ParentRegion == OMPD_critical ||
2600 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002601 Recommend = ShouldBeInParallelRegion;
2602 } else if (CurrentRegion == OMPD_ordered) {
2603 // OpenMP [2.16, Nesting of Regions]
2604 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002605 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002606 // An ordered region must be closely nested inside a loop region (or
2607 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002608 // OpenMP [2.8.1,simd Construct, Restrictions]
2609 // An ordered construct with the simd clause is the only OpenMP construct
2610 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002611 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002612 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002613 !(isOpenMPSimdDirective(ParentRegion) ||
2614 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002615 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002616 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002617 // OpenMP [2.16, Nesting of Regions]
2618 // If specified, a teams construct must be contained within a target
2619 // construct.
2620 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002621 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002622 Recommend = ShouldBeInTargetRegion;
2623 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2624 }
Kelvin Libf594a52016-12-17 05:48:59 +00002625 if (!NestingProhibited &&
2626 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2627 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2628 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002629 // OpenMP [2.16, Nesting of Regions]
2630 // distribute, parallel, parallel sections, parallel workshare, and the
2631 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2632 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002633 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2634 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002635 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002636 }
David Majnemer9d168222016-08-05 17:44:54 +00002637 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002638 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002639 // OpenMP 4.5 [2.17 Nesting of Regions]
2640 // The region associated with the distribute construct must be strictly
2641 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002642 NestingProhibited =
2643 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002644 Recommend = ShouldBeInTeamsRegion;
2645 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002646 if (!NestingProhibited &&
2647 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2648 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2649 // OpenMP 4.5 [2.17 Nesting of Regions]
2650 // If a target, target update, target data, target enter data, or
2651 // target exit data construct is encountered during execution of a
2652 // target region, the behavior is unspecified.
2653 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002654 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2655 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002656 if (isOpenMPTargetExecutionDirective(K)) {
2657 OffendingRegion = K;
2658 return true;
2659 } else
2660 return false;
2661 },
2662 false /* don't skip top directive */);
2663 CloseNesting = false;
2664 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002665 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002666 if (OrphanSeen) {
2667 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2668 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2669 } else {
2670 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2671 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2672 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2673 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002674 return true;
2675 }
2676 }
2677 return false;
2678}
2679
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002680static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2681 ArrayRef<OMPClause *> Clauses,
2682 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2683 bool ErrorFound = false;
2684 unsigned NamedModifiersNumber = 0;
2685 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2686 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002687 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002688 for (const auto *C : Clauses) {
2689 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2690 // At most one if clause without a directive-name-modifier can appear on
2691 // the directive.
2692 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2693 if (FoundNameModifiers[CurNM]) {
2694 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2695 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2696 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2697 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002698 } else if (CurNM != OMPD_unknown) {
2699 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002700 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002701 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002702 FoundNameModifiers[CurNM] = IC;
2703 if (CurNM == OMPD_unknown)
2704 continue;
2705 // Check if the specified name modifier is allowed for the current
2706 // directive.
2707 // At most one if clause with the particular directive-name-modifier can
2708 // appear on the directive.
2709 bool MatchFound = false;
2710 for (auto NM : AllowedNameModifiers) {
2711 if (CurNM == NM) {
2712 MatchFound = true;
2713 break;
2714 }
2715 }
2716 if (!MatchFound) {
2717 S.Diag(IC->getNameModifierLoc(),
2718 diag::err_omp_wrong_if_directive_name_modifier)
2719 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2720 ErrorFound = true;
2721 }
2722 }
2723 }
2724 // If any if clause on the directive includes a directive-name-modifier then
2725 // all if clauses on the directive must include a directive-name-modifier.
2726 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2727 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2728 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2729 diag::err_omp_no_more_if_clause);
2730 } else {
2731 std::string Values;
2732 std::string Sep(", ");
2733 unsigned AllowedCnt = 0;
2734 unsigned TotalAllowedNum =
2735 AllowedNameModifiers.size() - NamedModifiersNumber;
2736 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2737 ++Cnt) {
2738 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2739 if (!FoundNameModifiers[NM]) {
2740 Values += "'";
2741 Values += getOpenMPDirectiveName(NM);
2742 Values += "'";
2743 if (AllowedCnt + 2 == TotalAllowedNum)
2744 Values += " or ";
2745 else if (AllowedCnt + 1 != TotalAllowedNum)
2746 Values += Sep;
2747 ++AllowedCnt;
2748 }
2749 }
2750 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2751 diag::err_omp_unnamed_if_clause)
2752 << (TotalAllowedNum > 1) << Values;
2753 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002754 for (auto Loc : NameModifierLoc) {
2755 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2756 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002757 ErrorFound = true;
2758 }
2759 return ErrorFound;
2760}
2761
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002762StmtResult Sema::ActOnOpenMPExecutableDirective(
2763 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2764 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2765 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002766 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002767 // First check CancelRegion which is then used in checkNestingOfRegions.
2768 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2769 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002770 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002771 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002772
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002773 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002774 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002775 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002776 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002777 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002778 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2779
2780 // Check default data sharing attributes for referenced variables.
2781 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002782 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2783 Stmt *S = AStmt;
2784 while (--ThisCaptureLevel >= 0)
2785 S = cast<CapturedStmt>(S)->getCapturedStmt();
2786 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002787 if (DSAChecker.isErrorFound())
2788 return StmtError();
2789 // Generate list of implicitly defined firstprivate variables.
2790 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002791
Alexey Bataev88202be2017-07-27 13:20:36 +00002792 SmallVector<Expr *, 4> ImplicitFirstprivates(
2793 DSAChecker.getImplicitFirstprivate().begin(),
2794 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002795 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2796 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002797 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2798 for (auto *C : Clauses) {
2799 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2800 for (auto *E : IRC->taskgroup_descriptors())
2801 if (E)
2802 ImplicitFirstprivates.emplace_back(E);
2803 }
2804 }
2805 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002806 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002807 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2808 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002809 ClausesWithImplicit.push_back(Implicit);
2810 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002811 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002812 } else
2813 ErrorFound = true;
2814 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002815 if (!ImplicitMaps.empty()) {
2816 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2817 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2818 SourceLocation(), SourceLocation(), ImplicitMaps,
2819 SourceLocation(), SourceLocation(), SourceLocation())) {
2820 ClausesWithImplicit.emplace_back(Implicit);
2821 ErrorFound |=
2822 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2823 } else
2824 ErrorFound = true;
2825 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002826 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002827
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002828 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002829 switch (Kind) {
2830 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002831 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2832 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002833 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002834 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002835 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002836 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2837 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002838 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002839 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002840 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2841 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002842 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002843 case OMPD_for_simd:
2844 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2845 EndLoc, VarsWithInheritedDSA);
2846 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002847 case OMPD_sections:
2848 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2849 EndLoc);
2850 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002851 case OMPD_section:
2852 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002853 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002854 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2855 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002856 case OMPD_single:
2857 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2858 EndLoc);
2859 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002860 case OMPD_master:
2861 assert(ClausesWithImplicit.empty() &&
2862 "No clauses are allowed for 'omp master' directive");
2863 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2864 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002865 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002866 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2867 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002868 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002869 case OMPD_parallel_for:
2870 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2871 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002872 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002873 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002874 case OMPD_parallel_for_simd:
2875 Res = ActOnOpenMPParallelForSimdDirective(
2876 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002877 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002878 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002879 case OMPD_parallel_sections:
2880 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2881 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002882 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002883 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002884 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002885 Res =
2886 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002887 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002888 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002889 case OMPD_taskyield:
2890 assert(ClausesWithImplicit.empty() &&
2891 "No clauses are allowed for 'omp taskyield' directive");
2892 assert(AStmt == nullptr &&
2893 "No associated statement allowed for 'omp taskyield' directive");
2894 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2895 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002896 case OMPD_barrier:
2897 assert(ClausesWithImplicit.empty() &&
2898 "No clauses are allowed for 'omp barrier' directive");
2899 assert(AStmt == nullptr &&
2900 "No associated statement allowed for 'omp barrier' directive");
2901 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2902 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002903 case OMPD_taskwait:
2904 assert(ClausesWithImplicit.empty() &&
2905 "No clauses are allowed for 'omp taskwait' directive");
2906 assert(AStmt == nullptr &&
2907 "No associated statement allowed for 'omp taskwait' directive");
2908 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2909 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002910 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002911 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2912 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002913 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002914 case OMPD_flush:
2915 assert(AStmt == nullptr &&
2916 "No associated statement allowed for 'omp flush' directive");
2917 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2918 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002919 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002920 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2921 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002922 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002923 case OMPD_atomic:
2924 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2925 EndLoc);
2926 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002927 case OMPD_teams:
2928 Res =
2929 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2930 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002931 case OMPD_target:
2932 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2933 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002934 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002935 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002936 case OMPD_target_parallel:
2937 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2938 StartLoc, EndLoc);
2939 AllowedNameModifiers.push_back(OMPD_target);
2940 AllowedNameModifiers.push_back(OMPD_parallel);
2941 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002942 case OMPD_target_parallel_for:
2943 Res = ActOnOpenMPTargetParallelForDirective(
2944 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2945 AllowedNameModifiers.push_back(OMPD_target);
2946 AllowedNameModifiers.push_back(OMPD_parallel);
2947 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002948 case OMPD_cancellation_point:
2949 assert(ClausesWithImplicit.empty() &&
2950 "No clauses are allowed for 'omp cancellation point' directive");
2951 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2952 "cancellation point' directive");
2953 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2954 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002955 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002956 assert(AStmt == nullptr &&
2957 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002958 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2959 CancelRegion);
2960 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002961 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002962 case OMPD_target_data:
2963 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2964 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002965 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002966 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002967 case OMPD_target_enter_data:
2968 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2969 EndLoc);
2970 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2971 break;
Samuel Antao72590762016-01-19 20:04:50 +00002972 case OMPD_target_exit_data:
2973 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2974 EndLoc);
2975 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2976 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002977 case OMPD_taskloop:
2978 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2979 EndLoc, VarsWithInheritedDSA);
2980 AllowedNameModifiers.push_back(OMPD_taskloop);
2981 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002982 case OMPD_taskloop_simd:
2983 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2984 EndLoc, VarsWithInheritedDSA);
2985 AllowedNameModifiers.push_back(OMPD_taskloop);
2986 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002987 case OMPD_distribute:
2988 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2989 EndLoc, VarsWithInheritedDSA);
2990 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002991 case OMPD_target_update:
2992 assert(!AStmt && "Statement is not allowed for target update");
2993 Res =
2994 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2995 AllowedNameModifiers.push_back(OMPD_target_update);
2996 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002997 case OMPD_distribute_parallel_for:
2998 Res = ActOnOpenMPDistributeParallelForDirective(
2999 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3000 AllowedNameModifiers.push_back(OMPD_parallel);
3001 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003002 case OMPD_distribute_parallel_for_simd:
3003 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3004 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3005 AllowedNameModifiers.push_back(OMPD_parallel);
3006 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003007 case OMPD_distribute_simd:
3008 Res = ActOnOpenMPDistributeSimdDirective(
3009 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3010 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003011 case OMPD_target_parallel_for_simd:
3012 Res = ActOnOpenMPTargetParallelForSimdDirective(
3013 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3014 AllowedNameModifiers.push_back(OMPD_target);
3015 AllowedNameModifiers.push_back(OMPD_parallel);
3016 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003017 case OMPD_target_simd:
3018 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3019 EndLoc, VarsWithInheritedDSA);
3020 AllowedNameModifiers.push_back(OMPD_target);
3021 break;
Kelvin Li02532872016-08-05 14:37:37 +00003022 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003023 Res = ActOnOpenMPTeamsDistributeDirective(
3024 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003025 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003026 case OMPD_teams_distribute_simd:
3027 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3028 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3029 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003030 case OMPD_teams_distribute_parallel_for_simd:
3031 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3032 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3033 AllowedNameModifiers.push_back(OMPD_parallel);
3034 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003035 case OMPD_teams_distribute_parallel_for:
3036 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3037 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3038 AllowedNameModifiers.push_back(OMPD_parallel);
3039 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003040 case OMPD_target_teams:
3041 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3042 EndLoc);
3043 AllowedNameModifiers.push_back(OMPD_target);
3044 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003045 case OMPD_target_teams_distribute:
3046 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3047 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3048 AllowedNameModifiers.push_back(OMPD_target);
3049 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003050 case OMPD_target_teams_distribute_parallel_for:
3051 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3052 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3053 AllowedNameModifiers.push_back(OMPD_target);
3054 AllowedNameModifiers.push_back(OMPD_parallel);
3055 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003056 case OMPD_target_teams_distribute_parallel_for_simd:
3057 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3058 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3059 AllowedNameModifiers.push_back(OMPD_target);
3060 AllowedNameModifiers.push_back(OMPD_parallel);
3061 break;
Kelvin Lida681182017-01-10 18:08:18 +00003062 case OMPD_target_teams_distribute_simd:
3063 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3064 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3065 AllowedNameModifiers.push_back(OMPD_target);
3066 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003067 case OMPD_declare_target:
3068 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003069 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003070 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003071 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003072 llvm_unreachable("OpenMP Directive is not allowed");
3073 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003074 llvm_unreachable("Unknown OpenMP directive");
3075 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003076
Alexey Bataev4acb8592014-07-07 13:01:15 +00003077 for (auto P : VarsWithInheritedDSA) {
3078 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3079 << P.first << P.second->getSourceRange();
3080 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003081 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3082
3083 if (!AllowedNameModifiers.empty())
3084 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3085 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003086
Alexey Bataeved09d242014-05-28 05:53:51 +00003087 if (ErrorFound)
3088 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003089 return Res;
3090}
3091
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003092Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3093 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003094 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003095 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3096 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003097 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003098 assert(Linears.size() == LinModifiers.size());
3099 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003100 if (!DG || DG.get().isNull())
3101 return DeclGroupPtrTy();
3102
3103 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003104 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003105 return DG;
3106 }
3107 auto *ADecl = DG.get().getSingleDecl();
3108 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3109 ADecl = FTD->getTemplatedDecl();
3110
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003111 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3112 if (!FD) {
3113 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003114 return DeclGroupPtrTy();
3115 }
3116
Alexey Bataev2af33e32016-04-07 12:45:37 +00003117 // OpenMP [2.8.2, declare simd construct, Description]
3118 // The parameter of the simdlen clause must be a constant positive integer
3119 // expression.
3120 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003121 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003122 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003123 // OpenMP [2.8.2, declare simd construct, Description]
3124 // The special this pointer can be used as if was one of the arguments to the
3125 // function in any of the linear, aligned, or uniform clauses.
3126 // The uniform clause declares one or more arguments to have an invariant
3127 // value for all concurrent invocations of the function in the execution of a
3128 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003129 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3130 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003131 for (auto *E : Uniforms) {
3132 E = E->IgnoreParenImpCasts();
3133 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3134 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3135 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3136 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003137 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3138 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003139 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003140 }
3141 if (isa<CXXThisExpr>(E)) {
3142 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003143 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003144 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003145 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3146 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003147 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003148 // OpenMP [2.8.2, declare simd construct, Description]
3149 // The aligned clause declares that the object to which each list item points
3150 // is aligned to the number of bytes expressed in the optional parameter of
3151 // the aligned clause.
3152 // The special this pointer can be used as if was one of the arguments to the
3153 // function in any of the linear, aligned, or uniform clauses.
3154 // The type of list items appearing in the aligned clause must be array,
3155 // pointer, reference to array, or reference to pointer.
3156 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3157 Expr *AlignedThis = nullptr;
3158 for (auto *E : Aligneds) {
3159 E = E->IgnoreParenImpCasts();
3160 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3161 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3162 auto *CanonPVD = PVD->getCanonicalDecl();
3163 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3164 FD->getParamDecl(PVD->getFunctionScopeIndex())
3165 ->getCanonicalDecl() == CanonPVD) {
3166 // OpenMP [2.8.1, simd construct, Restrictions]
3167 // A list-item cannot appear in more than one aligned clause.
3168 if (AlignedArgs.count(CanonPVD) > 0) {
3169 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3170 << 1 << E->getSourceRange();
3171 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3172 diag::note_omp_explicit_dsa)
3173 << getOpenMPClauseName(OMPC_aligned);
3174 continue;
3175 }
3176 AlignedArgs[CanonPVD] = E;
3177 QualType QTy = PVD->getType()
3178 .getNonReferenceType()
3179 .getUnqualifiedType()
3180 .getCanonicalType();
3181 const Type *Ty = QTy.getTypePtrOrNull();
3182 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3183 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3184 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3185 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3186 }
3187 continue;
3188 }
3189 }
3190 if (isa<CXXThisExpr>(E)) {
3191 if (AlignedThis) {
3192 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3193 << 2 << E->getSourceRange();
3194 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3195 << getOpenMPClauseName(OMPC_aligned);
3196 }
3197 AlignedThis = E;
3198 continue;
3199 }
3200 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3201 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3202 }
3203 // The optional parameter of the aligned clause, alignment, must be a constant
3204 // positive integer expression. If no optional parameter is specified,
3205 // implementation-defined default alignments for SIMD instructions on the
3206 // target platforms are assumed.
3207 SmallVector<Expr *, 4> NewAligns;
3208 for (auto *E : Alignments) {
3209 ExprResult Align;
3210 if (E)
3211 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3212 NewAligns.push_back(Align.get());
3213 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003214 // OpenMP [2.8.2, declare simd construct, Description]
3215 // The linear clause declares one or more list items to be private to a SIMD
3216 // lane and to have a linear relationship with respect to the iteration space
3217 // of a loop.
3218 // The special this pointer can be used as if was one of the arguments to the
3219 // function in any of the linear, aligned, or uniform clauses.
3220 // When a linear-step expression is specified in a linear clause it must be
3221 // either a constant integer expression or an integer-typed parameter that is
3222 // specified in a uniform clause on the directive.
3223 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3224 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3225 auto MI = LinModifiers.begin();
3226 for (auto *E : Linears) {
3227 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3228 ++MI;
3229 E = E->IgnoreParenImpCasts();
3230 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3231 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3232 auto *CanonPVD = PVD->getCanonicalDecl();
3233 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3234 FD->getParamDecl(PVD->getFunctionScopeIndex())
3235 ->getCanonicalDecl() == CanonPVD) {
3236 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3237 // A list-item cannot appear in more than one linear clause.
3238 if (LinearArgs.count(CanonPVD) > 0) {
3239 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3240 << getOpenMPClauseName(OMPC_linear)
3241 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3242 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3243 diag::note_omp_explicit_dsa)
3244 << getOpenMPClauseName(OMPC_linear);
3245 continue;
3246 }
3247 // Each argument can appear in at most one uniform or linear clause.
3248 if (UniformedArgs.count(CanonPVD) > 0) {
3249 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3250 << getOpenMPClauseName(OMPC_linear)
3251 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3252 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3253 diag::note_omp_explicit_dsa)
3254 << getOpenMPClauseName(OMPC_uniform);
3255 continue;
3256 }
3257 LinearArgs[CanonPVD] = E;
3258 if (E->isValueDependent() || E->isTypeDependent() ||
3259 E->isInstantiationDependent() ||
3260 E->containsUnexpandedParameterPack())
3261 continue;
3262 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3263 PVD->getOriginalType());
3264 continue;
3265 }
3266 }
3267 if (isa<CXXThisExpr>(E)) {
3268 if (UniformedLinearThis) {
3269 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3270 << getOpenMPClauseName(OMPC_linear)
3271 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3272 << E->getSourceRange();
3273 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3274 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3275 : OMPC_linear);
3276 continue;
3277 }
3278 UniformedLinearThis = E;
3279 if (E->isValueDependent() || E->isTypeDependent() ||
3280 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3281 continue;
3282 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3283 E->getType());
3284 continue;
3285 }
3286 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3287 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3288 }
3289 Expr *Step = nullptr;
3290 Expr *NewStep = nullptr;
3291 SmallVector<Expr *, 4> NewSteps;
3292 for (auto *E : Steps) {
3293 // Skip the same step expression, it was checked already.
3294 if (Step == E || !E) {
3295 NewSteps.push_back(E ? NewStep : nullptr);
3296 continue;
3297 }
3298 Step = E;
3299 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3300 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3301 auto *CanonPVD = PVD->getCanonicalDecl();
3302 if (UniformedArgs.count(CanonPVD) == 0) {
3303 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3304 << Step->getSourceRange();
3305 } else if (E->isValueDependent() || E->isTypeDependent() ||
3306 E->isInstantiationDependent() ||
3307 E->containsUnexpandedParameterPack() ||
3308 CanonPVD->getType()->hasIntegerRepresentation())
3309 NewSteps.push_back(Step);
3310 else {
3311 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3312 << Step->getSourceRange();
3313 }
3314 continue;
3315 }
3316 NewStep = Step;
3317 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3318 !Step->isInstantiationDependent() &&
3319 !Step->containsUnexpandedParameterPack()) {
3320 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3321 .get();
3322 if (NewStep)
3323 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3324 }
3325 NewSteps.push_back(NewStep);
3326 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003327 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3328 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003329 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003330 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3331 const_cast<Expr **>(Linears.data()), Linears.size(),
3332 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3333 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003334 ADecl->addAttr(NewAttr);
3335 return ConvertDeclToDeclGroup(ADecl);
3336}
3337
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003338StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3339 Stmt *AStmt,
3340 SourceLocation StartLoc,
3341 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003342 if (!AStmt)
3343 return StmtError();
3344
Alexey Bataev9959db52014-05-06 10:08:46 +00003345 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3346 // 1.2.2 OpenMP Language Terminology
3347 // Structured block - An executable statement with a single entry at the
3348 // top and a single exit at the bottom.
3349 // The point of exit cannot be a branch out of the structured block.
3350 // longjmp() and throw() must not violate the entry/exit criteria.
3351 CS->getCapturedDecl()->setNothrow();
3352
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003353 getCurFunction()->setHasBranchProtectedScope();
3354
Alexey Bataev25e5b442015-09-15 12:52:43 +00003355 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3356 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003357}
3358
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003359namespace {
3360/// \brief Helper class for checking canonical form of the OpenMP loops and
3361/// extracting iteration space of each loop in the loop nest, that will be used
3362/// for IR generation.
3363class OpenMPIterationSpaceChecker {
3364 /// \brief Reference to Sema.
3365 Sema &SemaRef;
3366 /// \brief A location for diagnostics (when there is no some better location).
3367 SourceLocation DefaultLoc;
3368 /// \brief A location for diagnostics (when increment is not compatible).
3369 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003370 /// \brief A source location for referring to loop init later.
3371 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003372 /// \brief A source location for referring to condition later.
3373 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003374 /// \brief A source location for referring to increment later.
3375 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003376 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003377 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003378 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003379 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003380 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003381 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003382 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003383 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003384 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003385 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003386 /// \brief This flag is true when condition is one of:
3387 /// Var < UB
3388 /// Var <= UB
3389 /// UB > Var
3390 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003391 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003392 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003393 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003394 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003395 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003396
3397public:
3398 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003399 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003400 /// \brief Check init-expr for canonical loop form and save loop counter
3401 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003402 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003403 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3404 /// for less/greater and for strict/non-strict comparison.
3405 bool CheckCond(Expr *S);
3406 /// \brief Check incr-expr for canonical loop form and return true if it
3407 /// does not conform, otherwise save loop step (#Step).
3408 bool CheckInc(Expr *S);
3409 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003410 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003411 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003412 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003413 /// \brief Source range of the loop init.
3414 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3415 /// \brief Source range of the loop condition.
3416 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3417 /// \brief Source range of the loop increment.
3418 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3419 /// \brief True if the step should be subtracted.
3420 bool ShouldSubtractStep() const { return SubtractStep; }
3421 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003422 Expr *
3423 BuildNumIterations(Scope *S, const bool LimitedType,
3424 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003425 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003426 Expr *BuildPreCond(Scope *S, Expr *Cond,
3427 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003428 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003429 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3430 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003431 /// \brief Build reference expression to the private counter be used for
3432 /// codegen.
3433 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003434 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003435 Expr *BuildCounterInit() const;
3436 /// \brief Build step of the counter be used for codegen.
3437 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003438 /// \brief Return true if any expression is dependent.
3439 bool Dependent() const;
3440
3441private:
3442 /// \brief Check the right-hand side of an assignment in the increment
3443 /// expression.
3444 bool CheckIncRHS(Expr *RHS);
3445 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003446 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003447 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003448 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003449 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003450 /// \brief Helper to set loop increment.
3451 bool SetStep(Expr *NewStep, bool Subtract);
3452};
3453
3454bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003455 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003456 assert(!LB && !UB && !Step);
3457 return false;
3458 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003459 return LCDecl->getType()->isDependentType() ||
3460 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3461 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003462}
3463
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003464bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3465 Expr *NewLCRefExpr,
3466 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003467 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003468 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003469 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003470 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003471 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003472 LCDecl = getCanonicalDecl(NewLCDecl);
3473 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003474 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3475 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003476 if ((Ctor->isCopyOrMoveConstructor() ||
3477 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3478 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003479 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003480 LB = NewLB;
3481 return false;
3482}
3483
3484bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003485 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003486 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003487 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3488 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003489 if (!NewUB)
3490 return true;
3491 UB = NewUB;
3492 TestIsLessOp = LessOp;
3493 TestIsStrictOp = StrictOp;
3494 ConditionSrcRange = SR;
3495 ConditionLoc = SL;
3496 return false;
3497}
3498
3499bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3500 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003501 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003502 if (!NewStep)
3503 return true;
3504 if (!NewStep->isValueDependent()) {
3505 // Check that the step is integer expression.
3506 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003507 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3508 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003509 if (Val.isInvalid())
3510 return true;
3511 NewStep = Val.get();
3512
3513 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3514 // If test-expr is of form var relational-op b and relational-op is < or
3515 // <= then incr-expr must cause var to increase on each iteration of the
3516 // loop. If test-expr is of form var relational-op b and relational-op is
3517 // > or >= then incr-expr must cause var to decrease on each iteration of
3518 // the loop.
3519 // If test-expr is of form b relational-op var and relational-op is < or
3520 // <= then incr-expr must cause var to decrease on each iteration of the
3521 // loop. If test-expr is of form b relational-op var and relational-op is
3522 // > or >= then incr-expr must cause var to increase on each iteration of
3523 // the loop.
3524 llvm::APSInt Result;
3525 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3526 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3527 bool IsConstNeg =
3528 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003529 bool IsConstPos =
3530 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003531 bool IsConstZero = IsConstant && !Result.getBoolValue();
3532 if (UB && (IsConstZero ||
3533 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003534 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003535 SemaRef.Diag(NewStep->getExprLoc(),
3536 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003537 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003538 SemaRef.Diag(ConditionLoc,
3539 diag::note_omp_loop_cond_requres_compatible_incr)
3540 << TestIsLessOp << ConditionSrcRange;
3541 return true;
3542 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003543 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003544 NewStep =
3545 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3546 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003547 Subtract = !Subtract;
3548 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003549 }
3550
3551 Step = NewStep;
3552 SubtractStep = Subtract;
3553 return false;
3554}
3555
Alexey Bataev9c821032015-04-30 04:23:23 +00003556bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003557 // Check init-expr for canonical loop form and save loop counter
3558 // variable - #Var and its initialization value - #LB.
3559 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3560 // var = lb
3561 // integer-type var = lb
3562 // random-access-iterator-type var = lb
3563 // pointer-type var = lb
3564 //
3565 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003566 if (EmitDiags) {
3567 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3568 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003569 return true;
3570 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003571 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3572 if (!ExprTemp->cleanupsHaveSideEffects())
3573 S = ExprTemp->getSubExpr();
3574
Alexander Musmana5f070a2014-10-01 06:03:56 +00003575 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003576 if (Expr *E = dyn_cast<Expr>(S))
3577 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003578 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003579 if (BO->getOpcode() == BO_Assign) {
3580 auto *LHS = BO->getLHS()->IgnoreParens();
3581 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3582 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3583 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3584 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3585 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3586 }
3587 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3588 if (ME->isArrow() &&
3589 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3590 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3591 }
3592 }
David Majnemer9d168222016-08-05 17:44:54 +00003593 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003594 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003595 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003596 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003597 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003598 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003599 SemaRef.Diag(S->getLocStart(),
3600 diag::ext_omp_loop_not_canonical_init)
3601 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003602 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003603 }
3604 }
3605 }
David Majnemer9d168222016-08-05 17:44:54 +00003606 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003607 if (CE->getOperator() == OO_Equal) {
3608 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003609 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003610 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3611 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3612 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3613 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3614 }
3615 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3616 if (ME->isArrow() &&
3617 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3618 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3619 }
3620 }
3621 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003622
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003623 if (Dependent() || SemaRef.CurContext->isDependentContext())
3624 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003625 if (EmitDiags) {
3626 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3627 << S->getSourceRange();
3628 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003629 return true;
3630}
3631
Alexey Bataev23b69422014-06-18 07:08:49 +00003632/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003633/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003634static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003635 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003636 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003637 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003638 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3639 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003640 if ((Ctor->isCopyOrMoveConstructor() ||
3641 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3642 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003643 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003644 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003645 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003646 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003647 }
3648 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3649 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3650 return getCanonicalDecl(ME->getMemberDecl());
3651 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003652}
3653
3654bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3655 // Check test-expr for canonical form, save upper-bound UB, flags for
3656 // less/greater and for strict/non-strict comparison.
3657 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3658 // var relational-op b
3659 // b relational-op var
3660 //
3661 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003662 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003663 return true;
3664 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003665 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003666 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003667 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003668 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003669 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003670 return SetUB(BO->getRHS(),
3671 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3672 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3673 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003674 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003675 return SetUB(BO->getLHS(),
3676 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3677 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3678 BO->getSourceRange(), BO->getOperatorLoc());
3679 }
David Majnemer9d168222016-08-05 17:44:54 +00003680 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003681 if (CE->getNumArgs() == 2) {
3682 auto Op = CE->getOperator();
3683 switch (Op) {
3684 case OO_Greater:
3685 case OO_GreaterEqual:
3686 case OO_Less:
3687 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003688 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003689 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3690 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3691 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003692 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003693 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3694 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3695 CE->getOperatorLoc());
3696 break;
3697 default:
3698 break;
3699 }
3700 }
3701 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003702 if (Dependent() || SemaRef.CurContext->isDependentContext())
3703 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003704 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003705 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003706 return true;
3707}
3708
3709bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3710 // RHS of canonical loop form increment can be:
3711 // var + incr
3712 // incr + var
3713 // var - incr
3714 //
3715 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003716 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003717 if (BO->isAdditiveOp()) {
3718 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003719 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003720 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003721 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003722 return SetStep(BO->getLHS(), false);
3723 }
David Majnemer9d168222016-08-05 17:44:54 +00003724 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003725 bool IsAdd = CE->getOperator() == OO_Plus;
3726 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003727 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003728 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003729 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003730 return SetStep(CE->getArg(0), false);
3731 }
3732 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003733 if (Dependent() || SemaRef.CurContext->isDependentContext())
3734 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003735 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003736 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003737 return true;
3738}
3739
3740bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3741 // Check incr-expr for canonical loop form and return true if it
3742 // does not conform.
3743 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3744 // ++var
3745 // var++
3746 // --var
3747 // var--
3748 // var += incr
3749 // var -= incr
3750 // var = var + incr
3751 // var = incr + var
3752 // var = var - incr
3753 //
3754 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003755 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003756 return true;
3757 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003758 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3759 if (!ExprTemp->cleanupsHaveSideEffects())
3760 S = ExprTemp->getSubExpr();
3761
Alexander Musmana5f070a2014-10-01 06:03:56 +00003762 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003763 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003764 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003765 if (UO->isIncrementDecrementOp() &&
3766 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003767 return SetStep(SemaRef
3768 .ActOnIntegerConstant(UO->getLocStart(),
3769 (UO->isDecrementOp() ? -1 : 1))
3770 .get(),
3771 false);
3772 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003773 switch (BO->getOpcode()) {
3774 case BO_AddAssign:
3775 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003776 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003777 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3778 break;
3779 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003780 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003781 return CheckIncRHS(BO->getRHS());
3782 break;
3783 default:
3784 break;
3785 }
David Majnemer9d168222016-08-05 17:44:54 +00003786 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003787 switch (CE->getOperator()) {
3788 case OO_PlusPlus:
3789 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003790 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003791 return SetStep(SemaRef
3792 .ActOnIntegerConstant(
3793 CE->getLocStart(),
3794 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3795 .get(),
3796 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003797 break;
3798 case OO_PlusEqual:
3799 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003800 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003801 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3802 break;
3803 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003804 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003805 return CheckIncRHS(CE->getArg(1));
3806 break;
3807 default:
3808 break;
3809 }
3810 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003811 if (Dependent() || SemaRef.CurContext->isDependentContext())
3812 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003813 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003814 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003815 return true;
3816}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003817
Alexey Bataev5a3af132016-03-29 08:58:54 +00003818static ExprResult
3819tryBuildCapture(Sema &SemaRef, Expr *Capture,
3820 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003821 if (SemaRef.CurContext->isDependentContext())
3822 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003823 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3824 return SemaRef.PerformImplicitConversion(
3825 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3826 /*AllowExplicit=*/true);
3827 auto I = Captures.find(Capture);
3828 if (I != Captures.end())
3829 return buildCapture(SemaRef, Capture, I->second);
3830 DeclRefExpr *Ref = nullptr;
3831 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3832 Captures[Capture] = Ref;
3833 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003834}
3835
Alexander Musmana5f070a2014-10-01 06:03:56 +00003836/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003837Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3838 Scope *S, const bool LimitedType,
3839 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003840 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003841 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003842 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003843 SemaRef.getLangOpts().CPlusPlus) {
3844 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003845 auto *UBExpr = TestIsLessOp ? UB : LB;
3846 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003847 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3848 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003849 if (!Upper || !Lower)
3850 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003851
3852 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3853
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003854 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003855 // BuildBinOp already emitted error, this one is to point user to upper
3856 // and lower bound, and to tell what is passed to 'operator-'.
3857 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3858 << Upper->getSourceRange() << Lower->getSourceRange();
3859 return nullptr;
3860 }
3861 }
3862
3863 if (!Diff.isUsable())
3864 return nullptr;
3865
3866 // Upper - Lower [- 1]
3867 if (TestIsStrictOp)
3868 Diff = SemaRef.BuildBinOp(
3869 S, DefaultLoc, BO_Sub, Diff.get(),
3870 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3871 if (!Diff.isUsable())
3872 return nullptr;
3873
3874 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003875 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3876 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003877 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003878 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003879 if (!Diff.isUsable())
3880 return nullptr;
3881
3882 // Parentheses (for dumping/debugging purposes only).
3883 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3884 if (!Diff.isUsable())
3885 return nullptr;
3886
3887 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003888 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003889 if (!Diff.isUsable())
3890 return nullptr;
3891
Alexander Musman174b3ca2014-10-06 11:16:29 +00003892 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003893 QualType Type = Diff.get()->getType();
3894 auto &C = SemaRef.Context;
3895 bool UseVarType = VarType->hasIntegerRepresentation() &&
3896 C.getTypeSize(Type) > C.getTypeSize(VarType);
3897 if (!Type->isIntegerType() || UseVarType) {
3898 unsigned NewSize =
3899 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3900 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3901 : Type->hasSignedIntegerRepresentation();
3902 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003903 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3904 Diff = SemaRef.PerformImplicitConversion(
3905 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3906 if (!Diff.isUsable())
3907 return nullptr;
3908 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003909 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003910 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003911 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3912 if (NewSize != C.getTypeSize(Type)) {
3913 if (NewSize < C.getTypeSize(Type)) {
3914 assert(NewSize == 64 && "incorrect loop var size");
3915 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3916 << InitSrcRange << ConditionSrcRange;
3917 }
3918 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003919 NewSize, Type->hasSignedIntegerRepresentation() ||
3920 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003921 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3922 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3923 Sema::AA_Converting, true);
3924 if (!Diff.isUsable())
3925 return nullptr;
3926 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003927 }
3928 }
3929
Alexander Musmana5f070a2014-10-01 06:03:56 +00003930 return Diff.get();
3931}
3932
Alexey Bataev5a3af132016-03-29 08:58:54 +00003933Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3934 Scope *S, Expr *Cond,
3935 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003936 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3937 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3938 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003939
Alexey Bataev5a3af132016-03-29 08:58:54 +00003940 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3941 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3942 if (!NewLB.isUsable() || !NewUB.isUsable())
3943 return nullptr;
3944
Alexey Bataev62dbb972015-04-22 11:59:37 +00003945 auto CondExpr = SemaRef.BuildBinOp(
3946 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3947 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003948 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003949 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003950 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3951 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003952 CondExpr = SemaRef.PerformImplicitConversion(
3953 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3954 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003955 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003956 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3957 // Otherwise use original loop conditon and evaluate it in runtime.
3958 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3959}
3960
Alexander Musmana5f070a2014-10-01 06:03:56 +00003961/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003962DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003963 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003964 auto *VD = dyn_cast<VarDecl>(LCDecl);
3965 if (!VD) {
3966 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3967 auto *Ref = buildDeclRefExpr(
3968 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003969 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3970 // If the loop control decl is explicitly marked as private, do not mark it
3971 // as captured again.
3972 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3973 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003974 return Ref;
3975 }
3976 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003977 DefaultLoc);
3978}
3979
3980Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003981 if (LCDecl && !LCDecl->isInvalidDecl()) {
3982 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003983 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003984 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3985 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003986 if (PrivateVar->isInvalidDecl())
3987 return nullptr;
3988 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3989 }
3990 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003991}
3992
Samuel Antao4c8035b2016-12-12 18:00:20 +00003993/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003994Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3995
3996/// \brief Build step of the counter be used for codegen.
3997Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3998
3999/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004000struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004001 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004002 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004003 /// \brief This expression calculates the number of iterations in the loop.
4004 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004005 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004006 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004007 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004008 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004009 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004010 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004011 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004012 /// \brief This is step for the #CounterVar used to generate its update:
4013 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004014 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004015 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004016 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004017 /// \brief Source range of the loop init.
4018 SourceRange InitSrcRange;
4019 /// \brief Source range of the loop condition.
4020 SourceRange CondSrcRange;
4021 /// \brief Source range of the loop increment.
4022 SourceRange IncSrcRange;
4023};
4024
Alexey Bataev23b69422014-06-18 07:08:49 +00004025} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004026
Alexey Bataev9c821032015-04-30 04:23:23 +00004027void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4028 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4029 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004030 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4031 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004032 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4033 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004034 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4035 if (auto *D = ISC.GetLoopDecl()) {
4036 auto *VD = dyn_cast<VarDecl>(D);
4037 if (!VD) {
4038 if (auto *Private = IsOpenMPCapturedDecl(D))
4039 VD = Private;
4040 else {
4041 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4042 /*WithInit=*/false);
4043 VD = cast<VarDecl>(Ref->getDecl());
4044 }
4045 }
4046 DSAStack->addLoopControlVariable(D, VD);
4047 }
4048 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004049 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004050 }
4051}
4052
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004053/// \brief Called on a for stmt to check and extract its iteration space
4054/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004055static bool CheckOpenMPIterationSpace(
4056 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4057 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004058 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004059 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004060 LoopIterationSpace &ResultIterSpace,
4061 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004062 // OpenMP [2.6, Canonical Loop Form]
4063 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004064 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004065 if (!For) {
4066 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004067 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4068 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4069 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4070 if (NestedLoopCount > 1) {
4071 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4072 SemaRef.Diag(DSA.getConstructLoc(),
4073 diag::note_omp_collapse_ordered_expr)
4074 << 2 << CollapseLoopCountExpr->getSourceRange()
4075 << OrderedLoopCountExpr->getSourceRange();
4076 else if (CollapseLoopCountExpr)
4077 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4078 diag::note_omp_collapse_ordered_expr)
4079 << 0 << CollapseLoopCountExpr->getSourceRange();
4080 else
4081 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4082 diag::note_omp_collapse_ordered_expr)
4083 << 1 << OrderedLoopCountExpr->getSourceRange();
4084 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004085 return true;
4086 }
4087 assert(For->getBody());
4088
4089 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4090
4091 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004092 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004093 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004094 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004095
4096 bool HasErrors = false;
4097
4098 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004099 if (auto *LCDecl = ISC.GetLoopDecl()) {
4100 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004101
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004102 // OpenMP [2.6, Canonical Loop Form]
4103 // Var is one of the following:
4104 // A variable of signed or unsigned integer type.
4105 // For C++, a variable of a random access iterator type.
4106 // For C, a variable of a pointer type.
4107 auto VarType = LCDecl->getType().getNonReferenceType();
4108 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4109 !VarType->isPointerType() &&
4110 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4111 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4112 << SemaRef.getLangOpts().CPlusPlus;
4113 HasErrors = true;
4114 }
4115
4116 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4117 // a Construct
4118 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4119 // parallel for construct is (are) private.
4120 // The loop iteration variable in the associated for-loop of a simd
4121 // construct with just one associated for-loop is linear with a
4122 // constant-linear-step that is the increment of the associated for-loop.
4123 // Exclude loop var from the list of variables with implicitly defined data
4124 // sharing attributes.
4125 VarsWithImplicitDSA.erase(LCDecl);
4126
4127 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4128 // in a Construct, C/C++].
4129 // The loop iteration variable in the associated for-loop of a simd
4130 // construct with just one associated for-loop may be listed in a linear
4131 // clause with a constant-linear-step that is the increment of the
4132 // associated for-loop.
4133 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4134 // parallel for construct may be listed in a private or lastprivate clause.
4135 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4136 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4137 // declared in the loop and it is predetermined as a private.
4138 auto PredeterminedCKind =
4139 isOpenMPSimdDirective(DKind)
4140 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4141 : OMPC_private;
4142 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4143 DVar.CKind != PredeterminedCKind) ||
4144 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4145 isOpenMPDistributeDirective(DKind)) &&
4146 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4147 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4148 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4149 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4150 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4151 << getOpenMPClauseName(PredeterminedCKind);
4152 if (DVar.RefExpr == nullptr)
4153 DVar.CKind = PredeterminedCKind;
4154 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4155 HasErrors = true;
4156 } else if (LoopDeclRefExpr != nullptr) {
4157 // Make the loop iteration variable private (for worksharing constructs),
4158 // linear (for simd directives with the only one associated loop) or
4159 // lastprivate (for simd directives with several collapsed or ordered
4160 // loops).
4161 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004162 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4163 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004164 /*FromParent=*/false);
4165 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4166 }
4167
4168 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4169
4170 // Check test-expr.
4171 HasErrors |= ISC.CheckCond(For->getCond());
4172
4173 // Check incr-expr.
4174 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004175 }
4176
Alexander Musmana5f070a2014-10-01 06:03:56 +00004177 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004178 return HasErrors;
4179
Alexander Musmana5f070a2014-10-01 06:03:56 +00004180 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004181 ResultIterSpace.PreCond =
4182 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004183 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004184 DSA.getCurScope(),
4185 (isOpenMPWorksharingDirective(DKind) ||
4186 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4187 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004188 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004189 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004190 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4191 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4192 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4193 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4194 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4195 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4196
Alexey Bataev62dbb972015-04-22 11:59:37 +00004197 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4198 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004199 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004200 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004201 ResultIterSpace.CounterInit == nullptr ||
4202 ResultIterSpace.CounterStep == nullptr);
4203
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004204 return HasErrors;
4205}
4206
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004207/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004208static ExprResult
4209BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4210 ExprResult Start,
4211 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004212 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004213 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4214 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004215 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004216 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004217 VarRef.get()->getType())) {
4218 NewStart = SemaRef.PerformImplicitConversion(
4219 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4220 /*AllowExplicit=*/true);
4221 if (!NewStart.isUsable())
4222 return ExprError();
4223 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004224
4225 auto Init =
4226 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4227 return Init;
4228}
4229
Alexander Musmana5f070a2014-10-01 06:03:56 +00004230/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004231static ExprResult
4232BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4233 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4234 ExprResult Step, bool Subtract,
4235 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004236 // Add parentheses (for debugging purposes only).
4237 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4238 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4239 !Step.isUsable())
4240 return ExprError();
4241
Alexey Bataev5a3af132016-03-29 08:58:54 +00004242 ExprResult NewStep = Step;
4243 if (Captures)
4244 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004245 if (NewStep.isInvalid())
4246 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004247 ExprResult Update =
4248 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004249 if (!Update.isUsable())
4250 return ExprError();
4251
Alexey Bataevc0214e02016-02-16 12:13:49 +00004252 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4253 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004254 ExprResult NewStart = Start;
4255 if (Captures)
4256 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004257 if (NewStart.isInvalid())
4258 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004259
Alexey Bataevc0214e02016-02-16 12:13:49 +00004260 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4261 ExprResult SavedUpdate = Update;
4262 ExprResult UpdateVal;
4263 if (VarRef.get()->getType()->isOverloadableType() ||
4264 NewStart.get()->getType()->isOverloadableType() ||
4265 Update.get()->getType()->isOverloadableType()) {
4266 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4267 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4268 Update =
4269 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4270 if (Update.isUsable()) {
4271 UpdateVal =
4272 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4273 VarRef.get(), SavedUpdate.get());
4274 if (UpdateVal.isUsable()) {
4275 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4276 UpdateVal.get());
4277 }
4278 }
4279 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4280 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004281
Alexey Bataevc0214e02016-02-16 12:13:49 +00004282 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4283 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4284 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4285 NewStart.get(), SavedUpdate.get());
4286 if (!Update.isUsable())
4287 return ExprError();
4288
Alexey Bataev11481f52016-02-17 10:29:05 +00004289 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4290 VarRef.get()->getType())) {
4291 Update = SemaRef.PerformImplicitConversion(
4292 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4293 if (!Update.isUsable())
4294 return ExprError();
4295 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004296
4297 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4298 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004299 return Update;
4300}
4301
4302/// \brief Convert integer expression \a E to make it have at least \a Bits
4303/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004304static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004305 if (E == nullptr)
4306 return ExprError();
4307 auto &C = SemaRef.Context;
4308 QualType OldType = E->getType();
4309 unsigned HasBits = C.getTypeSize(OldType);
4310 if (HasBits >= Bits)
4311 return ExprResult(E);
4312 // OK to convert to signed, because new type has more bits than old.
4313 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4314 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4315 true);
4316}
4317
4318/// \brief Check if the given expression \a E is a constant integer that fits
4319/// into \a Bits bits.
4320static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4321 if (E == nullptr)
4322 return false;
4323 llvm::APSInt Result;
4324 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4325 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4326 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004327}
4328
Alexey Bataev5a3af132016-03-29 08:58:54 +00004329/// Build preinits statement for the given declarations.
4330static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004331 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004332 if (!PreInits.empty()) {
4333 return new (Context) DeclStmt(
4334 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4335 SourceLocation(), SourceLocation());
4336 }
4337 return nullptr;
4338}
4339
4340/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004341static Stmt *
4342buildPreInits(ASTContext &Context,
4343 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004344 if (!Captures.empty()) {
4345 SmallVector<Decl *, 16> PreInits;
4346 for (auto &Pair : Captures)
4347 PreInits.push_back(Pair.second->getDecl());
4348 return buildPreInits(Context, PreInits);
4349 }
4350 return nullptr;
4351}
4352
4353/// Build postupdate expression for the given list of postupdates expressions.
4354static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4355 Expr *PostUpdate = nullptr;
4356 if (!PostUpdates.empty()) {
4357 for (auto *E : PostUpdates) {
4358 Expr *ConvE = S.BuildCStyleCastExpr(
4359 E->getExprLoc(),
4360 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4361 E->getExprLoc(), E)
4362 .get();
4363 PostUpdate = PostUpdate
4364 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4365 PostUpdate, ConvE)
4366 .get()
4367 : ConvE;
4368 }
4369 }
4370 return PostUpdate;
4371}
4372
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004373/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004374/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4375/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004376static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004377CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4378 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4379 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004380 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004381 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004382 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004383 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004384 // Found 'collapse' clause - calculate collapse number.
4385 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004386 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004387 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004388 }
4389 if (OrderedLoopCountExpr) {
4390 // Found 'ordered' clause - calculate collapse number.
4391 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004392 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4393 if (Result.getLimitedValue() < NestedLoopCount) {
4394 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4395 diag::err_omp_wrong_ordered_loop_count)
4396 << OrderedLoopCountExpr->getSourceRange();
4397 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4398 diag::note_collapse_loop_count)
4399 << CollapseLoopCountExpr->getSourceRange();
4400 }
4401 NestedLoopCount = Result.getLimitedValue();
4402 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004403 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004404 // This is helper routine for loop directives (e.g., 'for', 'simd',
4405 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004406 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004407 SmallVector<LoopIterationSpace, 4> IterSpaces;
4408 IterSpaces.resize(NestedLoopCount);
4409 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004410 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004411 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004412 NestedLoopCount, CollapseLoopCountExpr,
4413 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004414 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004415 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004416 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004417 // OpenMP [2.8.1, simd construct, Restrictions]
4418 // All loops associated with the construct must be perfectly nested; that
4419 // is, there must be no intervening code nor any OpenMP directive between
4420 // any two loops.
4421 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004422 }
4423
Alexander Musmana5f070a2014-10-01 06:03:56 +00004424 Built.clear(/* size */ NestedLoopCount);
4425
4426 if (SemaRef.CurContext->isDependentContext())
4427 return NestedLoopCount;
4428
4429 // An example of what is generated for the following code:
4430 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004431 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004432 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004433 // for (k = 0; k < NK; ++k)
4434 // for (j = J0; j < NJ; j+=2) {
4435 // <loop body>
4436 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004437 //
4438 // We generate the code below.
4439 // Note: the loop body may be outlined in CodeGen.
4440 // Note: some counters may be C++ classes, operator- is used to find number of
4441 // iterations and operator+= to calculate counter value.
4442 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4443 // or i64 is currently supported).
4444 //
4445 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4446 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4447 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4448 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4449 // // similar updates for vars in clauses (e.g. 'linear')
4450 // <loop body (using local i and j)>
4451 // }
4452 // i = NI; // assign final values of counters
4453 // j = NJ;
4454 //
4455
4456 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4457 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004458 // Precondition tests if there is at least one iteration (all conditions are
4459 // true).
4460 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004461 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004462 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004463 32 /* Bits */, SemaRef
4464 .PerformImplicitConversion(
4465 N0->IgnoreImpCasts(), N0->getType(),
4466 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004467 .get(),
4468 SemaRef);
4469 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004470 64 /* Bits */, SemaRef
4471 .PerformImplicitConversion(
4472 N0->IgnoreImpCasts(), N0->getType(),
4473 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004474 .get(),
4475 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004476
4477 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4478 return NestedLoopCount;
4479
4480 auto &C = SemaRef.Context;
4481 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4482
4483 Scope *CurScope = DSA.getCurScope();
4484 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004485 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004486 PreCond =
4487 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4488 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004489 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004490 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004491 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004492 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4493 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004494 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004495 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004496 SemaRef
4497 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4498 Sema::AA_Converting,
4499 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004500 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004501 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004502 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004503 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004504 SemaRef
4505 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4506 Sema::AA_Converting,
4507 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004508 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004509 }
4510
4511 // Choose either the 32-bit or 64-bit version.
4512 ExprResult LastIteration = LastIteration64;
4513 if (LastIteration32.isUsable() &&
4514 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4515 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4516 FitsInto(
4517 32 /* Bits */,
4518 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4519 LastIteration64.get(), SemaRef)))
4520 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004521 QualType VType = LastIteration.get()->getType();
4522 QualType RealVType = VType;
4523 QualType StrideVType = VType;
4524 if (isOpenMPTaskLoopDirective(DKind)) {
4525 VType =
4526 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4527 StrideVType =
4528 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4529 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004530
4531 if (!LastIteration.isUsable())
4532 return 0;
4533
4534 // Save the number of iterations.
4535 ExprResult NumIterations = LastIteration;
4536 {
4537 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004538 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4539 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004540 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4541 if (!LastIteration.isUsable())
4542 return 0;
4543 }
4544
4545 // Calculate the last iteration number beforehand instead of doing this on
4546 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4547 llvm::APSInt Result;
4548 bool IsConstant =
4549 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4550 ExprResult CalcLastIteration;
4551 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004552 ExprResult SaveRef =
4553 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004554 LastIteration = SaveRef;
4555
4556 // Prepare SaveRef + 1.
4557 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004558 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004559 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4560 if (!NumIterations.isUsable())
4561 return 0;
4562 }
4563
4564 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4565
David Majnemer9d168222016-08-05 17:44:54 +00004566 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004567 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004568 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4569 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004570 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004571 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4572 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004573 SemaRef.AddInitializerToDecl(LBDecl,
4574 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4575 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004576
4577 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004578 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4579 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004580 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004581 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004582
4583 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4584 // This will be used to implement clause 'lastprivate'.
4585 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004586 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4587 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004588 SemaRef.AddInitializerToDecl(ILDecl,
4589 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4590 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004591
4592 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004593 VarDecl *STDecl =
4594 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4595 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004596 SemaRef.AddInitializerToDecl(STDecl,
4597 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4598 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004599
4600 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004601 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004602 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4603 UB.get(), LastIteration.get());
4604 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4605 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4606 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4607 CondOp.get());
4608 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004609
4610 // If we have a combined directive that combines 'distribute', 'for' or
4611 // 'simd' we need to be able to access the bounds of the schedule of the
4612 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4613 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4614 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004615
Carlo Bertolliffafe102017-04-20 00:39:39 +00004616 // Lower bound variable, initialized with zero.
4617 VarDecl *CombLBDecl =
4618 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4619 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4620 SemaRef.AddInitializerToDecl(
4621 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4622 /*DirectInit*/ false);
4623
4624 // Upper bound variable, initialized with last iteration number.
4625 VarDecl *CombUBDecl =
4626 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4627 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4628 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4629 /*DirectInit*/ false);
4630
4631 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4632 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4633 ExprResult CombCondOp =
4634 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4635 LastIteration.get(), CombUB.get());
4636 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4637 CombCondOp.get());
4638 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4639
4640 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004641 // We expect to have at least 2 more parameters than the 'parallel'
4642 // directive does - the lower and upper bounds of the previous schedule.
4643 assert(CD->getNumParams() >= 4 &&
4644 "Unexpected number of parameters in loop combined directive");
4645
4646 // Set the proper type for the bounds given what we learned from the
4647 // enclosed loops.
4648 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4649 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4650
4651 // Previous lower and upper bounds are obtained from the region
4652 // parameters.
4653 PrevLB =
4654 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4655 PrevUB =
4656 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4657 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004658 }
4659
4660 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004661 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004662 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004663 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004664 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4665 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004666 Expr *RHS =
4667 (isOpenMPWorksharingDirective(DKind) ||
4668 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4669 ? LB.get()
4670 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004671 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4672 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004673
4674 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4675 Expr *CombRHS =
4676 (isOpenMPWorksharingDirective(DKind) ||
4677 isOpenMPTaskLoopDirective(DKind) ||
4678 isOpenMPDistributeDirective(DKind))
4679 ? CombLB.get()
4680 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4681 CombInit =
4682 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4683 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4684 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004685 }
4686
Alexander Musmanc6388682014-12-15 07:07:06 +00004687 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004688 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004689 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004690 (isOpenMPWorksharingDirective(DKind) ||
4691 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004692 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4693 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4694 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004695 ExprResult CombCond;
4696 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4697 CombCond =
4698 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4699 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004700 // Loop increment (IV = IV + 1)
4701 SourceLocation IncLoc;
4702 ExprResult Inc =
4703 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4704 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4705 if (!Inc.isUsable())
4706 return 0;
4707 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004708 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4709 if (!Inc.isUsable())
4710 return 0;
4711
4712 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4713 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004714 // In combined construct, add combined version that use CombLB and CombUB
4715 // base variables for the update
4716 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004717 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4718 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004719 // LB + ST
4720 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4721 if (!NextLB.isUsable())
4722 return 0;
4723 // LB = LB + ST
4724 NextLB =
4725 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4726 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4727 if (!NextLB.isUsable())
4728 return 0;
4729 // UB + ST
4730 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4731 if (!NextUB.isUsable())
4732 return 0;
4733 // UB = UB + ST
4734 NextUB =
4735 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4736 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4737 if (!NextUB.isUsable())
4738 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004739 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4740 CombNextLB =
4741 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4742 if (!NextLB.isUsable())
4743 return 0;
4744 // LB = LB + ST
4745 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4746 CombNextLB.get());
4747 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4748 if (!CombNextLB.isUsable())
4749 return 0;
4750 // UB + ST
4751 CombNextUB =
4752 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4753 if (!CombNextUB.isUsable())
4754 return 0;
4755 // UB = UB + ST
4756 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4757 CombNextUB.get());
4758 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4759 if (!CombNextUB.isUsable())
4760 return 0;
4761 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004762 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004763
Carlo Bertolliffafe102017-04-20 00:39:39 +00004764 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004765 // directive with for as IV = IV + ST; ensure upper bound expression based
4766 // on PrevUB instead of NumIterations - used to implement 'for' when found
4767 // in combination with 'distribute', like in 'distribute parallel for'
4768 SourceLocation DistIncLoc;
4769 ExprResult DistCond, DistInc, PrevEUB;
4770 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4771 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4772 assert(DistCond.isUsable() && "distribute cond expr was not built");
4773
4774 DistInc =
4775 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4776 assert(DistInc.isUsable() && "distribute inc expr was not built");
4777 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4778 DistInc.get());
4779 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4780 assert(DistInc.isUsable() && "distribute inc expr was not built");
4781
4782 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4783 // construct
4784 SourceLocation DistEUBLoc;
4785 ExprResult IsUBGreater =
4786 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4787 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4788 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4789 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4790 CondOp.get());
4791 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4792 }
4793
Alexander Musmana5f070a2014-10-01 06:03:56 +00004794 // Build updates and final values of the loop counters.
4795 bool HasErrors = false;
4796 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004797 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004798 Built.Updates.resize(NestedLoopCount);
4799 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004800 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004801 {
4802 ExprResult Div;
4803 // Go from inner nested loop to outer.
4804 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4805 LoopIterationSpace &IS = IterSpaces[Cnt];
4806 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4807 // Build: Iter = (IV / Div) % IS.NumIters
4808 // where Div is product of previous iterations' IS.NumIters.
4809 ExprResult Iter;
4810 if (Div.isUsable()) {
4811 Iter =
4812 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4813 } else {
4814 Iter = IV;
4815 assert((Cnt == (int)NestedLoopCount - 1) &&
4816 "unusable div expected on first iteration only");
4817 }
4818
4819 if (Cnt != 0 && Iter.isUsable())
4820 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4821 IS.NumIterations);
4822 if (!Iter.isUsable()) {
4823 HasErrors = true;
4824 break;
4825 }
4826
Alexey Bataev39f915b82015-05-08 10:41:21 +00004827 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004828 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4829 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4830 IS.CounterVar->getExprLoc(),
4831 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004832 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004833 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004834 if (!Init.isUsable()) {
4835 HasErrors = true;
4836 break;
4837 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004838 ExprResult Update = BuildCounterUpdate(
4839 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4840 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004841 if (!Update.isUsable()) {
4842 HasErrors = true;
4843 break;
4844 }
4845
4846 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4847 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004848 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004849 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004850 if (!Final.isUsable()) {
4851 HasErrors = true;
4852 break;
4853 }
4854
4855 // Build Div for the next iteration: Div <- Div * IS.NumIters
4856 if (Cnt != 0) {
4857 if (Div.isUnset())
4858 Div = IS.NumIterations;
4859 else
4860 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4861 IS.NumIterations);
4862
4863 // Add parentheses (for debugging purposes only).
4864 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004865 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004866 if (!Div.isUsable()) {
4867 HasErrors = true;
4868 break;
4869 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004870 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004871 }
4872 if (!Update.isUsable() || !Final.isUsable()) {
4873 HasErrors = true;
4874 break;
4875 }
4876 // Save results
4877 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004878 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004879 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004880 Built.Updates[Cnt] = Update.get();
4881 Built.Finals[Cnt] = Final.get();
4882 }
4883 }
4884
4885 if (HasErrors)
4886 return 0;
4887
4888 // Save results
4889 Built.IterationVarRef = IV.get();
4890 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004891 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004892 Built.CalcLastIteration =
4893 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004894 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004895 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004896 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004897 Built.Init = Init.get();
4898 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004899 Built.LB = LB.get();
4900 Built.UB = UB.get();
4901 Built.IL = IL.get();
4902 Built.ST = ST.get();
4903 Built.EUB = EUB.get();
4904 Built.NLB = NextLB.get();
4905 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004906 Built.PrevLB = PrevLB.get();
4907 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004908 Built.DistInc = DistInc.get();
4909 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004910 Built.DistCombinedFields.LB = CombLB.get();
4911 Built.DistCombinedFields.UB = CombUB.get();
4912 Built.DistCombinedFields.EUB = CombEUB.get();
4913 Built.DistCombinedFields.Init = CombInit.get();
4914 Built.DistCombinedFields.Cond = CombCond.get();
4915 Built.DistCombinedFields.NLB = CombNextLB.get();
4916 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004917
Alexey Bataev8b427062016-05-25 12:36:08 +00004918 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4919 // Fill data for doacross depend clauses.
4920 for (auto Pair : DSA.getDoacrossDependClauses()) {
4921 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4922 Pair.first->setCounterValue(CounterVal);
4923 else {
4924 if (NestedLoopCount != Pair.second.size() ||
4925 NestedLoopCount != LoopMultipliers.size() + 1) {
4926 // Erroneous case - clause has some problems.
4927 Pair.first->setCounterValue(CounterVal);
4928 continue;
4929 }
4930 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4931 auto I = Pair.second.rbegin();
4932 auto IS = IterSpaces.rbegin();
4933 auto ILM = LoopMultipliers.rbegin();
4934 Expr *UpCounterVal = CounterVal;
4935 Expr *Multiplier = nullptr;
4936 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4937 if (I->first) {
4938 assert(IS->CounterStep);
4939 Expr *NormalizedOffset =
4940 SemaRef
4941 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4942 I->first, IS->CounterStep)
4943 .get();
4944 if (Multiplier) {
4945 NormalizedOffset =
4946 SemaRef
4947 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4948 NormalizedOffset, Multiplier)
4949 .get();
4950 }
4951 assert(I->second == OO_Plus || I->second == OO_Minus);
4952 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004953 UpCounterVal = SemaRef
4954 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4955 UpCounterVal, NormalizedOffset)
4956 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004957 }
4958 Multiplier = *ILM;
4959 ++I;
4960 ++IS;
4961 ++ILM;
4962 }
4963 Pair.first->setCounterValue(UpCounterVal);
4964 }
4965 }
4966
Alexey Bataevabfc0692014-06-25 06:52:00 +00004967 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004968}
4969
Alexey Bataev10e775f2015-07-30 11:36:16 +00004970static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004971 auto CollapseClauses =
4972 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4973 if (CollapseClauses.begin() != CollapseClauses.end())
4974 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004975 return nullptr;
4976}
4977
Alexey Bataev10e775f2015-07-30 11:36:16 +00004978static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004979 auto OrderedClauses =
4980 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4981 if (OrderedClauses.begin() != OrderedClauses.end())
4982 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004983 return nullptr;
4984}
4985
Kelvin Lic5609492016-07-15 04:39:07 +00004986static bool checkSimdlenSafelenSpecified(Sema &S,
4987 const ArrayRef<OMPClause *> Clauses) {
4988 OMPSafelenClause *Safelen = nullptr;
4989 OMPSimdlenClause *Simdlen = nullptr;
4990
4991 for (auto *Clause : Clauses) {
4992 if (Clause->getClauseKind() == OMPC_safelen)
4993 Safelen = cast<OMPSafelenClause>(Clause);
4994 else if (Clause->getClauseKind() == OMPC_simdlen)
4995 Simdlen = cast<OMPSimdlenClause>(Clause);
4996 if (Safelen && Simdlen)
4997 break;
4998 }
4999
5000 if (Simdlen && Safelen) {
5001 llvm::APSInt SimdlenRes, SafelenRes;
5002 auto SimdlenLength = Simdlen->getSimdlen();
5003 auto SafelenLength = Safelen->getSafelen();
5004 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5005 SimdlenLength->isInstantiationDependent() ||
5006 SimdlenLength->containsUnexpandedParameterPack())
5007 return false;
5008 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5009 SafelenLength->isInstantiationDependent() ||
5010 SafelenLength->containsUnexpandedParameterPack())
5011 return false;
5012 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5013 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5014 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5015 // If both simdlen and safelen clauses are specified, the value of the
5016 // simdlen parameter must be less than or equal to the value of the safelen
5017 // parameter.
5018 if (SimdlenRes > SafelenRes) {
5019 S.Diag(SimdlenLength->getExprLoc(),
5020 diag::err_omp_wrong_simdlen_safelen_values)
5021 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5022 return true;
5023 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005024 }
5025 return false;
5026}
5027
Alexey Bataev4acb8592014-07-07 13:01:15 +00005028StmtResult Sema::ActOnOpenMPSimdDirective(
5029 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5030 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005031 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005032 if (!AStmt)
5033 return StmtError();
5034
5035 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005036 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005037 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5038 // define the nested loops number.
5039 unsigned NestedLoopCount = CheckOpenMPLoop(
5040 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5041 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005042 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005043 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005044
Alexander Musmana5f070a2014-10-01 06:03:56 +00005045 assert((CurContext->isDependentContext() || B.builtAll()) &&
5046 "omp simd loop exprs were not built");
5047
Alexander Musman3276a272015-03-21 10:12:56 +00005048 if (!CurContext->isDependentContext()) {
5049 // Finalize the clauses that need pre-built expressions for CodeGen.
5050 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005051 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005052 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005053 B.NumIterations, *this, CurScope,
5054 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005055 return StmtError();
5056 }
5057 }
5058
Kelvin Lic5609492016-07-15 04:39:07 +00005059 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005060 return StmtError();
5061
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005062 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005063 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5064 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005065}
5066
Alexey Bataev4acb8592014-07-07 13:01:15 +00005067StmtResult Sema::ActOnOpenMPForDirective(
5068 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5069 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005070 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005071 if (!AStmt)
5072 return StmtError();
5073
5074 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005075 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005076 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5077 // define the nested loops number.
5078 unsigned NestedLoopCount = CheckOpenMPLoop(
5079 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5080 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005081 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005082 return StmtError();
5083
Alexander Musmana5f070a2014-10-01 06:03:56 +00005084 assert((CurContext->isDependentContext() || B.builtAll()) &&
5085 "omp for loop exprs were not built");
5086
Alexey Bataev54acd402015-08-04 11:18:19 +00005087 if (!CurContext->isDependentContext()) {
5088 // Finalize the clauses that need pre-built expressions for CodeGen.
5089 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005090 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005091 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005092 B.NumIterations, *this, CurScope,
5093 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005094 return StmtError();
5095 }
5096 }
5097
Alexey Bataevf29276e2014-06-18 04:14:57 +00005098 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005099 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005100 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005101}
5102
Alexander Musmanf82886e2014-09-18 05:12:34 +00005103StmtResult Sema::ActOnOpenMPForSimdDirective(
5104 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5105 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005106 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005107 if (!AStmt)
5108 return StmtError();
5109
5110 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005111 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005112 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5113 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005114 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005115 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5116 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5117 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005118 if (NestedLoopCount == 0)
5119 return StmtError();
5120
Alexander Musmanc6388682014-12-15 07:07:06 +00005121 assert((CurContext->isDependentContext() || B.builtAll()) &&
5122 "omp for simd loop exprs were not built");
5123
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005124 if (!CurContext->isDependentContext()) {
5125 // Finalize the clauses that need pre-built expressions for CodeGen.
5126 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005127 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005128 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005129 B.NumIterations, *this, CurScope,
5130 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005131 return StmtError();
5132 }
5133 }
5134
Kelvin Lic5609492016-07-15 04:39:07 +00005135 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005136 return StmtError();
5137
Alexander Musmanf82886e2014-09-18 05:12:34 +00005138 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005139 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5140 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005141}
5142
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005143StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5144 Stmt *AStmt,
5145 SourceLocation StartLoc,
5146 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005147 if (!AStmt)
5148 return StmtError();
5149
5150 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005151 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005152 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005153 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005154 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005155 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005156 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005157 return StmtError();
5158 // All associated statements must be '#pragma omp section' except for
5159 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005160 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005161 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5162 if (SectionStmt)
5163 Diag(SectionStmt->getLocStart(),
5164 diag::err_omp_sections_substmt_not_section);
5165 return StmtError();
5166 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005167 cast<OMPSectionDirective>(SectionStmt)
5168 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005169 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005170 } else {
5171 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5172 return StmtError();
5173 }
5174
5175 getCurFunction()->setHasBranchProtectedScope();
5176
Alexey Bataev25e5b442015-09-15 12:52:43 +00005177 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5178 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005179}
5180
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005181StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5182 SourceLocation StartLoc,
5183 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005184 if (!AStmt)
5185 return StmtError();
5186
5187 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005188
5189 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005190 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005191
Alexey Bataev25e5b442015-09-15 12:52:43 +00005192 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5193 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005194}
5195
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005196StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5197 Stmt *AStmt,
5198 SourceLocation StartLoc,
5199 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005200 if (!AStmt)
5201 return StmtError();
5202
5203 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005204
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005205 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005206
Alexey Bataev3255bf32015-01-19 05:20:46 +00005207 // OpenMP [2.7.3, single Construct, Restrictions]
5208 // The copyprivate clause must not be used with the nowait clause.
5209 OMPClause *Nowait = nullptr;
5210 OMPClause *Copyprivate = nullptr;
5211 for (auto *Clause : Clauses) {
5212 if (Clause->getClauseKind() == OMPC_nowait)
5213 Nowait = Clause;
5214 else if (Clause->getClauseKind() == OMPC_copyprivate)
5215 Copyprivate = Clause;
5216 if (Copyprivate && Nowait) {
5217 Diag(Copyprivate->getLocStart(),
5218 diag::err_omp_single_copyprivate_with_nowait);
5219 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5220 return StmtError();
5221 }
5222 }
5223
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005224 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5225}
5226
Alexander Musman80c22892014-07-17 08:54:58 +00005227StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5228 SourceLocation StartLoc,
5229 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005230 if (!AStmt)
5231 return StmtError();
5232
5233 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005234
5235 getCurFunction()->setHasBranchProtectedScope();
5236
5237 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5238}
5239
Alexey Bataev28c75412015-12-15 08:19:24 +00005240StmtResult Sema::ActOnOpenMPCriticalDirective(
5241 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5242 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005243 if (!AStmt)
5244 return StmtError();
5245
5246 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005247
Alexey Bataev28c75412015-12-15 08:19:24 +00005248 bool ErrorFound = false;
5249 llvm::APSInt Hint;
5250 SourceLocation HintLoc;
5251 bool DependentHint = false;
5252 for (auto *C : Clauses) {
5253 if (C->getClauseKind() == OMPC_hint) {
5254 if (!DirName.getName()) {
5255 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5256 ErrorFound = true;
5257 }
5258 Expr *E = cast<OMPHintClause>(C)->getHint();
5259 if (E->isTypeDependent() || E->isValueDependent() ||
5260 E->isInstantiationDependent())
5261 DependentHint = true;
5262 else {
5263 Hint = E->EvaluateKnownConstInt(Context);
5264 HintLoc = C->getLocStart();
5265 }
5266 }
5267 }
5268 if (ErrorFound)
5269 return StmtError();
5270 auto Pair = DSAStack->getCriticalWithHint(DirName);
5271 if (Pair.first && DirName.getName() && !DependentHint) {
5272 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5273 Diag(StartLoc, diag::err_omp_critical_with_hint);
5274 if (HintLoc.isValid()) {
5275 Diag(HintLoc, diag::note_omp_critical_hint_here)
5276 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5277 } else
5278 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5279 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5280 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5281 << 1
5282 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5283 /*Radix=*/10, /*Signed=*/false);
5284 } else
5285 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5286 }
5287 }
5288
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005289 getCurFunction()->setHasBranchProtectedScope();
5290
Alexey Bataev28c75412015-12-15 08:19:24 +00005291 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5292 Clauses, AStmt);
5293 if (!Pair.first && DirName.getName() && !DependentHint)
5294 DSAStack->addCriticalWithHint(Dir, Hint);
5295 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005296}
5297
Alexey Bataev4acb8592014-07-07 13:01:15 +00005298StmtResult Sema::ActOnOpenMPParallelForDirective(
5299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5300 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005302 if (!AStmt)
5303 return StmtError();
5304
Alexey Bataev4acb8592014-07-07 13:01:15 +00005305 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5306 // 1.2.2 OpenMP Language Terminology
5307 // Structured block - An executable statement with a single entry at the
5308 // top and a single exit at the bottom.
5309 // The point of exit cannot be a branch out of the structured block.
5310 // longjmp() and throw() must not violate the entry/exit criteria.
5311 CS->getCapturedDecl()->setNothrow();
5312
Alexander Musmanc6388682014-12-15 07:07:06 +00005313 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5315 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005316 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005317 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5318 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5319 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005320 if (NestedLoopCount == 0)
5321 return StmtError();
5322
Alexander Musmana5f070a2014-10-01 06:03:56 +00005323 assert((CurContext->isDependentContext() || B.builtAll()) &&
5324 "omp parallel for loop exprs were not built");
5325
Alexey Bataev54acd402015-08-04 11:18:19 +00005326 if (!CurContext->isDependentContext()) {
5327 // Finalize the clauses that need pre-built expressions for CodeGen.
5328 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005329 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005331 B.NumIterations, *this, CurScope,
5332 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005333 return StmtError();
5334 }
5335 }
5336
Alexey Bataev4acb8592014-07-07 13:01:15 +00005337 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005338 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005339 NestedLoopCount, Clauses, AStmt, B,
5340 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005341}
5342
Alexander Musmane4e893b2014-09-23 09:33:00 +00005343StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5344 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5345 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005346 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005347 if (!AStmt)
5348 return StmtError();
5349
Alexander Musmane4e893b2014-09-23 09:33:00 +00005350 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5351 // 1.2.2 OpenMP Language Terminology
5352 // Structured block - An executable statement with a single entry at the
5353 // top and a single exit at the bottom.
5354 // The point of exit cannot be a branch out of the structured block.
5355 // longjmp() and throw() must not violate the entry/exit criteria.
5356 CS->getCapturedDecl()->setNothrow();
5357
Alexander Musmanc6388682014-12-15 07:07:06 +00005358 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005359 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5360 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005361 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005362 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5363 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5364 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005365 if (NestedLoopCount == 0)
5366 return StmtError();
5367
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005368 if (!CurContext->isDependentContext()) {
5369 // Finalize the clauses that need pre-built expressions for CodeGen.
5370 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005371 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005372 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005373 B.NumIterations, *this, CurScope,
5374 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005375 return StmtError();
5376 }
5377 }
5378
Kelvin Lic5609492016-07-15 04:39:07 +00005379 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005380 return StmtError();
5381
Alexander Musmane4e893b2014-09-23 09:33:00 +00005382 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005383 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005384 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005385}
5386
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005387StmtResult
5388Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5389 Stmt *AStmt, SourceLocation StartLoc,
5390 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005391 if (!AStmt)
5392 return StmtError();
5393
5394 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005395 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005396 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005397 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005398 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005399 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005400 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005401 return StmtError();
5402 // All associated statements must be '#pragma omp section' except for
5403 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005404 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005405 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5406 if (SectionStmt)
5407 Diag(SectionStmt->getLocStart(),
5408 diag::err_omp_parallel_sections_substmt_not_section);
5409 return StmtError();
5410 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005411 cast<OMPSectionDirective>(SectionStmt)
5412 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005413 }
5414 } else {
5415 Diag(AStmt->getLocStart(),
5416 diag::err_omp_parallel_sections_not_compound_stmt);
5417 return StmtError();
5418 }
5419
5420 getCurFunction()->setHasBranchProtectedScope();
5421
Alexey Bataev25e5b442015-09-15 12:52:43 +00005422 return OMPParallelSectionsDirective::Create(
5423 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005424}
5425
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005426StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5427 Stmt *AStmt, SourceLocation StartLoc,
5428 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005429 if (!AStmt)
5430 return StmtError();
5431
David Majnemer9d168222016-08-05 17:44:54 +00005432 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005433 // 1.2.2 OpenMP Language Terminology
5434 // Structured block - An executable statement with a single entry at the
5435 // top and a single exit at the bottom.
5436 // The point of exit cannot be a branch out of the structured block.
5437 // longjmp() and throw() must not violate the entry/exit criteria.
5438 CS->getCapturedDecl()->setNothrow();
5439
5440 getCurFunction()->setHasBranchProtectedScope();
5441
Alexey Bataev25e5b442015-09-15 12:52:43 +00005442 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5443 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005444}
5445
Alexey Bataev68446b72014-07-18 07:47:19 +00005446StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5447 SourceLocation EndLoc) {
5448 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5449}
5450
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005451StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5452 SourceLocation EndLoc) {
5453 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5454}
5455
Alexey Bataev2df347a2014-07-18 10:17:07 +00005456StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5457 SourceLocation EndLoc) {
5458 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5459}
5460
Alexey Bataev169d96a2017-07-18 20:17:46 +00005461StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5462 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005463 SourceLocation StartLoc,
5464 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005465 if (!AStmt)
5466 return StmtError();
5467
5468 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005469
5470 getCurFunction()->setHasBranchProtectedScope();
5471
Alexey Bataev169d96a2017-07-18 20:17:46 +00005472 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005473 AStmt,
5474 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005475}
5476
Alexey Bataev6125da92014-07-21 11:26:11 +00005477StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5478 SourceLocation StartLoc,
5479 SourceLocation EndLoc) {
5480 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5481 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5482}
5483
Alexey Bataev346265e2015-09-25 10:37:12 +00005484StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5485 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005486 SourceLocation StartLoc,
5487 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005488 OMPClause *DependFound = nullptr;
5489 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005490 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005491 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005492 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005493 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005494 for (auto *C : Clauses) {
5495 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5496 DependFound = C;
5497 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5498 if (DependSourceClause) {
5499 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5500 << getOpenMPDirectiveName(OMPD_ordered)
5501 << getOpenMPClauseName(OMPC_depend) << 2;
5502 ErrorFound = true;
5503 } else
5504 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005505 if (DependSinkClause) {
5506 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5507 << 0;
5508 ErrorFound = true;
5509 }
5510 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5511 if (DependSourceClause) {
5512 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5513 << 1;
5514 ErrorFound = true;
5515 }
5516 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005517 }
5518 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005519 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005520 else if (C->getClauseKind() == OMPC_simd)
5521 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005522 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005523 if (!ErrorFound && !SC &&
5524 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005525 // OpenMP [2.8.1,simd Construct, Restrictions]
5526 // An ordered construct with the simd clause is the only OpenMP construct
5527 // that can appear in the simd region.
5528 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005529 ErrorFound = true;
5530 } else if (DependFound && (TC || SC)) {
5531 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5532 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5533 ErrorFound = true;
5534 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5535 Diag(DependFound->getLocStart(),
5536 diag::err_omp_ordered_directive_without_param);
5537 ErrorFound = true;
5538 } else if (TC || Clauses.empty()) {
5539 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5540 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5541 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5542 << (TC != nullptr);
5543 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5544 ErrorFound = true;
5545 }
5546 }
5547 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005548 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005549
5550 if (AStmt) {
5551 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5552
5553 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005554 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005555
5556 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005557}
5558
Alexey Bataev1d160b12015-03-13 12:27:31 +00005559namespace {
5560/// \brief Helper class for checking expression in 'omp atomic [update]'
5561/// construct.
5562class OpenMPAtomicUpdateChecker {
5563 /// \brief Error results for atomic update expressions.
5564 enum ExprAnalysisErrorCode {
5565 /// \brief A statement is not an expression statement.
5566 NotAnExpression,
5567 /// \brief Expression is not builtin binary or unary operation.
5568 NotABinaryOrUnaryExpression,
5569 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5570 NotAnUnaryIncDecExpression,
5571 /// \brief An expression is not of scalar type.
5572 NotAScalarType,
5573 /// \brief A binary operation is not an assignment operation.
5574 NotAnAssignmentOp,
5575 /// \brief RHS part of the binary operation is not a binary expression.
5576 NotABinaryExpression,
5577 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5578 /// expression.
5579 NotABinaryOperator,
5580 /// \brief RHS binary operation does not have reference to the updated LHS
5581 /// part.
5582 NotAnUpdateExpression,
5583 /// \brief No errors is found.
5584 NoError
5585 };
5586 /// \brief Reference to Sema.
5587 Sema &SemaRef;
5588 /// \brief A location for note diagnostics (when error is found).
5589 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005590 /// \brief 'x' lvalue part of the source atomic expression.
5591 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005592 /// \brief 'expr' rvalue part of the source atomic expression.
5593 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005594 /// \brief Helper expression of the form
5595 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5596 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5597 Expr *UpdateExpr;
5598 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5599 /// important for non-associative operations.
5600 bool IsXLHSInRHSPart;
5601 BinaryOperatorKind Op;
5602 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005603 /// \brief true if the source expression is a postfix unary operation, false
5604 /// if it is a prefix unary operation.
5605 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005606
5607public:
5608 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005609 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005610 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005611 /// \brief Check specified statement that it is suitable for 'atomic update'
5612 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005613 /// expression. If DiagId and NoteId == 0, then only check is performed
5614 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005615 /// \param DiagId Diagnostic which should be emitted if error is found.
5616 /// \param NoteId Diagnostic note for the main error message.
5617 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005618 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005619 /// \brief Return the 'x' lvalue part of the source atomic expression.
5620 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005621 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5622 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005623 /// \brief Return the update expression used in calculation of the updated
5624 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5625 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5626 Expr *getUpdateExpr() const { return UpdateExpr; }
5627 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5628 /// false otherwise.
5629 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5630
Alexey Bataevb78ca832015-04-01 03:33:17 +00005631 /// \brief true if the source expression is a postfix unary operation, false
5632 /// if it is a prefix unary operation.
5633 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5634
Alexey Bataev1d160b12015-03-13 12:27:31 +00005635private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005636 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5637 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005638};
5639} // namespace
5640
5641bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5642 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5643 ExprAnalysisErrorCode ErrorFound = NoError;
5644 SourceLocation ErrorLoc, NoteLoc;
5645 SourceRange ErrorRange, NoteRange;
5646 // Allowed constructs are:
5647 // x = x binop expr;
5648 // x = expr binop x;
5649 if (AtomicBinOp->getOpcode() == BO_Assign) {
5650 X = AtomicBinOp->getLHS();
5651 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5652 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5653 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5654 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5655 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005656 Op = AtomicInnerBinOp->getOpcode();
5657 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005658 auto *LHS = AtomicInnerBinOp->getLHS();
5659 auto *RHS = AtomicInnerBinOp->getRHS();
5660 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5661 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5662 /*Canonical=*/true);
5663 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5664 /*Canonical=*/true);
5665 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5666 /*Canonical=*/true);
5667 if (XId == LHSId) {
5668 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005669 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005670 } else if (XId == RHSId) {
5671 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005672 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005673 } else {
5674 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5675 ErrorRange = AtomicInnerBinOp->getSourceRange();
5676 NoteLoc = X->getExprLoc();
5677 NoteRange = X->getSourceRange();
5678 ErrorFound = NotAnUpdateExpression;
5679 }
5680 } else {
5681 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5682 ErrorRange = AtomicInnerBinOp->getSourceRange();
5683 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5684 NoteRange = SourceRange(NoteLoc, NoteLoc);
5685 ErrorFound = NotABinaryOperator;
5686 }
5687 } else {
5688 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5689 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5690 ErrorFound = NotABinaryExpression;
5691 }
5692 } else {
5693 ErrorLoc = AtomicBinOp->getExprLoc();
5694 ErrorRange = AtomicBinOp->getSourceRange();
5695 NoteLoc = AtomicBinOp->getOperatorLoc();
5696 NoteRange = SourceRange(NoteLoc, NoteLoc);
5697 ErrorFound = NotAnAssignmentOp;
5698 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005699 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005700 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5701 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5702 return true;
5703 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005704 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005705 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005706}
5707
5708bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5709 unsigned NoteId) {
5710 ExprAnalysisErrorCode ErrorFound = NoError;
5711 SourceLocation ErrorLoc, NoteLoc;
5712 SourceRange ErrorRange, NoteRange;
5713 // Allowed constructs are:
5714 // x++;
5715 // x--;
5716 // ++x;
5717 // --x;
5718 // x binop= expr;
5719 // x = x binop expr;
5720 // x = expr binop x;
5721 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5722 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5723 if (AtomicBody->getType()->isScalarType() ||
5724 AtomicBody->isInstantiationDependent()) {
5725 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5726 AtomicBody->IgnoreParenImpCasts())) {
5727 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005728 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005729 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005730 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005731 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005732 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005733 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005734 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5735 AtomicBody->IgnoreParenImpCasts())) {
5736 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005737 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005738 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005739 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5740 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005741 // Check for Unary Operation
5742 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005743 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005744 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5745 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005746 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005747 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5748 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005749 } else {
5750 ErrorFound = NotAnUnaryIncDecExpression;
5751 ErrorLoc = AtomicUnaryOp->getExprLoc();
5752 ErrorRange = AtomicUnaryOp->getSourceRange();
5753 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5754 NoteRange = SourceRange(NoteLoc, NoteLoc);
5755 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005756 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005757 ErrorFound = NotABinaryOrUnaryExpression;
5758 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5759 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5760 }
5761 } else {
5762 ErrorFound = NotAScalarType;
5763 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5764 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5765 }
5766 } else {
5767 ErrorFound = NotAnExpression;
5768 NoteLoc = ErrorLoc = S->getLocStart();
5769 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5770 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005771 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005772 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5773 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5774 return true;
5775 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005776 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005777 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005778 // Build an update expression of form 'OpaqueValueExpr(x) binop
5779 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5780 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5781 auto *OVEX = new (SemaRef.getASTContext())
5782 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5783 auto *OVEExpr = new (SemaRef.getASTContext())
5784 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5785 auto Update =
5786 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5787 IsXLHSInRHSPart ? OVEExpr : OVEX);
5788 if (Update.isInvalid())
5789 return true;
5790 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5791 Sema::AA_Casting);
5792 if (Update.isInvalid())
5793 return true;
5794 UpdateExpr = Update.get();
5795 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005796 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005797}
5798
Alexey Bataev0162e452014-07-22 10:10:35 +00005799StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5800 Stmt *AStmt,
5801 SourceLocation StartLoc,
5802 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005803 if (!AStmt)
5804 return StmtError();
5805
David Majnemer9d168222016-08-05 17:44:54 +00005806 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005807 // 1.2.2 OpenMP Language Terminology
5808 // Structured block - An executable statement with a single entry at the
5809 // top and a single exit at the bottom.
5810 // The point of exit cannot be a branch out of the structured block.
5811 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005812 OpenMPClauseKind AtomicKind = OMPC_unknown;
5813 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005814 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005815 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005816 C->getClauseKind() == OMPC_update ||
5817 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005818 if (AtomicKind != OMPC_unknown) {
5819 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5820 << SourceRange(C->getLocStart(), C->getLocEnd());
5821 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5822 << getOpenMPClauseName(AtomicKind);
5823 } else {
5824 AtomicKind = C->getClauseKind();
5825 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005826 }
5827 }
5828 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005829
Alexey Bataev459dec02014-07-24 06:46:57 +00005830 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005831 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5832 Body = EWC->getSubExpr();
5833
Alexey Bataev62cec442014-11-18 10:14:22 +00005834 Expr *X = nullptr;
5835 Expr *V = nullptr;
5836 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005837 Expr *UE = nullptr;
5838 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005839 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005840 // OpenMP [2.12.6, atomic Construct]
5841 // In the next expressions:
5842 // * x and v (as applicable) are both l-value expressions with scalar type.
5843 // * During the execution of an atomic region, multiple syntactic
5844 // occurrences of x must designate the same storage location.
5845 // * Neither of v and expr (as applicable) may access the storage location
5846 // designated by x.
5847 // * Neither of x and expr (as applicable) may access the storage location
5848 // designated by v.
5849 // * expr is an expression with scalar type.
5850 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5851 // * binop, binop=, ++, and -- are not overloaded operators.
5852 // * The expression x binop expr must be numerically equivalent to x binop
5853 // (expr). This requirement is satisfied if the operators in expr have
5854 // precedence greater than binop, or by using parentheses around expr or
5855 // subexpressions of expr.
5856 // * The expression expr binop x must be numerically equivalent to (expr)
5857 // binop x. This requirement is satisfied if the operators in expr have
5858 // precedence equal to or greater than binop, or by using parentheses around
5859 // expr or subexpressions of expr.
5860 // * For forms that allow multiple occurrences of x, the number of times
5861 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005862 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005863 enum {
5864 NotAnExpression,
5865 NotAnAssignmentOp,
5866 NotAScalarType,
5867 NotAnLValue,
5868 NoError
5869 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005870 SourceLocation ErrorLoc, NoteLoc;
5871 SourceRange ErrorRange, NoteRange;
5872 // If clause is read:
5873 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005874 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5875 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005876 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5877 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5878 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5879 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5880 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5881 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5882 if (!X->isLValue() || !V->isLValue()) {
5883 auto NotLValueExpr = X->isLValue() ? V : X;
5884 ErrorFound = NotAnLValue;
5885 ErrorLoc = AtomicBinOp->getExprLoc();
5886 ErrorRange = AtomicBinOp->getSourceRange();
5887 NoteLoc = NotLValueExpr->getExprLoc();
5888 NoteRange = NotLValueExpr->getSourceRange();
5889 }
5890 } else if (!X->isInstantiationDependent() ||
5891 !V->isInstantiationDependent()) {
5892 auto NotScalarExpr =
5893 (X->isInstantiationDependent() || X->getType()->isScalarType())
5894 ? V
5895 : X;
5896 ErrorFound = NotAScalarType;
5897 ErrorLoc = AtomicBinOp->getExprLoc();
5898 ErrorRange = AtomicBinOp->getSourceRange();
5899 NoteLoc = NotScalarExpr->getExprLoc();
5900 NoteRange = NotScalarExpr->getSourceRange();
5901 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005902 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005903 ErrorFound = NotAnAssignmentOp;
5904 ErrorLoc = AtomicBody->getExprLoc();
5905 ErrorRange = AtomicBody->getSourceRange();
5906 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5907 : AtomicBody->getExprLoc();
5908 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5909 : AtomicBody->getSourceRange();
5910 }
5911 } else {
5912 ErrorFound = NotAnExpression;
5913 NoteLoc = ErrorLoc = Body->getLocStart();
5914 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005915 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005916 if (ErrorFound != NoError) {
5917 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5918 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005919 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5920 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005921 return StmtError();
5922 } else if (CurContext->isDependentContext())
5923 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005924 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005925 enum {
5926 NotAnExpression,
5927 NotAnAssignmentOp,
5928 NotAScalarType,
5929 NotAnLValue,
5930 NoError
5931 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005932 SourceLocation ErrorLoc, NoteLoc;
5933 SourceRange ErrorRange, NoteRange;
5934 // If clause is write:
5935 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005936 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5937 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005938 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5939 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005940 X = AtomicBinOp->getLHS();
5941 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005942 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5943 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5944 if (!X->isLValue()) {
5945 ErrorFound = NotAnLValue;
5946 ErrorLoc = AtomicBinOp->getExprLoc();
5947 ErrorRange = AtomicBinOp->getSourceRange();
5948 NoteLoc = X->getExprLoc();
5949 NoteRange = X->getSourceRange();
5950 }
5951 } else if (!X->isInstantiationDependent() ||
5952 !E->isInstantiationDependent()) {
5953 auto NotScalarExpr =
5954 (X->isInstantiationDependent() || X->getType()->isScalarType())
5955 ? E
5956 : X;
5957 ErrorFound = NotAScalarType;
5958 ErrorLoc = AtomicBinOp->getExprLoc();
5959 ErrorRange = AtomicBinOp->getSourceRange();
5960 NoteLoc = NotScalarExpr->getExprLoc();
5961 NoteRange = NotScalarExpr->getSourceRange();
5962 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005963 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005964 ErrorFound = NotAnAssignmentOp;
5965 ErrorLoc = AtomicBody->getExprLoc();
5966 ErrorRange = AtomicBody->getSourceRange();
5967 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5968 : AtomicBody->getExprLoc();
5969 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5970 : AtomicBody->getSourceRange();
5971 }
5972 } else {
5973 ErrorFound = NotAnExpression;
5974 NoteLoc = ErrorLoc = Body->getLocStart();
5975 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005976 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005977 if (ErrorFound != NoError) {
5978 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5979 << ErrorRange;
5980 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5981 << NoteRange;
5982 return StmtError();
5983 } else if (CurContext->isDependentContext())
5984 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005985 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005986 // If clause is update:
5987 // x++;
5988 // x--;
5989 // ++x;
5990 // --x;
5991 // x binop= expr;
5992 // x = x binop expr;
5993 // x = expr binop x;
5994 OpenMPAtomicUpdateChecker Checker(*this);
5995 if (Checker.checkStatement(
5996 Body, (AtomicKind == OMPC_update)
5997 ? diag::err_omp_atomic_update_not_expression_statement
5998 : diag::err_omp_atomic_not_expression_statement,
5999 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006000 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006001 if (!CurContext->isDependentContext()) {
6002 E = Checker.getExpr();
6003 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006004 UE = Checker.getUpdateExpr();
6005 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006006 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006007 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006008 enum {
6009 NotAnAssignmentOp,
6010 NotACompoundStatement,
6011 NotTwoSubstatements,
6012 NotASpecificExpression,
6013 NoError
6014 } ErrorFound = NoError;
6015 SourceLocation ErrorLoc, NoteLoc;
6016 SourceRange ErrorRange, NoteRange;
6017 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6018 // If clause is a capture:
6019 // v = x++;
6020 // v = x--;
6021 // v = ++x;
6022 // v = --x;
6023 // v = x binop= expr;
6024 // v = x = x binop expr;
6025 // v = x = expr binop x;
6026 auto *AtomicBinOp =
6027 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6028 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6029 V = AtomicBinOp->getLHS();
6030 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6031 OpenMPAtomicUpdateChecker Checker(*this);
6032 if (Checker.checkStatement(
6033 Body, diag::err_omp_atomic_capture_not_expression_statement,
6034 diag::note_omp_atomic_update))
6035 return StmtError();
6036 E = Checker.getExpr();
6037 X = Checker.getX();
6038 UE = Checker.getUpdateExpr();
6039 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6040 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006041 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006042 ErrorLoc = AtomicBody->getExprLoc();
6043 ErrorRange = AtomicBody->getSourceRange();
6044 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6045 : AtomicBody->getExprLoc();
6046 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6047 : AtomicBody->getSourceRange();
6048 ErrorFound = NotAnAssignmentOp;
6049 }
6050 if (ErrorFound != NoError) {
6051 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6052 << ErrorRange;
6053 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6054 return StmtError();
6055 } else if (CurContext->isDependentContext()) {
6056 UE = V = E = X = nullptr;
6057 }
6058 } else {
6059 // If clause is a capture:
6060 // { v = x; x = expr; }
6061 // { v = x; x++; }
6062 // { v = x; x--; }
6063 // { v = x; ++x; }
6064 // { v = x; --x; }
6065 // { v = x; x binop= expr; }
6066 // { v = x; x = x binop expr; }
6067 // { v = x; x = expr binop x; }
6068 // { x++; v = x; }
6069 // { x--; v = x; }
6070 // { ++x; v = x; }
6071 // { --x; v = x; }
6072 // { x binop= expr; v = x; }
6073 // { x = x binop expr; v = x; }
6074 // { x = expr binop x; v = x; }
6075 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6076 // Check that this is { expr1; expr2; }
6077 if (CS->size() == 2) {
6078 auto *First = CS->body_front();
6079 auto *Second = CS->body_back();
6080 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6081 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6082 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6083 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6084 // Need to find what subexpression is 'v' and what is 'x'.
6085 OpenMPAtomicUpdateChecker Checker(*this);
6086 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6087 BinaryOperator *BinOp = nullptr;
6088 if (IsUpdateExprFound) {
6089 BinOp = dyn_cast<BinaryOperator>(First);
6090 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6091 }
6092 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6093 // { v = x; x++; }
6094 // { v = x; x--; }
6095 // { v = x; ++x; }
6096 // { v = x; --x; }
6097 // { v = x; x binop= expr; }
6098 // { v = x; x = x binop expr; }
6099 // { v = x; x = expr binop x; }
6100 // Check that the first expression has form v = x.
6101 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6102 llvm::FoldingSetNodeID XId, PossibleXId;
6103 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6104 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6105 IsUpdateExprFound = XId == PossibleXId;
6106 if (IsUpdateExprFound) {
6107 V = BinOp->getLHS();
6108 X = Checker.getX();
6109 E = Checker.getExpr();
6110 UE = Checker.getUpdateExpr();
6111 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006112 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006113 }
6114 }
6115 if (!IsUpdateExprFound) {
6116 IsUpdateExprFound = !Checker.checkStatement(First);
6117 BinOp = nullptr;
6118 if (IsUpdateExprFound) {
6119 BinOp = dyn_cast<BinaryOperator>(Second);
6120 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6121 }
6122 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6123 // { x++; v = x; }
6124 // { x--; v = x; }
6125 // { ++x; v = x; }
6126 // { --x; v = x; }
6127 // { x binop= expr; v = x; }
6128 // { x = x binop expr; v = x; }
6129 // { x = expr binop x; v = x; }
6130 // Check that the second expression has form v = x.
6131 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6132 llvm::FoldingSetNodeID XId, PossibleXId;
6133 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6134 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6135 IsUpdateExprFound = XId == PossibleXId;
6136 if (IsUpdateExprFound) {
6137 V = BinOp->getLHS();
6138 X = Checker.getX();
6139 E = Checker.getExpr();
6140 UE = Checker.getUpdateExpr();
6141 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006142 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006143 }
6144 }
6145 }
6146 if (!IsUpdateExprFound) {
6147 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006148 auto *FirstExpr = dyn_cast<Expr>(First);
6149 auto *SecondExpr = dyn_cast<Expr>(Second);
6150 if (!FirstExpr || !SecondExpr ||
6151 !(FirstExpr->isInstantiationDependent() ||
6152 SecondExpr->isInstantiationDependent())) {
6153 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6154 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006155 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006156 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6157 : First->getLocStart();
6158 NoteRange = ErrorRange = FirstBinOp
6159 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006160 : SourceRange(ErrorLoc, ErrorLoc);
6161 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006162 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6163 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6164 ErrorFound = NotAnAssignmentOp;
6165 NoteLoc = ErrorLoc = SecondBinOp
6166 ? SecondBinOp->getOperatorLoc()
6167 : Second->getLocStart();
6168 NoteRange = ErrorRange =
6169 SecondBinOp ? SecondBinOp->getSourceRange()
6170 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006171 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006172 auto *PossibleXRHSInFirst =
6173 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6174 auto *PossibleXLHSInSecond =
6175 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6176 llvm::FoldingSetNodeID X1Id, X2Id;
6177 PossibleXRHSInFirst->Profile(X1Id, Context,
6178 /*Canonical=*/true);
6179 PossibleXLHSInSecond->Profile(X2Id, Context,
6180 /*Canonical=*/true);
6181 IsUpdateExprFound = X1Id == X2Id;
6182 if (IsUpdateExprFound) {
6183 V = FirstBinOp->getLHS();
6184 X = SecondBinOp->getLHS();
6185 E = SecondBinOp->getRHS();
6186 UE = nullptr;
6187 IsXLHSInRHSPart = false;
6188 IsPostfixUpdate = true;
6189 } else {
6190 ErrorFound = NotASpecificExpression;
6191 ErrorLoc = FirstBinOp->getExprLoc();
6192 ErrorRange = FirstBinOp->getSourceRange();
6193 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6194 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6195 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006196 }
6197 }
6198 }
6199 }
6200 } else {
6201 NoteLoc = ErrorLoc = Body->getLocStart();
6202 NoteRange = ErrorRange =
6203 SourceRange(Body->getLocStart(), Body->getLocStart());
6204 ErrorFound = NotTwoSubstatements;
6205 }
6206 } else {
6207 NoteLoc = ErrorLoc = Body->getLocStart();
6208 NoteRange = ErrorRange =
6209 SourceRange(Body->getLocStart(), Body->getLocStart());
6210 ErrorFound = NotACompoundStatement;
6211 }
6212 if (ErrorFound != NoError) {
6213 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6214 << ErrorRange;
6215 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6216 return StmtError();
6217 } else if (CurContext->isDependentContext()) {
6218 UE = V = E = X = nullptr;
6219 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006220 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006221 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006222
6223 getCurFunction()->setHasBranchProtectedScope();
6224
Alexey Bataev62cec442014-11-18 10:14:22 +00006225 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006226 X, V, E, UE, IsXLHSInRHSPart,
6227 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006228}
6229
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006230StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6231 Stmt *AStmt,
6232 SourceLocation StartLoc,
6233 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006234 if (!AStmt)
6235 return StmtError();
6236
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006237 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6238 // 1.2.2 OpenMP Language Terminology
6239 // Structured block - An executable statement with a single entry at the
6240 // top and a single exit at the bottom.
6241 // The point of exit cannot be a branch out of the structured block.
6242 // longjmp() and throw() must not violate the entry/exit criteria.
6243 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006244
Alexey Bataev13314bf2014-10-09 04:18:56 +00006245 // OpenMP [2.16, Nesting of Regions]
6246 // If specified, a teams construct must be contained within a target
6247 // construct. That target construct must contain no statements or directives
6248 // outside of the teams construct.
6249 if (DSAStack->hasInnerTeamsRegion()) {
6250 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6251 bool OMPTeamsFound = true;
6252 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6253 auto I = CS->body_begin();
6254 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006255 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006256 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6257 OMPTeamsFound = false;
6258 break;
6259 }
6260 ++I;
6261 }
6262 assert(I != CS->body_end() && "Not found statement");
6263 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006264 } else {
6265 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6266 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006267 }
6268 if (!OMPTeamsFound) {
6269 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6270 Diag(DSAStack->getInnerTeamsRegionLoc(),
6271 diag::note_omp_nested_teams_construct_here);
6272 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6273 << isa<OMPExecutableDirective>(S);
6274 return StmtError();
6275 }
6276 }
6277
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006278 getCurFunction()->setHasBranchProtectedScope();
6279
6280 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6281}
6282
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006283StmtResult
6284Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6285 Stmt *AStmt, SourceLocation StartLoc,
6286 SourceLocation EndLoc) {
6287 if (!AStmt)
6288 return StmtError();
6289
6290 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6291 // 1.2.2 OpenMP Language Terminology
6292 // Structured block - An executable statement with a single entry at the
6293 // top and a single exit at the bottom.
6294 // The point of exit cannot be a branch out of the structured block.
6295 // longjmp() and throw() must not violate the entry/exit criteria.
6296 CS->getCapturedDecl()->setNothrow();
6297
6298 getCurFunction()->setHasBranchProtectedScope();
6299
6300 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6301 AStmt);
6302}
6303
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006304StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6305 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6306 SourceLocation EndLoc,
6307 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6308 if (!AStmt)
6309 return StmtError();
6310
6311 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6312 // 1.2.2 OpenMP Language Terminology
6313 // Structured block - An executable statement with a single entry at the
6314 // top and a single exit at the bottom.
6315 // The point of exit cannot be a branch out of the structured block.
6316 // longjmp() and throw() must not violate the entry/exit criteria.
6317 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006318 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6319 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6320 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6321 // 1.2.2 OpenMP Language Terminology
6322 // Structured block - An executable statement with a single entry at the
6323 // top and a single exit at the bottom.
6324 // The point of exit cannot be a branch out of the structured block.
6325 // longjmp() and throw() must not violate the entry/exit criteria.
6326 CS->getCapturedDecl()->setNothrow();
6327 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006328
6329 OMPLoopDirective::HelperExprs B;
6330 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6331 // define the nested loops number.
6332 unsigned NestedLoopCount =
6333 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006334 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006335 VarsWithImplicitDSA, B);
6336 if (NestedLoopCount == 0)
6337 return StmtError();
6338
6339 assert((CurContext->isDependentContext() || B.builtAll()) &&
6340 "omp target parallel for loop exprs were not built");
6341
6342 if (!CurContext->isDependentContext()) {
6343 // Finalize the clauses that need pre-built expressions for CodeGen.
6344 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006345 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006346 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006347 B.NumIterations, *this, CurScope,
6348 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006349 return StmtError();
6350 }
6351 }
6352
6353 getCurFunction()->setHasBranchProtectedScope();
6354 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6355 NestedLoopCount, Clauses, AStmt,
6356 B, DSAStack->isCancelRegion());
6357}
6358
Alexey Bataev95b64a92017-05-30 16:00:04 +00006359/// Check for existence of a map clause in the list of clauses.
6360static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6361 const OpenMPClauseKind K) {
6362 return llvm::any_of(
6363 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6364}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006365
Alexey Bataev95b64a92017-05-30 16:00:04 +00006366template <typename... Params>
6367static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6368 const Params... ClauseTypes) {
6369 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006370}
6371
Michael Wong65f367f2015-07-21 13:44:28 +00006372StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6373 Stmt *AStmt,
6374 SourceLocation StartLoc,
6375 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006376 if (!AStmt)
6377 return StmtError();
6378
6379 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6380
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006381 // OpenMP [2.10.1, Restrictions, p. 97]
6382 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006383 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6384 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6385 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006386 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006387 return StmtError();
6388 }
6389
Michael Wong65f367f2015-07-21 13:44:28 +00006390 getCurFunction()->setHasBranchProtectedScope();
6391
6392 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6393 AStmt);
6394}
6395
Samuel Antaodf67fc42016-01-19 19:15:56 +00006396StmtResult
6397Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6398 SourceLocation StartLoc,
6399 SourceLocation EndLoc) {
6400 // OpenMP [2.10.2, Restrictions, p. 99]
6401 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006402 if (!hasClauses(Clauses, OMPC_map)) {
6403 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6404 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006405 return StmtError();
6406 }
6407
6408 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6409 Clauses);
6410}
6411
Samuel Antao72590762016-01-19 20:04:50 +00006412StmtResult
6413Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6414 SourceLocation StartLoc,
6415 SourceLocation EndLoc) {
6416 // OpenMP [2.10.3, Restrictions, p. 102]
6417 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006418 if (!hasClauses(Clauses, OMPC_map)) {
6419 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6420 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006421 return StmtError();
6422 }
6423
6424 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6425}
6426
Samuel Antao686c70c2016-05-26 17:30:50 +00006427StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6428 SourceLocation StartLoc,
6429 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006430 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006431 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6432 return StmtError();
6433 }
6434 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6435}
6436
Alexey Bataev13314bf2014-10-09 04:18:56 +00006437StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6438 Stmt *AStmt, SourceLocation StartLoc,
6439 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006440 if (!AStmt)
6441 return StmtError();
6442
Alexey Bataev13314bf2014-10-09 04:18:56 +00006443 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6444 // 1.2.2 OpenMP Language Terminology
6445 // Structured block - An executable statement with a single entry at the
6446 // top and a single exit at the bottom.
6447 // The point of exit cannot be a branch out of the structured block.
6448 // longjmp() and throw() must not violate the entry/exit criteria.
6449 CS->getCapturedDecl()->setNothrow();
6450
6451 getCurFunction()->setHasBranchProtectedScope();
6452
6453 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6454}
6455
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006456StmtResult
6457Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6458 SourceLocation EndLoc,
6459 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006460 if (DSAStack->isParentNowaitRegion()) {
6461 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6462 return StmtError();
6463 }
6464 if (DSAStack->isParentOrderedRegion()) {
6465 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6466 return StmtError();
6467 }
6468 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6469 CancelRegion);
6470}
6471
Alexey Bataev87933c72015-09-18 08:07:34 +00006472StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6473 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006474 SourceLocation EndLoc,
6475 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006476 if (DSAStack->isParentNowaitRegion()) {
6477 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6478 return StmtError();
6479 }
6480 if (DSAStack->isParentOrderedRegion()) {
6481 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6482 return StmtError();
6483 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006484 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006485 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6486 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006487}
6488
Alexey Bataev382967a2015-12-08 12:06:20 +00006489static bool checkGrainsizeNumTasksClauses(Sema &S,
6490 ArrayRef<OMPClause *> Clauses) {
6491 OMPClause *PrevClause = nullptr;
6492 bool ErrorFound = false;
6493 for (auto *C : Clauses) {
6494 if (C->getClauseKind() == OMPC_grainsize ||
6495 C->getClauseKind() == OMPC_num_tasks) {
6496 if (!PrevClause)
6497 PrevClause = C;
6498 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6499 S.Diag(C->getLocStart(),
6500 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6501 << getOpenMPClauseName(C->getClauseKind())
6502 << getOpenMPClauseName(PrevClause->getClauseKind());
6503 S.Diag(PrevClause->getLocStart(),
6504 diag::note_omp_previous_grainsize_num_tasks)
6505 << getOpenMPClauseName(PrevClause->getClauseKind());
6506 ErrorFound = true;
6507 }
6508 }
6509 }
6510 return ErrorFound;
6511}
6512
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006513static bool checkReductionClauseWithNogroup(Sema &S,
6514 ArrayRef<OMPClause *> Clauses) {
6515 OMPClause *ReductionClause = nullptr;
6516 OMPClause *NogroupClause = nullptr;
6517 for (auto *C : Clauses) {
6518 if (C->getClauseKind() == OMPC_reduction) {
6519 ReductionClause = C;
6520 if (NogroupClause)
6521 break;
6522 continue;
6523 }
6524 if (C->getClauseKind() == OMPC_nogroup) {
6525 NogroupClause = C;
6526 if (ReductionClause)
6527 break;
6528 continue;
6529 }
6530 }
6531 if (ReductionClause && NogroupClause) {
6532 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6533 << SourceRange(NogroupClause->getLocStart(),
6534 NogroupClause->getLocEnd());
6535 return true;
6536 }
6537 return false;
6538}
6539
Alexey Bataev49f6e782015-12-01 04:18:41 +00006540StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6541 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6542 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006543 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006544 if (!AStmt)
6545 return StmtError();
6546
6547 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6548 OMPLoopDirective::HelperExprs B;
6549 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6550 // define the nested loops number.
6551 unsigned NestedLoopCount =
6552 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006553 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006554 VarsWithImplicitDSA, B);
6555 if (NestedLoopCount == 0)
6556 return StmtError();
6557
6558 assert((CurContext->isDependentContext() || B.builtAll()) &&
6559 "omp for loop exprs were not built");
6560
Alexey Bataev382967a2015-12-08 12:06:20 +00006561 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6562 // The grainsize clause and num_tasks clause are mutually exclusive and may
6563 // not appear on the same taskloop directive.
6564 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6565 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006566 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6567 // If a reduction clause is present on the taskloop directive, the nogroup
6568 // clause must not be specified.
6569 if (checkReductionClauseWithNogroup(*this, Clauses))
6570 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006571
Alexey Bataev49f6e782015-12-01 04:18:41 +00006572 getCurFunction()->setHasBranchProtectedScope();
6573 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6574 NestedLoopCount, Clauses, AStmt, B);
6575}
6576
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006577StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6578 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6579 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006580 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006581 if (!AStmt)
6582 return StmtError();
6583
6584 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6585 OMPLoopDirective::HelperExprs B;
6586 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6587 // define the nested loops number.
6588 unsigned NestedLoopCount =
6589 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6590 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6591 VarsWithImplicitDSA, B);
6592 if (NestedLoopCount == 0)
6593 return StmtError();
6594
6595 assert((CurContext->isDependentContext() || B.builtAll()) &&
6596 "omp for loop exprs were not built");
6597
Alexey Bataev5a3af132016-03-29 08:58:54 +00006598 if (!CurContext->isDependentContext()) {
6599 // Finalize the clauses that need pre-built expressions for CodeGen.
6600 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006601 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006602 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006603 B.NumIterations, *this, CurScope,
6604 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006605 return StmtError();
6606 }
6607 }
6608
Alexey Bataev382967a2015-12-08 12:06:20 +00006609 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6610 // The grainsize clause and num_tasks clause are mutually exclusive and may
6611 // not appear on the same taskloop directive.
6612 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6613 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006614 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6615 // If a reduction clause is present on the taskloop directive, the nogroup
6616 // clause must not be specified.
6617 if (checkReductionClauseWithNogroup(*this, Clauses))
6618 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006619
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006620 getCurFunction()->setHasBranchProtectedScope();
6621 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6622 NestedLoopCount, Clauses, AStmt, B);
6623}
6624
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006625StmtResult Sema::ActOnOpenMPDistributeDirective(
6626 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6627 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006628 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006629 if (!AStmt)
6630 return StmtError();
6631
6632 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6633 OMPLoopDirective::HelperExprs B;
6634 // In presence of clause 'collapse' with number of loops, it will
6635 // define the nested loops number.
6636 unsigned NestedLoopCount =
6637 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6638 nullptr /*ordered not a clause on distribute*/, AStmt,
6639 *this, *DSAStack, VarsWithImplicitDSA, B);
6640 if (NestedLoopCount == 0)
6641 return StmtError();
6642
6643 assert((CurContext->isDependentContext() || B.builtAll()) &&
6644 "omp for loop exprs were not built");
6645
6646 getCurFunction()->setHasBranchProtectedScope();
6647 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6648 NestedLoopCount, Clauses, AStmt, B);
6649}
6650
Carlo Bertolli9925f152016-06-27 14:55:37 +00006651StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6652 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6653 SourceLocation EndLoc,
6654 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6655 if (!AStmt)
6656 return StmtError();
6657
6658 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6659 // 1.2.2 OpenMP Language Terminology
6660 // Structured block - An executable statement with a single entry at the
6661 // top and a single exit at the bottom.
6662 // The point of exit cannot be a branch out of the structured block.
6663 // longjmp() and throw() must not violate the entry/exit criteria.
6664 CS->getCapturedDecl()->setNothrow();
6665
6666 OMPLoopDirective::HelperExprs B;
6667 // In presence of clause 'collapse' with number of loops, it will
6668 // define the nested loops number.
6669 unsigned NestedLoopCount = CheckOpenMPLoop(
6670 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6671 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6672 VarsWithImplicitDSA, B);
6673 if (NestedLoopCount == 0)
6674 return StmtError();
6675
6676 assert((CurContext->isDependentContext() || B.builtAll()) &&
6677 "omp for loop exprs were not built");
6678
6679 getCurFunction()->setHasBranchProtectedScope();
6680 return OMPDistributeParallelForDirective::Create(
6681 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6682}
6683
Kelvin Li4a39add2016-07-05 05:00:15 +00006684StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6685 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6686 SourceLocation EndLoc,
6687 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6688 if (!AStmt)
6689 return StmtError();
6690
6691 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6692 // 1.2.2 OpenMP Language Terminology
6693 // Structured block - An executable statement with a single entry at the
6694 // top and a single exit at the bottom.
6695 // The point of exit cannot be a branch out of the structured block.
6696 // longjmp() and throw() must not violate the entry/exit criteria.
6697 CS->getCapturedDecl()->setNothrow();
6698
6699 OMPLoopDirective::HelperExprs B;
6700 // In presence of clause 'collapse' with number of loops, it will
6701 // define the nested loops number.
6702 unsigned NestedLoopCount = CheckOpenMPLoop(
6703 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6704 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6705 VarsWithImplicitDSA, B);
6706 if (NestedLoopCount == 0)
6707 return StmtError();
6708
6709 assert((CurContext->isDependentContext() || B.builtAll()) &&
6710 "omp for loop exprs were not built");
6711
Kelvin Lic5609492016-07-15 04:39:07 +00006712 if (checkSimdlenSafelenSpecified(*this, Clauses))
6713 return StmtError();
6714
Kelvin Li4a39add2016-07-05 05:00:15 +00006715 getCurFunction()->setHasBranchProtectedScope();
6716 return OMPDistributeParallelForSimdDirective::Create(
6717 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6718}
6719
Kelvin Li787f3fc2016-07-06 04:45:38 +00006720StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6721 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6722 SourceLocation EndLoc,
6723 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6724 if (!AStmt)
6725 return StmtError();
6726
6727 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6728 // 1.2.2 OpenMP Language Terminology
6729 // Structured block - An executable statement with a single entry at the
6730 // top and a single exit at the bottom.
6731 // The point of exit cannot be a branch out of the structured block.
6732 // longjmp() and throw() must not violate the entry/exit criteria.
6733 CS->getCapturedDecl()->setNothrow();
6734
6735 OMPLoopDirective::HelperExprs B;
6736 // In presence of clause 'collapse' with number of loops, it will
6737 // define the nested loops number.
6738 unsigned NestedLoopCount =
6739 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6740 nullptr /*ordered not a clause on distribute*/, AStmt,
6741 *this, *DSAStack, VarsWithImplicitDSA, B);
6742 if (NestedLoopCount == 0)
6743 return StmtError();
6744
6745 assert((CurContext->isDependentContext() || B.builtAll()) &&
6746 "omp for loop exprs were not built");
6747
Kelvin Lic5609492016-07-15 04:39:07 +00006748 if (checkSimdlenSafelenSpecified(*this, Clauses))
6749 return StmtError();
6750
Kelvin Li787f3fc2016-07-06 04:45:38 +00006751 getCurFunction()->setHasBranchProtectedScope();
6752 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6753 NestedLoopCount, Clauses, AStmt, B);
6754}
6755
Kelvin Lia579b912016-07-14 02:54:56 +00006756StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6758 SourceLocation EndLoc,
6759 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6760 if (!AStmt)
6761 return StmtError();
6762
6763 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6764 // 1.2.2 OpenMP Language Terminology
6765 // Structured block - An executable statement with a single entry at the
6766 // top and a single exit at the bottom.
6767 // The point of exit cannot be a branch out of the structured block.
6768 // longjmp() and throw() must not violate the entry/exit criteria.
6769 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006770 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6771 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6772 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6773 // 1.2.2 OpenMP Language Terminology
6774 // Structured block - An executable statement with a single entry at the
6775 // top and a single exit at the bottom.
6776 // The point of exit cannot be a branch out of the structured block.
6777 // longjmp() and throw() must not violate the entry/exit criteria.
6778 CS->getCapturedDecl()->setNothrow();
6779 }
Kelvin Lia579b912016-07-14 02:54:56 +00006780
6781 OMPLoopDirective::HelperExprs B;
6782 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6783 // define the nested loops number.
6784 unsigned NestedLoopCount = CheckOpenMPLoop(
6785 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006786 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00006787 VarsWithImplicitDSA, B);
6788 if (NestedLoopCount == 0)
6789 return StmtError();
6790
6791 assert((CurContext->isDependentContext() || B.builtAll()) &&
6792 "omp target parallel for simd loop exprs were not built");
6793
6794 if (!CurContext->isDependentContext()) {
6795 // Finalize the clauses that need pre-built expressions for CodeGen.
6796 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006797 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006798 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6799 B.NumIterations, *this, CurScope,
6800 DSAStack))
6801 return StmtError();
6802 }
6803 }
Kelvin Lic5609492016-07-15 04:39:07 +00006804 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006805 return StmtError();
6806
6807 getCurFunction()->setHasBranchProtectedScope();
6808 return OMPTargetParallelForSimdDirective::Create(
6809 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6810}
6811
Kelvin Li986330c2016-07-20 22:57:10 +00006812StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6814 SourceLocation EndLoc,
6815 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6816 if (!AStmt)
6817 return StmtError();
6818
6819 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6820 // 1.2.2 OpenMP Language Terminology
6821 // Structured block - An executable statement with a single entry at the
6822 // top and a single exit at the bottom.
6823 // The point of exit cannot be a branch out of the structured block.
6824 // longjmp() and throw() must not violate the entry/exit criteria.
6825 CS->getCapturedDecl()->setNothrow();
6826
6827 OMPLoopDirective::HelperExprs B;
6828 // In presence of clause 'collapse' with number of loops, it will define the
6829 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006830 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006831 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6832 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6833 VarsWithImplicitDSA, B);
6834 if (NestedLoopCount == 0)
6835 return StmtError();
6836
6837 assert((CurContext->isDependentContext() || B.builtAll()) &&
6838 "omp target simd loop exprs were not built");
6839
6840 if (!CurContext->isDependentContext()) {
6841 // Finalize the clauses that need pre-built expressions for CodeGen.
6842 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006843 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006844 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6845 B.NumIterations, *this, CurScope,
6846 DSAStack))
6847 return StmtError();
6848 }
6849 }
6850
6851 if (checkSimdlenSafelenSpecified(*this, Clauses))
6852 return StmtError();
6853
6854 getCurFunction()->setHasBranchProtectedScope();
6855 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6856 NestedLoopCount, Clauses, AStmt, B);
6857}
6858
Kelvin Li02532872016-08-05 14:37:37 +00006859StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6860 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6861 SourceLocation EndLoc,
6862 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6863 if (!AStmt)
6864 return StmtError();
6865
6866 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6867 // 1.2.2 OpenMP Language Terminology
6868 // Structured block - An executable statement with a single entry at the
6869 // top and a single exit at the bottom.
6870 // The point of exit cannot be a branch out of the structured block.
6871 // longjmp() and throw() must not violate the entry/exit criteria.
6872 CS->getCapturedDecl()->setNothrow();
6873
6874 OMPLoopDirective::HelperExprs B;
6875 // In presence of clause 'collapse' with number of loops, it will
6876 // define the nested loops number.
6877 unsigned NestedLoopCount =
6878 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6879 nullptr /*ordered not a clause on distribute*/, AStmt,
6880 *this, *DSAStack, VarsWithImplicitDSA, B);
6881 if (NestedLoopCount == 0)
6882 return StmtError();
6883
6884 assert((CurContext->isDependentContext() || B.builtAll()) &&
6885 "omp teams distribute loop exprs were not built");
6886
6887 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006888 return OMPTeamsDistributeDirective::Create(
6889 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006890}
6891
Kelvin Li4e325f72016-10-25 12:50:55 +00006892StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6893 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6894 SourceLocation EndLoc,
6895 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6896 if (!AStmt)
6897 return StmtError();
6898
6899 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6900 // 1.2.2 OpenMP Language Terminology
6901 // Structured block - An executable statement with a single entry at the
6902 // top and a single exit at the bottom.
6903 // The point of exit cannot be a branch out of the structured block.
6904 // longjmp() and throw() must not violate the entry/exit criteria.
6905 CS->getCapturedDecl()->setNothrow();
6906
6907 OMPLoopDirective::HelperExprs B;
6908 // In presence of clause 'collapse' with number of loops, it will
6909 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006910 unsigned NestedLoopCount = CheckOpenMPLoop(
6911 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6912 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6913 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006914
6915 if (NestedLoopCount == 0)
6916 return StmtError();
6917
6918 assert((CurContext->isDependentContext() || B.builtAll()) &&
6919 "omp teams distribute simd loop exprs were not built");
6920
6921 if (!CurContext->isDependentContext()) {
6922 // Finalize the clauses that need pre-built expressions for CodeGen.
6923 for (auto C : Clauses) {
6924 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6925 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6926 B.NumIterations, *this, CurScope,
6927 DSAStack))
6928 return StmtError();
6929 }
6930 }
6931
6932 if (checkSimdlenSafelenSpecified(*this, Clauses))
6933 return StmtError();
6934
6935 getCurFunction()->setHasBranchProtectedScope();
6936 return OMPTeamsDistributeSimdDirective::Create(
6937 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6938}
6939
Kelvin Li579e41c2016-11-30 23:51:03 +00006940StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6941 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6942 SourceLocation EndLoc,
6943 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6944 if (!AStmt)
6945 return StmtError();
6946
6947 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6948 // 1.2.2 OpenMP Language Terminology
6949 // Structured block - An executable statement with a single entry at the
6950 // top and a single exit at the bottom.
6951 // The point of exit cannot be a branch out of the structured block.
6952 // longjmp() and throw() must not violate the entry/exit criteria.
6953 CS->getCapturedDecl()->setNothrow();
6954
6955 OMPLoopDirective::HelperExprs B;
6956 // In presence of clause 'collapse' with number of loops, it will
6957 // define the nested loops number.
6958 auto NestedLoopCount = CheckOpenMPLoop(
6959 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6960 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6961 VarsWithImplicitDSA, B);
6962
6963 if (NestedLoopCount == 0)
6964 return StmtError();
6965
6966 assert((CurContext->isDependentContext() || B.builtAll()) &&
6967 "omp for loop exprs were not built");
6968
6969 if (!CurContext->isDependentContext()) {
6970 // Finalize the clauses that need pre-built expressions for CodeGen.
6971 for (auto C : Clauses) {
6972 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6973 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6974 B.NumIterations, *this, CurScope,
6975 DSAStack))
6976 return StmtError();
6977 }
6978 }
6979
6980 if (checkSimdlenSafelenSpecified(*this, Clauses))
6981 return StmtError();
6982
6983 getCurFunction()->setHasBranchProtectedScope();
6984 return OMPTeamsDistributeParallelForSimdDirective::Create(
6985 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6986}
6987
Kelvin Li7ade93f2016-12-09 03:24:30 +00006988StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6989 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6990 SourceLocation EndLoc,
6991 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6992 if (!AStmt)
6993 return StmtError();
6994
6995 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6996 // 1.2.2 OpenMP Language Terminology
6997 // Structured block - An executable statement with a single entry at the
6998 // top and a single exit at the bottom.
6999 // The point of exit cannot be a branch out of the structured block.
7000 // longjmp() and throw() must not violate the entry/exit criteria.
7001 CS->getCapturedDecl()->setNothrow();
7002
7003 OMPLoopDirective::HelperExprs B;
7004 // In presence of clause 'collapse' with number of loops, it will
7005 // define the nested loops number.
7006 unsigned NestedLoopCount = CheckOpenMPLoop(
7007 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7008 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7009 VarsWithImplicitDSA, B);
7010
7011 if (NestedLoopCount == 0)
7012 return StmtError();
7013
7014 assert((CurContext->isDependentContext() || B.builtAll()) &&
7015 "omp for loop exprs were not built");
7016
7017 if (!CurContext->isDependentContext()) {
7018 // Finalize the clauses that need pre-built expressions for CodeGen.
7019 for (auto C : Clauses) {
7020 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7021 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7022 B.NumIterations, *this, CurScope,
7023 DSAStack))
7024 return StmtError();
7025 }
7026 }
7027
7028 getCurFunction()->setHasBranchProtectedScope();
7029 return OMPTeamsDistributeParallelForDirective::Create(
7030 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7031}
7032
Kelvin Libf594a52016-12-17 05:48:59 +00007033StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7034 Stmt *AStmt,
7035 SourceLocation StartLoc,
7036 SourceLocation EndLoc) {
7037 if (!AStmt)
7038 return StmtError();
7039
7040 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7041 // 1.2.2 OpenMP Language Terminology
7042 // Structured block - An executable statement with a single entry at the
7043 // top and a single exit at the bottom.
7044 // The point of exit cannot be a branch out of the structured block.
7045 // longjmp() and throw() must not violate the entry/exit criteria.
7046 CS->getCapturedDecl()->setNothrow();
7047
7048 getCurFunction()->setHasBranchProtectedScope();
7049
7050 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7051 AStmt);
7052}
7053
Kelvin Li83c451e2016-12-25 04:52:54 +00007054StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7055 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7056 SourceLocation EndLoc,
7057 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7058 if (!AStmt)
7059 return StmtError();
7060
7061 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7062 // 1.2.2 OpenMP Language Terminology
7063 // Structured block - An executable statement with a single entry at the
7064 // top and a single exit at the bottom.
7065 // The point of exit cannot be a branch out of the structured block.
7066 // longjmp() and throw() must not violate the entry/exit criteria.
7067 CS->getCapturedDecl()->setNothrow();
7068
7069 OMPLoopDirective::HelperExprs B;
7070 // In presence of clause 'collapse' with number of loops, it will
7071 // define the nested loops number.
7072 auto NestedLoopCount = CheckOpenMPLoop(
7073 OMPD_target_teams_distribute,
7074 getCollapseNumberExpr(Clauses),
7075 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7076 VarsWithImplicitDSA, B);
7077 if (NestedLoopCount == 0)
7078 return StmtError();
7079
7080 assert((CurContext->isDependentContext() || B.builtAll()) &&
7081 "omp target teams distribute loop exprs were not built");
7082
7083 getCurFunction()->setHasBranchProtectedScope();
7084 return OMPTargetTeamsDistributeDirective::Create(
7085 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7086}
7087
Kelvin Li80e8f562016-12-29 22:16:30 +00007088StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7089 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7090 SourceLocation EndLoc,
7091 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7092 if (!AStmt)
7093 return StmtError();
7094
7095 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7096 // 1.2.2 OpenMP Language Terminology
7097 // Structured block - An executable statement with a single entry at the
7098 // top and a single exit at the bottom.
7099 // The point of exit cannot be a branch out of the structured block.
7100 // longjmp() and throw() must not violate the entry/exit criteria.
7101 CS->getCapturedDecl()->setNothrow();
7102
7103 OMPLoopDirective::HelperExprs B;
7104 // In presence of clause 'collapse' with number of loops, it will
7105 // define the nested loops number.
7106 auto NestedLoopCount = CheckOpenMPLoop(
7107 OMPD_target_teams_distribute_parallel_for,
7108 getCollapseNumberExpr(Clauses),
7109 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7110 VarsWithImplicitDSA, B);
7111 if (NestedLoopCount == 0)
7112 return StmtError();
7113
7114 assert((CurContext->isDependentContext() || B.builtAll()) &&
7115 "omp target teams distribute parallel for loop exprs were not built");
7116
7117 if (!CurContext->isDependentContext()) {
7118 // Finalize the clauses that need pre-built expressions for CodeGen.
7119 for (auto C : Clauses) {
7120 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7121 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7122 B.NumIterations, *this, CurScope,
7123 DSAStack))
7124 return StmtError();
7125 }
7126 }
7127
7128 getCurFunction()->setHasBranchProtectedScope();
7129 return OMPTargetTeamsDistributeParallelForDirective::Create(
7130 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7131}
7132
Kelvin Li1851df52017-01-03 05:23:48 +00007133StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7134 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7135 SourceLocation EndLoc,
7136 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7137 if (!AStmt)
7138 return StmtError();
7139
7140 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7141 // 1.2.2 OpenMP Language Terminology
7142 // Structured block - An executable statement with a single entry at the
7143 // top and a single exit at the bottom.
7144 // The point of exit cannot be a branch out of the structured block.
7145 // longjmp() and throw() must not violate the entry/exit criteria.
7146 CS->getCapturedDecl()->setNothrow();
7147
7148 OMPLoopDirective::HelperExprs B;
7149 // In presence of clause 'collapse' with number of loops, it will
7150 // define the nested loops number.
7151 auto NestedLoopCount = CheckOpenMPLoop(
7152 OMPD_target_teams_distribute_parallel_for_simd,
7153 getCollapseNumberExpr(Clauses),
7154 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7155 VarsWithImplicitDSA, B);
7156 if (NestedLoopCount == 0)
7157 return StmtError();
7158
7159 assert((CurContext->isDependentContext() || B.builtAll()) &&
7160 "omp target teams distribute parallel for simd loop exprs were not "
7161 "built");
7162
7163 if (!CurContext->isDependentContext()) {
7164 // Finalize the clauses that need pre-built expressions for CodeGen.
7165 for (auto C : Clauses) {
7166 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7167 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7168 B.NumIterations, *this, CurScope,
7169 DSAStack))
7170 return StmtError();
7171 }
7172 }
7173
7174 getCurFunction()->setHasBranchProtectedScope();
7175 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7176 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7177}
7178
Kelvin Lida681182017-01-10 18:08:18 +00007179StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7180 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7181 SourceLocation EndLoc,
7182 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7183 if (!AStmt)
7184 return StmtError();
7185
7186 auto *CS = cast<CapturedStmt>(AStmt);
7187 // 1.2.2 OpenMP Language Terminology
7188 // Structured block - An executable statement with a single entry at the
7189 // top and a single exit at the bottom.
7190 // The point of exit cannot be a branch out of the structured block.
7191 // longjmp() and throw() must not violate the entry/exit criteria.
7192 CS->getCapturedDecl()->setNothrow();
7193
7194 OMPLoopDirective::HelperExprs B;
7195 // In presence of clause 'collapse' with number of loops, it will
7196 // define the nested loops number.
7197 auto NestedLoopCount = CheckOpenMPLoop(
7198 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7199 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7200 VarsWithImplicitDSA, B);
7201 if (NestedLoopCount == 0)
7202 return StmtError();
7203
7204 assert((CurContext->isDependentContext() || B.builtAll()) &&
7205 "omp target teams distribute simd loop exprs were not built");
7206
7207 getCurFunction()->setHasBranchProtectedScope();
7208 return OMPTargetTeamsDistributeSimdDirective::Create(
7209 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7210}
7211
Alexey Bataeved09d242014-05-28 05:53:51 +00007212OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007213 SourceLocation StartLoc,
7214 SourceLocation LParenLoc,
7215 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007216 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007217 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007218 case OMPC_final:
7219 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7220 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007221 case OMPC_num_threads:
7222 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7223 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007224 case OMPC_safelen:
7225 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7226 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007227 case OMPC_simdlen:
7228 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7229 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007230 case OMPC_collapse:
7231 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7232 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007233 case OMPC_ordered:
7234 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7235 break;
Michael Wonge710d542015-08-07 16:16:36 +00007236 case OMPC_device:
7237 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7238 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007239 case OMPC_num_teams:
7240 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7241 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007242 case OMPC_thread_limit:
7243 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7244 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007245 case OMPC_priority:
7246 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7247 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007248 case OMPC_grainsize:
7249 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7250 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007251 case OMPC_num_tasks:
7252 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7253 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007254 case OMPC_hint:
7255 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7256 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007257 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007258 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007259 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007260 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007261 case OMPC_private:
7262 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007263 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007264 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007265 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007266 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007267 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007268 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007269 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007270 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007271 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007272 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007273 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007274 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007275 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007276 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007277 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007278 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007279 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007280 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007281 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007282 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007283 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007284 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007285 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007286 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007287 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007288 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007289 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007290 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007291 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007292 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007293 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007294 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007295 llvm_unreachable("Clause is not allowed.");
7296 }
7297 return Res;
7298}
7299
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007300// An OpenMP directive such as 'target parallel' has two captured regions:
7301// for the 'target' and 'parallel' respectively. This function returns
7302// the region in which to capture expressions associated with a clause.
7303// A return value of OMPD_unknown signifies that the expression should not
7304// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007305static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7306 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7307 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007308 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7309
7310 switch (CKind) {
7311 case OMPC_if:
7312 switch (DKind) {
7313 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007314 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007315 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007316 // If this clause applies to the nested 'parallel' region, capture within
7317 // the 'target' region, otherwise do not capture.
7318 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7319 CaptureRegion = OMPD_target;
7320 break;
7321 case OMPD_cancel:
7322 case OMPD_parallel:
7323 case OMPD_parallel_sections:
7324 case OMPD_parallel_for:
7325 case OMPD_parallel_for_simd:
7326 case OMPD_target:
7327 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007328 case OMPD_target_teams:
7329 case OMPD_target_teams_distribute:
7330 case OMPD_target_teams_distribute_simd:
7331 case OMPD_target_teams_distribute_parallel_for:
7332 case OMPD_target_teams_distribute_parallel_for_simd:
7333 case OMPD_teams_distribute_parallel_for:
7334 case OMPD_teams_distribute_parallel_for_simd:
7335 case OMPD_distribute_parallel_for:
7336 case OMPD_distribute_parallel_for_simd:
7337 case OMPD_task:
7338 case OMPD_taskloop:
7339 case OMPD_taskloop_simd:
7340 case OMPD_target_data:
7341 case OMPD_target_enter_data:
7342 case OMPD_target_exit_data:
7343 case OMPD_target_update:
7344 // Do not capture if-clause expressions.
7345 break;
7346 case OMPD_threadprivate:
7347 case OMPD_taskyield:
7348 case OMPD_barrier:
7349 case OMPD_taskwait:
7350 case OMPD_cancellation_point:
7351 case OMPD_flush:
7352 case OMPD_declare_reduction:
7353 case OMPD_declare_simd:
7354 case OMPD_declare_target:
7355 case OMPD_end_declare_target:
7356 case OMPD_teams:
7357 case OMPD_simd:
7358 case OMPD_for:
7359 case OMPD_for_simd:
7360 case OMPD_sections:
7361 case OMPD_section:
7362 case OMPD_single:
7363 case OMPD_master:
7364 case OMPD_critical:
7365 case OMPD_taskgroup:
7366 case OMPD_distribute:
7367 case OMPD_ordered:
7368 case OMPD_atomic:
7369 case OMPD_distribute_simd:
7370 case OMPD_teams_distribute:
7371 case OMPD_teams_distribute_simd:
7372 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7373 case OMPD_unknown:
7374 llvm_unreachable("Unknown OpenMP directive");
7375 }
7376 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007377 case OMPC_num_threads:
7378 switch (DKind) {
7379 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007380 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007381 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007382 CaptureRegion = OMPD_target;
7383 break;
7384 case OMPD_cancel:
7385 case OMPD_parallel:
7386 case OMPD_parallel_sections:
7387 case OMPD_parallel_for:
7388 case OMPD_parallel_for_simd:
7389 case OMPD_target:
7390 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007391 case OMPD_target_teams:
7392 case OMPD_target_teams_distribute:
7393 case OMPD_target_teams_distribute_simd:
7394 case OMPD_target_teams_distribute_parallel_for:
7395 case OMPD_target_teams_distribute_parallel_for_simd:
7396 case OMPD_teams_distribute_parallel_for:
7397 case OMPD_teams_distribute_parallel_for_simd:
7398 case OMPD_distribute_parallel_for:
7399 case OMPD_distribute_parallel_for_simd:
7400 case OMPD_task:
7401 case OMPD_taskloop:
7402 case OMPD_taskloop_simd:
7403 case OMPD_target_data:
7404 case OMPD_target_enter_data:
7405 case OMPD_target_exit_data:
7406 case OMPD_target_update:
7407 // Do not capture num_threads-clause expressions.
7408 break;
7409 case OMPD_threadprivate:
7410 case OMPD_taskyield:
7411 case OMPD_barrier:
7412 case OMPD_taskwait:
7413 case OMPD_cancellation_point:
7414 case OMPD_flush:
7415 case OMPD_declare_reduction:
7416 case OMPD_declare_simd:
7417 case OMPD_declare_target:
7418 case OMPD_end_declare_target:
7419 case OMPD_teams:
7420 case OMPD_simd:
7421 case OMPD_for:
7422 case OMPD_for_simd:
7423 case OMPD_sections:
7424 case OMPD_section:
7425 case OMPD_single:
7426 case OMPD_master:
7427 case OMPD_critical:
7428 case OMPD_taskgroup:
7429 case OMPD_distribute:
7430 case OMPD_ordered:
7431 case OMPD_atomic:
7432 case OMPD_distribute_simd:
7433 case OMPD_teams_distribute:
7434 case OMPD_teams_distribute_simd:
7435 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7436 case OMPD_unknown:
7437 llvm_unreachable("Unknown OpenMP directive");
7438 }
7439 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007440 case OMPC_num_teams:
7441 switch (DKind) {
7442 case OMPD_target_teams:
7443 CaptureRegion = OMPD_target;
7444 break;
7445 case OMPD_cancel:
7446 case OMPD_parallel:
7447 case OMPD_parallel_sections:
7448 case OMPD_parallel_for:
7449 case OMPD_parallel_for_simd:
7450 case OMPD_target:
7451 case OMPD_target_simd:
7452 case OMPD_target_parallel:
7453 case OMPD_target_parallel_for:
7454 case OMPD_target_parallel_for_simd:
7455 case OMPD_target_teams_distribute:
7456 case OMPD_target_teams_distribute_simd:
7457 case OMPD_target_teams_distribute_parallel_for:
7458 case OMPD_target_teams_distribute_parallel_for_simd:
7459 case OMPD_teams_distribute_parallel_for:
7460 case OMPD_teams_distribute_parallel_for_simd:
7461 case OMPD_distribute_parallel_for:
7462 case OMPD_distribute_parallel_for_simd:
7463 case OMPD_task:
7464 case OMPD_taskloop:
7465 case OMPD_taskloop_simd:
7466 case OMPD_target_data:
7467 case OMPD_target_enter_data:
7468 case OMPD_target_exit_data:
7469 case OMPD_target_update:
7470 case OMPD_teams:
7471 case OMPD_teams_distribute:
7472 case OMPD_teams_distribute_simd:
7473 // Do not capture num_teams-clause expressions.
7474 break;
7475 case OMPD_threadprivate:
7476 case OMPD_taskyield:
7477 case OMPD_barrier:
7478 case OMPD_taskwait:
7479 case OMPD_cancellation_point:
7480 case OMPD_flush:
7481 case OMPD_declare_reduction:
7482 case OMPD_declare_simd:
7483 case OMPD_declare_target:
7484 case OMPD_end_declare_target:
7485 case OMPD_simd:
7486 case OMPD_for:
7487 case OMPD_for_simd:
7488 case OMPD_sections:
7489 case OMPD_section:
7490 case OMPD_single:
7491 case OMPD_master:
7492 case OMPD_critical:
7493 case OMPD_taskgroup:
7494 case OMPD_distribute:
7495 case OMPD_ordered:
7496 case OMPD_atomic:
7497 case OMPD_distribute_simd:
7498 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7499 case OMPD_unknown:
7500 llvm_unreachable("Unknown OpenMP directive");
7501 }
7502 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007503 case OMPC_thread_limit:
7504 switch (DKind) {
7505 case OMPD_target_teams:
7506 CaptureRegion = OMPD_target;
7507 break;
7508 case OMPD_cancel:
7509 case OMPD_parallel:
7510 case OMPD_parallel_sections:
7511 case OMPD_parallel_for:
7512 case OMPD_parallel_for_simd:
7513 case OMPD_target:
7514 case OMPD_target_simd:
7515 case OMPD_target_parallel:
7516 case OMPD_target_parallel_for:
7517 case OMPD_target_parallel_for_simd:
7518 case OMPD_target_teams_distribute:
7519 case OMPD_target_teams_distribute_simd:
7520 case OMPD_target_teams_distribute_parallel_for:
7521 case OMPD_target_teams_distribute_parallel_for_simd:
7522 case OMPD_teams_distribute_parallel_for:
7523 case OMPD_teams_distribute_parallel_for_simd:
7524 case OMPD_distribute_parallel_for:
7525 case OMPD_distribute_parallel_for_simd:
7526 case OMPD_task:
7527 case OMPD_taskloop:
7528 case OMPD_taskloop_simd:
7529 case OMPD_target_data:
7530 case OMPD_target_enter_data:
7531 case OMPD_target_exit_data:
7532 case OMPD_target_update:
7533 case OMPD_teams:
7534 case OMPD_teams_distribute:
7535 case OMPD_teams_distribute_simd:
7536 // Do not capture thread_limit-clause expressions.
7537 break;
7538 case OMPD_threadprivate:
7539 case OMPD_taskyield:
7540 case OMPD_barrier:
7541 case OMPD_taskwait:
7542 case OMPD_cancellation_point:
7543 case OMPD_flush:
7544 case OMPD_declare_reduction:
7545 case OMPD_declare_simd:
7546 case OMPD_declare_target:
7547 case OMPD_end_declare_target:
7548 case OMPD_simd:
7549 case OMPD_for:
7550 case OMPD_for_simd:
7551 case OMPD_sections:
7552 case OMPD_section:
7553 case OMPD_single:
7554 case OMPD_master:
7555 case OMPD_critical:
7556 case OMPD_taskgroup:
7557 case OMPD_distribute:
7558 case OMPD_ordered:
7559 case OMPD_atomic:
7560 case OMPD_distribute_simd:
7561 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7562 case OMPD_unknown:
7563 llvm_unreachable("Unknown OpenMP directive");
7564 }
7565 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007566 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007567 switch (DKind) {
7568 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007569 case OMPD_target_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007570 CaptureRegion = OMPD_target;
7571 break;
7572 case OMPD_parallel_for:
7573 case OMPD_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007574 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 // Do not capture thread_limit-clause expressions.
7581 break;
7582 case OMPD_task:
7583 case OMPD_taskloop:
7584 case OMPD_taskloop_simd:
7585 case OMPD_target_data:
7586 case OMPD_target_enter_data:
7587 case OMPD_target_exit_data:
7588 case OMPD_target_update:
7589 case OMPD_teams:
7590 case OMPD_teams_distribute:
7591 case OMPD_teams_distribute_simd:
7592 case OMPD_target_teams_distribute:
7593 case OMPD_target_teams_distribute_simd:
7594 case OMPD_target:
7595 case OMPD_target_simd:
7596 case OMPD_target_parallel:
7597 case OMPD_cancel:
7598 case OMPD_parallel:
7599 case OMPD_parallel_sections:
7600 case OMPD_threadprivate:
7601 case OMPD_taskyield:
7602 case OMPD_barrier:
7603 case OMPD_taskwait:
7604 case OMPD_cancellation_point:
7605 case OMPD_flush:
7606 case OMPD_declare_reduction:
7607 case OMPD_declare_simd:
7608 case OMPD_declare_target:
7609 case OMPD_end_declare_target:
7610 case OMPD_simd:
7611 case OMPD_for:
7612 case OMPD_for_simd:
7613 case OMPD_sections:
7614 case OMPD_section:
7615 case OMPD_single:
7616 case OMPD_master:
7617 case OMPD_critical:
7618 case OMPD_taskgroup:
7619 case OMPD_distribute:
7620 case OMPD_ordered:
7621 case OMPD_atomic:
7622 case OMPD_distribute_simd:
7623 case OMPD_target_teams:
7624 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7625 case OMPD_unknown:
7626 llvm_unreachable("Unknown OpenMP directive");
7627 }
7628 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007629 case OMPC_dist_schedule:
7630 case OMPC_firstprivate:
7631 case OMPC_lastprivate:
7632 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007633 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007634 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007635 case OMPC_linear:
7636 case OMPC_default:
7637 case OMPC_proc_bind:
7638 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007639 case OMPC_safelen:
7640 case OMPC_simdlen:
7641 case OMPC_collapse:
7642 case OMPC_private:
7643 case OMPC_shared:
7644 case OMPC_aligned:
7645 case OMPC_copyin:
7646 case OMPC_copyprivate:
7647 case OMPC_ordered:
7648 case OMPC_nowait:
7649 case OMPC_untied:
7650 case OMPC_mergeable:
7651 case OMPC_threadprivate:
7652 case OMPC_flush:
7653 case OMPC_read:
7654 case OMPC_write:
7655 case OMPC_update:
7656 case OMPC_capture:
7657 case OMPC_seq_cst:
7658 case OMPC_depend:
7659 case OMPC_device:
7660 case OMPC_threads:
7661 case OMPC_simd:
7662 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007663 case OMPC_priority:
7664 case OMPC_grainsize:
7665 case OMPC_nogroup:
7666 case OMPC_num_tasks:
7667 case OMPC_hint:
7668 case OMPC_defaultmap:
7669 case OMPC_unknown:
7670 case OMPC_uniform:
7671 case OMPC_to:
7672 case OMPC_from:
7673 case OMPC_use_device_ptr:
7674 case OMPC_is_device_ptr:
7675 llvm_unreachable("Unexpected OpenMP clause.");
7676 }
7677 return CaptureRegion;
7678}
7679
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007680OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7681 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007682 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007683 SourceLocation NameModifierLoc,
7684 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007685 SourceLocation EndLoc) {
7686 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007687 Stmt *HelperValStmt = nullptr;
7688 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007689 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7690 !Condition->isInstantiationDependent() &&
7691 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007692 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007693 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007694 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007695
Richard Smith03a4aa32016-06-23 19:02:52 +00007696 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007697
7698 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7699 CaptureRegion =
7700 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7701 if (CaptureRegion != OMPD_unknown) {
7702 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7703 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7704 HelperValStmt = buildPreInits(Context, Captures);
7705 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007706 }
7707
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007708 return new (Context)
7709 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7710 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007711}
7712
Alexey Bataev3778b602014-07-17 07:32:53 +00007713OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7714 SourceLocation StartLoc,
7715 SourceLocation LParenLoc,
7716 SourceLocation EndLoc) {
7717 Expr *ValExpr = Condition;
7718 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7719 !Condition->isInstantiationDependent() &&
7720 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007721 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007722 if (Val.isInvalid())
7723 return nullptr;
7724
Richard Smith03a4aa32016-06-23 19:02:52 +00007725 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007726 }
7727
7728 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7729}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007730ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7731 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007732 if (!Op)
7733 return ExprError();
7734
7735 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7736 public:
7737 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007738 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007739 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7740 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007741 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7742 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007743 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7744 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007745 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7746 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007747 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7748 QualType T,
7749 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007750 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7751 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007752 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7753 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007754 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007755 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007756 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007757 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7758 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007759 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7760 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007761 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7762 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007763 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007764 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007765 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007766 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7767 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007768 llvm_unreachable("conversion functions are permitted");
7769 }
7770 } ConvertDiagnoser;
7771 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7772}
7773
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007774static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007775 OpenMPClauseKind CKind,
7776 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007777 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7778 !ValExpr->isInstantiationDependent()) {
7779 SourceLocation Loc = ValExpr->getExprLoc();
7780 ExprResult Value =
7781 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7782 if (Value.isInvalid())
7783 return false;
7784
7785 ValExpr = Value.get();
7786 // The expression must evaluate to a non-negative integer value.
7787 llvm::APSInt Result;
7788 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007789 Result.isSigned() &&
7790 !((!StrictlyPositive && Result.isNonNegative()) ||
7791 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007792 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007793 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7794 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007795 return false;
7796 }
7797 }
7798 return true;
7799}
7800
Alexey Bataev568a8332014-03-06 06:15:19 +00007801OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7802 SourceLocation StartLoc,
7803 SourceLocation LParenLoc,
7804 SourceLocation EndLoc) {
7805 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007806 Stmt *HelperValStmt = nullptr;
7807 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007808
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007809 // OpenMP [2.5, Restrictions]
7810 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007811 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7812 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007813 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007814
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007815 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7816 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7817 if (CaptureRegion != OMPD_unknown) {
7818 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7819 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7820 HelperValStmt = buildPreInits(Context, Captures);
7821 }
7822
7823 return new (Context) OMPNumThreadsClause(
7824 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007825}
7826
Alexey Bataev62c87d22014-03-21 04:51:18 +00007827ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007828 OpenMPClauseKind CKind,
7829 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007830 if (!E)
7831 return ExprError();
7832 if (E->isValueDependent() || E->isTypeDependent() ||
7833 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007834 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007835 llvm::APSInt Result;
7836 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7837 if (ICE.isInvalid())
7838 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007839 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7840 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007841 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007842 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7843 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007844 return ExprError();
7845 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007846 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7847 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7848 << E->getSourceRange();
7849 return ExprError();
7850 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007851 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7852 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007853 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007854 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007855 return ICE;
7856}
7857
7858OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7859 SourceLocation LParenLoc,
7860 SourceLocation EndLoc) {
7861 // OpenMP [2.8.1, simd construct, Description]
7862 // The parameter of the safelen clause must be a constant
7863 // positive integer expression.
7864 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7865 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007866 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007867 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007868 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007869}
7870
Alexey Bataev66b15b52015-08-21 11:14:16 +00007871OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7872 SourceLocation LParenLoc,
7873 SourceLocation EndLoc) {
7874 // OpenMP [2.8.1, simd construct, Description]
7875 // The parameter of the simdlen clause must be a constant
7876 // positive integer expression.
7877 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7878 if (Simdlen.isInvalid())
7879 return nullptr;
7880 return new (Context)
7881 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7882}
7883
Alexander Musman64d33f12014-06-04 07:53:32 +00007884OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7885 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007886 SourceLocation LParenLoc,
7887 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007888 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007889 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007890 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007891 // The parameter of the collapse clause must be a constant
7892 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007893 ExprResult NumForLoopsResult =
7894 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7895 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007896 return nullptr;
7897 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007898 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007899}
7900
Alexey Bataev10e775f2015-07-30 11:36:16 +00007901OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7902 SourceLocation EndLoc,
7903 SourceLocation LParenLoc,
7904 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007905 // OpenMP [2.7.1, loop construct, Description]
7906 // OpenMP [2.8.1, simd construct, Description]
7907 // OpenMP [2.9.6, distribute construct, Description]
7908 // The parameter of the ordered clause must be a constant
7909 // positive integer expression if any.
7910 if (NumForLoops && LParenLoc.isValid()) {
7911 ExprResult NumForLoopsResult =
7912 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7913 if (NumForLoopsResult.isInvalid())
7914 return nullptr;
7915 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007916 } else
7917 NumForLoops = nullptr;
7918 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007919 return new (Context)
7920 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7921}
7922
Alexey Bataeved09d242014-05-28 05:53:51 +00007923OMPClause *Sema::ActOnOpenMPSimpleClause(
7924 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7925 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007926 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007927 switch (Kind) {
7928 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007929 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007930 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7931 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007932 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007933 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007934 Res = ActOnOpenMPProcBindClause(
7935 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7936 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007937 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007938 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007939 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007940 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007941 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007942 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007943 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007944 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007945 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007946 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007947 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007948 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007949 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007950 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007951 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007952 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007953 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007954 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007955 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007956 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007957 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007958 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007959 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007960 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007961 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007962 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007963 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007964 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007965 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007966 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007967 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007968 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007969 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007970 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007971 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007972 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007973 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007974 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007975 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007976 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007977 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007978 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007979 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007980 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007981 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007982 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007983 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007984 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007985 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007986 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007987 llvm_unreachable("Clause is not allowed.");
7988 }
7989 return Res;
7990}
7991
Alexey Bataev6402bca2015-12-28 07:25:51 +00007992static std::string
7993getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7994 ArrayRef<unsigned> Exclude = llvm::None) {
7995 std::string Values;
7996 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7997 unsigned Skipped = Exclude.size();
7998 auto S = Exclude.begin(), E = Exclude.end();
7999 for (unsigned i = First; i < Last; ++i) {
8000 if (std::find(S, E, i) != E) {
8001 --Skipped;
8002 continue;
8003 }
8004 Values += "'";
8005 Values += getOpenMPSimpleClauseTypeName(K, i);
8006 Values += "'";
8007 if (i == Bound - Skipped)
8008 Values += " or ";
8009 else if (i != Bound + 1 - Skipped)
8010 Values += ", ";
8011 }
8012 return Values;
8013}
8014
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008015OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8016 SourceLocation KindKwLoc,
8017 SourceLocation StartLoc,
8018 SourceLocation LParenLoc,
8019 SourceLocation EndLoc) {
8020 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008021 static_assert(OMPC_DEFAULT_unknown > 0,
8022 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008023 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008024 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8025 /*Last=*/OMPC_DEFAULT_unknown)
8026 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008027 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008028 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008029 switch (Kind) {
8030 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008031 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008032 break;
8033 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008034 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008035 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008036 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008037 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008038 break;
8039 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008040 return new (Context)
8041 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008042}
8043
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008044OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8045 SourceLocation KindKwLoc,
8046 SourceLocation StartLoc,
8047 SourceLocation LParenLoc,
8048 SourceLocation EndLoc) {
8049 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008050 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008051 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8052 /*Last=*/OMPC_PROC_BIND_unknown)
8053 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008054 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008055 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008056 return new (Context)
8057 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008058}
8059
Alexey Bataev56dafe82014-06-20 07:16:17 +00008060OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008061 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008062 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008063 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008064 SourceLocation EndLoc) {
8065 OMPClause *Res = nullptr;
8066 switch (Kind) {
8067 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008068 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8069 assert(Argument.size() == NumberOfElements &&
8070 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008071 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008072 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8073 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8074 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8075 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8076 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008077 break;
8078 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008079 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8080 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8081 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8082 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008083 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008084 case OMPC_dist_schedule:
8085 Res = ActOnOpenMPDistScheduleClause(
8086 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8087 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8088 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008089 case OMPC_defaultmap:
8090 enum { Modifier, DefaultmapKind };
8091 Res = ActOnOpenMPDefaultmapClause(
8092 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8093 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008094 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8095 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008096 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008097 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008098 case OMPC_num_threads:
8099 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008100 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008101 case OMPC_collapse:
8102 case OMPC_default:
8103 case OMPC_proc_bind:
8104 case OMPC_private:
8105 case OMPC_firstprivate:
8106 case OMPC_lastprivate:
8107 case OMPC_shared:
8108 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008109 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008110 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008111 case OMPC_linear:
8112 case OMPC_aligned:
8113 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008114 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008115 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008116 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008117 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008118 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008119 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008120 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008121 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008122 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008123 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008124 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008125 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008126 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008127 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008128 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008129 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008130 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008131 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008132 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008133 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008134 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008135 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008136 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008137 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008138 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008139 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008140 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008141 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008142 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008143 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008144 llvm_unreachable("Clause is not allowed.");
8145 }
8146 return Res;
8147}
8148
Alexey Bataev6402bca2015-12-28 07:25:51 +00008149static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8150 OpenMPScheduleClauseModifier M2,
8151 SourceLocation M1Loc, SourceLocation M2Loc) {
8152 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8153 SmallVector<unsigned, 2> Excluded;
8154 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8155 Excluded.push_back(M2);
8156 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8157 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8158 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8159 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8160 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8161 << getListOfPossibleValues(OMPC_schedule,
8162 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8163 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8164 Excluded)
8165 << getOpenMPClauseName(OMPC_schedule);
8166 return true;
8167 }
8168 return false;
8169}
8170
Alexey Bataev56dafe82014-06-20 07:16:17 +00008171OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008172 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008173 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008174 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8175 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8176 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8177 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8178 return nullptr;
8179 // OpenMP, 2.7.1, Loop Construct, Restrictions
8180 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8181 // but not both.
8182 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8183 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8184 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8185 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8186 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8187 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8188 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8189 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8190 return nullptr;
8191 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008192 if (Kind == OMPC_SCHEDULE_unknown) {
8193 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008194 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8195 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8196 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8197 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8198 Exclude);
8199 } else {
8200 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8201 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008202 }
8203 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8204 << Values << getOpenMPClauseName(OMPC_schedule);
8205 return nullptr;
8206 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008207 // OpenMP, 2.7.1, Loop Construct, Restrictions
8208 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8209 // schedule(guided).
8210 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8211 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8212 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8213 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8214 diag::err_omp_schedule_nonmonotonic_static);
8215 return nullptr;
8216 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008217 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008218 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008219 if (ChunkSize) {
8220 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8221 !ChunkSize->isInstantiationDependent() &&
8222 !ChunkSize->containsUnexpandedParameterPack()) {
8223 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8224 ExprResult Val =
8225 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8226 if (Val.isInvalid())
8227 return nullptr;
8228
8229 ValExpr = Val.get();
8230
8231 // OpenMP [2.7.1, Restrictions]
8232 // chunk_size must be a loop invariant integer expression with a positive
8233 // value.
8234 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008235 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8236 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8237 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008238 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008239 return nullptr;
8240 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008241 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
8242 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008243 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8244 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8245 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008246 }
8247 }
8248 }
8249
Alexey Bataev6402bca2015-12-28 07:25:51 +00008250 return new (Context)
8251 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008252 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008253}
8254
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008255OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8256 SourceLocation StartLoc,
8257 SourceLocation EndLoc) {
8258 OMPClause *Res = nullptr;
8259 switch (Kind) {
8260 case OMPC_ordered:
8261 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8262 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008263 case OMPC_nowait:
8264 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8265 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008266 case OMPC_untied:
8267 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8268 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008269 case OMPC_mergeable:
8270 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8271 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008272 case OMPC_read:
8273 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8274 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008275 case OMPC_write:
8276 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8277 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008278 case OMPC_update:
8279 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8280 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008281 case OMPC_capture:
8282 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8283 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008284 case OMPC_seq_cst:
8285 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8286 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008287 case OMPC_threads:
8288 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8289 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008290 case OMPC_simd:
8291 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8292 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008293 case OMPC_nogroup:
8294 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8295 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008296 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008297 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008298 case OMPC_num_threads:
8299 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008300 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008301 case OMPC_collapse:
8302 case OMPC_schedule:
8303 case OMPC_private:
8304 case OMPC_firstprivate:
8305 case OMPC_lastprivate:
8306 case OMPC_shared:
8307 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008308 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008309 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008310 case OMPC_linear:
8311 case OMPC_aligned:
8312 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008313 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008314 case OMPC_default:
8315 case OMPC_proc_bind:
8316 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008317 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008318 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008319 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008320 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008321 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008322 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008323 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008324 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008325 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008326 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008327 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008328 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008329 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008330 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008331 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008332 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008333 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008334 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008335 llvm_unreachable("Clause is not allowed.");
8336 }
8337 return Res;
8338}
8339
Alexey Bataev236070f2014-06-20 11:19:47 +00008340OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8341 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008342 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008343 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8344}
8345
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008346OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8347 SourceLocation EndLoc) {
8348 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8349}
8350
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008351OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8352 SourceLocation EndLoc) {
8353 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8354}
8355
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008356OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8357 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008358 return new (Context) OMPReadClause(StartLoc, EndLoc);
8359}
8360
Alexey Bataevdea47612014-07-23 07:46:59 +00008361OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8362 SourceLocation EndLoc) {
8363 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8364}
8365
Alexey Bataev67a4f222014-07-23 10:25:33 +00008366OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8367 SourceLocation EndLoc) {
8368 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8369}
8370
Alexey Bataev459dec02014-07-24 06:46:57 +00008371OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8372 SourceLocation EndLoc) {
8373 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8374}
8375
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008376OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8377 SourceLocation EndLoc) {
8378 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8379}
8380
Alexey Bataev346265e2015-09-25 10:37:12 +00008381OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8382 SourceLocation EndLoc) {
8383 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8384}
8385
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008386OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8387 SourceLocation EndLoc) {
8388 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8389}
8390
Alexey Bataevb825de12015-12-07 10:51:44 +00008391OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8392 SourceLocation EndLoc) {
8393 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8394}
8395
Alexey Bataevc5e02582014-06-16 07:08:35 +00008396OMPClause *Sema::ActOnOpenMPVarListClause(
8397 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8398 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8399 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008400 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008401 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8402 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8403 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008404 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008405 switch (Kind) {
8406 case OMPC_private:
8407 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8408 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008409 case OMPC_firstprivate:
8410 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8411 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008412 case OMPC_lastprivate:
8413 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8414 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008415 case OMPC_shared:
8416 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8417 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008418 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008419 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8420 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008421 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008422 case OMPC_task_reduction:
8423 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8424 EndLoc, ReductionIdScopeSpec,
8425 ReductionId);
8426 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008427 case OMPC_in_reduction:
8428 Res =
8429 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8430 EndLoc, ReductionIdScopeSpec, ReductionId);
8431 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008432 case OMPC_linear:
8433 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008434 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008435 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008436 case OMPC_aligned:
8437 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8438 ColonLoc, EndLoc);
8439 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008440 case OMPC_copyin:
8441 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8442 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008443 case OMPC_copyprivate:
8444 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8445 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008446 case OMPC_flush:
8447 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8448 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008449 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008450 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008451 StartLoc, LParenLoc, EndLoc);
8452 break;
8453 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008454 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8455 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8456 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008457 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008458 case OMPC_to:
8459 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8460 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008461 case OMPC_from:
8462 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8463 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008464 case OMPC_use_device_ptr:
8465 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8466 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008467 case OMPC_is_device_ptr:
8468 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8469 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008470 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008471 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008472 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008473 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008474 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008475 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008476 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008477 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008478 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008479 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008480 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008481 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008482 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008483 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008484 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008485 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008486 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008487 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008488 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008489 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008490 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008491 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008492 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008493 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008494 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008495 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008496 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008497 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008498 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008499 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008500 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008501 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008502 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008503 llvm_unreachable("Clause is not allowed.");
8504 }
8505 return Res;
8506}
8507
Alexey Bataev90c228f2016-02-08 09:29:13 +00008508ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008509 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008510 ExprResult Res = BuildDeclRefExpr(
8511 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8512 if (!Res.isUsable())
8513 return ExprError();
8514 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8515 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8516 if (!Res.isUsable())
8517 return ExprError();
8518 }
8519 if (VK != VK_LValue && Res.get()->isGLValue()) {
8520 Res = DefaultLvalueConversion(Res.get());
8521 if (!Res.isUsable())
8522 return ExprError();
8523 }
8524 return Res;
8525}
8526
Alexey Bataev60da77e2016-02-29 05:54:20 +00008527static std::pair<ValueDecl *, bool>
8528getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8529 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008530 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8531 RefExpr->containsUnexpandedParameterPack())
8532 return std::make_pair(nullptr, true);
8533
Alexey Bataevd985eda2016-02-10 11:29:16 +00008534 // OpenMP [3.1, C/C++]
8535 // A list item is a variable name.
8536 // OpenMP [2.9.3.3, Restrictions, p.1]
8537 // A variable that is part of another variable (as an array or
8538 // structure element) cannot appear in a private clause.
8539 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008540 enum {
8541 NoArrayExpr = -1,
8542 ArraySubscript = 0,
8543 OMPArraySection = 1
8544 } IsArrayExpr = NoArrayExpr;
8545 if (AllowArraySection) {
8546 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8547 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8548 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8549 Base = TempASE->getBase()->IgnoreParenImpCasts();
8550 RefExpr = Base;
8551 IsArrayExpr = ArraySubscript;
8552 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8553 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8554 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8555 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8556 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8557 Base = TempASE->getBase()->IgnoreParenImpCasts();
8558 RefExpr = Base;
8559 IsArrayExpr = OMPArraySection;
8560 }
8561 }
8562 ELoc = RefExpr->getExprLoc();
8563 ERange = RefExpr->getSourceRange();
8564 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008565 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8566 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8567 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8568 (S.getCurrentThisType().isNull() || !ME ||
8569 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8570 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008571 if (IsArrayExpr != NoArrayExpr)
8572 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8573 << ERange;
8574 else {
8575 S.Diag(ELoc,
8576 AllowArraySection
8577 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8578 : diag::err_omp_expected_var_name_member_expr)
8579 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8580 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008581 return std::make_pair(nullptr, false);
8582 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008583 return std::make_pair(
8584 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008585}
8586
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008587OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8588 SourceLocation StartLoc,
8589 SourceLocation LParenLoc,
8590 SourceLocation EndLoc) {
8591 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008592 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008593 for (auto &RefExpr : VarList) {
8594 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008595 SourceLocation ELoc;
8596 SourceRange ERange;
8597 Expr *SimpleRefExpr = RefExpr;
8598 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008599 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008600 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008601 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008602 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008603 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008604 ValueDecl *D = Res.first;
8605 if (!D)
8606 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008607
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008608 QualType Type = D->getType();
8609 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008610
8611 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8612 // A variable that appears in a private clause must not have an incomplete
8613 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008614 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008615 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008616 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008617
Alexey Bataev758e55e2013-09-06 18:03:48 +00008618 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8619 // in a Construct]
8620 // Variables with the predetermined data-sharing attributes may not be
8621 // listed in data-sharing attributes clauses, except for the cases
8622 // listed below. For these exceptions only, listing a predetermined
8623 // variable in a data-sharing attribute clause is allowed and overrides
8624 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008625 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008626 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008627 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8628 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008629 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008630 continue;
8631 }
8632
Kelvin Libf594a52016-12-17 05:48:59 +00008633 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008634 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008635 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008636 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008637 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8638 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008639 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008640 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008641 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008642 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008643 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008644 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008645 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008646 continue;
8647 }
8648
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008649 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8650 // A list item cannot appear in both a map clause and a data-sharing
8651 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008652 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008653 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008654 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008655 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008656 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008657 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008658 CurrDir == OMPD_target_parallel_for_simd ||
8659 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008660 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008661 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008662 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008663 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8664 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8665 ConflictKind = WhereFoundClauseKind;
8666 return true;
8667 })) {
8668 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008669 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008670 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008671 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008672 ReportOriginalDSA(*this, DSAStack, D, DVar);
8673 continue;
8674 }
8675 }
8676
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008677 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8678 // A variable of class type (or array thereof) that appears in a private
8679 // clause requires an accessible, unambiguous default constructor for the
8680 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008681 // Generate helper private variable and initialize it with the default
8682 // value. The address of the original variable is replaced by the address of
8683 // the new private variable in CodeGen. This new variable is not added to
8684 // IdResolver, so the code in the OpenMP region uses original variable for
8685 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008686 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008687 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8688 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008689 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008690 if (VDPrivate->isInvalidDecl())
8691 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008692 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008693 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008694
Alexey Bataev90c228f2016-02-08 09:29:13 +00008695 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008696 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008697 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008698 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008699 Vars.push_back((VD || CurContext->isDependentContext())
8700 ? RefExpr->IgnoreParens()
8701 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008702 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008703 }
8704
Alexey Bataeved09d242014-05-28 05:53:51 +00008705 if (Vars.empty())
8706 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008707
Alexey Bataev03b340a2014-10-21 03:16:40 +00008708 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8709 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008710}
8711
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008712namespace {
8713class DiagsUninitializedSeveretyRAII {
8714private:
8715 DiagnosticsEngine &Diags;
8716 SourceLocation SavedLoc;
8717 bool IsIgnored;
8718
8719public:
8720 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8721 bool IsIgnored)
8722 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8723 if (!IsIgnored) {
8724 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8725 /*Map*/ diag::Severity::Ignored, Loc);
8726 }
8727 }
8728 ~DiagsUninitializedSeveretyRAII() {
8729 if (!IsIgnored)
8730 Diags.popMappings(SavedLoc);
8731 }
8732};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008733}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008734
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008735OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8736 SourceLocation StartLoc,
8737 SourceLocation LParenLoc,
8738 SourceLocation EndLoc) {
8739 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008740 SmallVector<Expr *, 8> PrivateCopies;
8741 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008742 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008743 bool IsImplicitClause =
8744 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8745 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8746
Alexey Bataeved09d242014-05-28 05:53:51 +00008747 for (auto &RefExpr : VarList) {
8748 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008749 SourceLocation ELoc;
8750 SourceRange ERange;
8751 Expr *SimpleRefExpr = RefExpr;
8752 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008753 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008754 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008755 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008756 PrivateCopies.push_back(nullptr);
8757 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008758 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008759 ValueDecl *D = Res.first;
8760 if (!D)
8761 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008762
Alexey Bataev60da77e2016-02-29 05:54:20 +00008763 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008764 QualType Type = D->getType();
8765 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008766
8767 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8768 // A variable that appears in a private clause must not have an incomplete
8769 // type or a reference type.
8770 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008771 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008772 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008773 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008774
8775 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8776 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008777 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008778 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008779 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008780
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008781 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008782 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008783 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008784 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008785 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008786 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008787 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008788 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8789 // A list item that specifies a given variable may not appear in more
8790 // than one clause on the same directive, except that a variable may be
8791 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008792 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8793 // A list item may appear in a firstprivate or lastprivate clause but not
8794 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008795 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008796 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8797 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008798 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008799 << getOpenMPClauseName(DVar.CKind)
8800 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008801 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008802 continue;
8803 }
8804
8805 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8806 // in a Construct]
8807 // Variables with the predetermined data-sharing attributes may not be
8808 // listed in data-sharing attributes clauses, except for the cases
8809 // listed below. For these exceptions only, listing a predetermined
8810 // variable in a data-sharing attribute clause is allowed and overrides
8811 // the variable's predetermined data-sharing attributes.
8812 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8813 // in a Construct, C/C++, p.2]
8814 // Variables with const-qualified type having no mutable member may be
8815 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008816 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008817 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8818 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008819 << getOpenMPClauseName(DVar.CKind)
8820 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008821 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008822 continue;
8823 }
8824
8825 // OpenMP [2.9.3.4, Restrictions, p.2]
8826 // A list item that is private within a parallel region must not appear
8827 // in a firstprivate clause on a worksharing construct if any of the
8828 // worksharing regions arising from the worksharing construct ever bind
8829 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008830 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8831 // A list item that is private within a teams region must not appear in a
8832 // firstprivate clause on a distribute construct if any of the distribute
8833 // regions arising from the distribute construct ever bind to any of the
8834 // teams regions arising from the teams construct.
8835 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8836 // A list item that appears in a reduction clause of a teams construct
8837 // must not appear in a firstprivate clause on a distribute construct if
8838 // any of the distribute regions arising from the distribute construct
8839 // ever bind to any of the teams regions arising from the teams construct.
8840 if ((isOpenMPWorksharingDirective(CurrDir) ||
8841 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008842 !isOpenMPParallelDirective(CurrDir) &&
8843 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008844 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008845 if (DVar.CKind != OMPC_shared &&
8846 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008847 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008848 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008849 Diag(ELoc, diag::err_omp_required_access)
8850 << getOpenMPClauseName(OMPC_firstprivate)
8851 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008852 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008853 continue;
8854 }
8855 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008856 // OpenMP [2.9.3.4, Restrictions, p.3]
8857 // A list item that appears in a reduction clause of a parallel construct
8858 // must not appear in a firstprivate clause on a worksharing or task
8859 // construct if any of the worksharing or task regions arising from the
8860 // worksharing or task construct ever bind to any of the parallel regions
8861 // arising from the parallel construct.
8862 // OpenMP [2.9.3.4, Restrictions, p.4]
8863 // A list item that appears in a reduction clause in worksharing
8864 // construct must not appear in a firstprivate clause in a task construct
8865 // encountered during execution of any of the worksharing regions arising
8866 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008867 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008868 DVar = DSAStack->hasInnermostDSA(
8869 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8870 [](OpenMPDirectiveKind K) -> bool {
8871 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008872 isOpenMPWorksharingDirective(K) ||
8873 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008874 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008875 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008876 if (DVar.CKind == OMPC_reduction &&
8877 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008878 isOpenMPWorksharingDirective(DVar.DKind) ||
8879 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008880 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8881 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008882 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008883 continue;
8884 }
8885 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008886
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008887 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8888 // A list item cannot appear in both a map clause and a data-sharing
8889 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008890 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008891 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008892 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008893 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008894 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008895 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008896 CurrDir == OMPD_target_parallel_for_simd ||
8897 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008898 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008899 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008900 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008901 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8902 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8903 ConflictKind = WhereFoundClauseKind;
8904 return true;
8905 })) {
8906 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008907 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008908 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008909 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8910 ReportOriginalDSA(*this, DSAStack, D, DVar);
8911 continue;
8912 }
8913 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008914 }
8915
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008916 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008917 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008918 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008919 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8920 << getOpenMPClauseName(OMPC_firstprivate) << Type
8921 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8922 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008923 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008924 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008925 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008926 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008927 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008928 continue;
8929 }
8930
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008931 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008932 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8933 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008934 // Generate helper private variable and initialize it with the value of the
8935 // original variable. The address of the original variable is replaced by
8936 // the address of the new private variable in the CodeGen. This new variable
8937 // is not added to IdResolver, so the code in the OpenMP region uses
8938 // original variable for proper diagnostics and variable capturing.
8939 Expr *VDInitRefExpr = nullptr;
8940 // For arrays generate initializer for single element and replace it by the
8941 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008942 if (Type->isArrayType()) {
8943 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008944 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008945 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008946 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008947 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008948 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008949 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008950 InitializedEntity Entity =
8951 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008952 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8953
8954 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8955 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8956 if (Result.isInvalid())
8957 VDPrivate->setInvalidDecl();
8958 else
8959 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008960 // Remove temp variable declaration.
8961 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008962 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008963 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8964 ".firstprivate.temp");
8965 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8966 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008967 AddInitializerToDecl(VDPrivate,
8968 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008969 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008970 }
8971 if (VDPrivate->isInvalidDecl()) {
8972 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008973 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008974 diag::note_omp_task_predetermined_firstprivate_here);
8975 }
8976 continue;
8977 }
8978 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008979 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008980 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8981 RefExpr->getExprLoc());
8982 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008983 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008984 if (TopDVar.CKind == OMPC_lastprivate)
8985 Ref = TopDVar.PrivateCopy;
8986 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008987 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008988 if (!IsOpenMPCapturedDecl(D))
8989 ExprCaptures.push_back(Ref->getDecl());
8990 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008991 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008992 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008993 Vars.push_back((VD || CurContext->isDependentContext())
8994 ? RefExpr->IgnoreParens()
8995 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008996 PrivateCopies.push_back(VDPrivateRefExpr);
8997 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008998 }
8999
Alexey Bataeved09d242014-05-28 05:53:51 +00009000 if (Vars.empty())
9001 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009002
9003 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009004 Vars, PrivateCopies, Inits,
9005 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009006}
9007
Alexander Musman1bb328c2014-06-04 13:06:39 +00009008OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9009 SourceLocation StartLoc,
9010 SourceLocation LParenLoc,
9011 SourceLocation EndLoc) {
9012 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009013 SmallVector<Expr *, 8> SrcExprs;
9014 SmallVector<Expr *, 8> DstExprs;
9015 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009016 SmallVector<Decl *, 4> ExprCaptures;
9017 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009018 for (auto &RefExpr : VarList) {
9019 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009020 SourceLocation ELoc;
9021 SourceRange ERange;
9022 Expr *SimpleRefExpr = RefExpr;
9023 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009024 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009025 // It will be analyzed later.
9026 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009027 SrcExprs.push_back(nullptr);
9028 DstExprs.push_back(nullptr);
9029 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009030 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009031 ValueDecl *D = Res.first;
9032 if (!D)
9033 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009034
Alexey Bataev74caaf22016-02-20 04:09:36 +00009035 QualType Type = D->getType();
9036 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009037
9038 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9039 // A variable that appears in a lastprivate clause must not have an
9040 // incomplete type or a reference type.
9041 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009042 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009043 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009044 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009045
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009046 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009047 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9048 // in a Construct]
9049 // Variables with the predetermined data-sharing attributes may not be
9050 // listed in data-sharing attributes clauses, except for the cases
9051 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009052 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9053 // A list item may appear in a firstprivate or lastprivate clause but not
9054 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009055 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009056 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009057 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009058 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9059 Diag(ELoc, diag::err_omp_wrong_dsa)
9060 << getOpenMPClauseName(DVar.CKind)
9061 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009062 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009063 continue;
9064 }
9065
Alexey Bataevf29276e2014-06-18 04:14:57 +00009066 // OpenMP [2.14.3.5, Restrictions, p.2]
9067 // A list item that is private within a parallel region, or that appears in
9068 // the reduction clause of a parallel construct, must not appear in a
9069 // lastprivate clause on a worksharing construct if any of the corresponding
9070 // worksharing regions ever binds to any of the corresponding parallel
9071 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009072 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009073 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009074 !isOpenMPParallelDirective(CurrDir) &&
9075 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009076 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009077 if (DVar.CKind != OMPC_shared) {
9078 Diag(ELoc, diag::err_omp_required_access)
9079 << getOpenMPClauseName(OMPC_lastprivate)
9080 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009081 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009082 continue;
9083 }
9084 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009085
Alexander Musman1bb328c2014-06-04 13:06:39 +00009086 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009087 // A variable of class type (or array thereof) that appears in a
9088 // lastprivate clause requires an accessible, unambiguous default
9089 // constructor for the class type, unless the list item is also specified
9090 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009091 // A variable of class type (or array thereof) that appears in a
9092 // lastprivate clause requires an accessible, unambiguous copy assignment
9093 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009094 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009095 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009096 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009097 D->hasAttrs() ? &D->getAttrs() : nullptr);
9098 auto *PseudoSrcExpr =
9099 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009100 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009101 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009102 D->hasAttrs() ? &D->getAttrs() : nullptr);
9103 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009104 // For arrays generate assignment operation for single element and replace
9105 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009106 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009107 PseudoDstExpr, PseudoSrcExpr);
9108 if (AssignmentOp.isInvalid())
9109 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009110 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009111 /*DiscardedValue=*/true);
9112 if (AssignmentOp.isInvalid())
9113 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009114
Alexey Bataev74caaf22016-02-20 04:09:36 +00009115 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009116 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009117 if (TopDVar.CKind == OMPC_firstprivate)
9118 Ref = TopDVar.PrivateCopy;
9119 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009120 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009121 if (!IsOpenMPCapturedDecl(D))
9122 ExprCaptures.push_back(Ref->getDecl());
9123 }
9124 if (TopDVar.CKind == OMPC_firstprivate ||
9125 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009126 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009127 ExprResult RefRes = DefaultLvalueConversion(Ref);
9128 if (!RefRes.isUsable())
9129 continue;
9130 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009131 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9132 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009133 if (!PostUpdateRes.isUsable())
9134 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009135 ExprPostUpdates.push_back(
9136 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009137 }
9138 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009139 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009140 Vars.push_back((VD || CurContext->isDependentContext())
9141 ? RefExpr->IgnoreParens()
9142 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009143 SrcExprs.push_back(PseudoSrcExpr);
9144 DstExprs.push_back(PseudoDstExpr);
9145 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009146 }
9147
9148 if (Vars.empty())
9149 return nullptr;
9150
9151 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009152 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009153 buildPreInits(Context, ExprCaptures),
9154 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009155}
9156
Alexey Bataev758e55e2013-09-06 18:03:48 +00009157OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9158 SourceLocation StartLoc,
9159 SourceLocation LParenLoc,
9160 SourceLocation EndLoc) {
9161 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009162 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009163 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009164 SourceLocation ELoc;
9165 SourceRange ERange;
9166 Expr *SimpleRefExpr = RefExpr;
9167 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009168 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009169 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009170 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009171 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009172 ValueDecl *D = Res.first;
9173 if (!D)
9174 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009175
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009176 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009177 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9178 // in a Construct]
9179 // Variables with the predetermined data-sharing attributes may not be
9180 // listed in data-sharing attributes clauses, except for the cases
9181 // listed below. For these exceptions only, listing a predetermined
9182 // variable in a data-sharing attribute clause is allowed and overrides
9183 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009184 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009185 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9186 DVar.RefExpr) {
9187 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9188 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009189 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009190 continue;
9191 }
9192
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009193 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009194 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009195 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009196 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009197 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9198 ? RefExpr->IgnoreParens()
9199 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009200 }
9201
Alexey Bataeved09d242014-05-28 05:53:51 +00009202 if (Vars.empty())
9203 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009204
9205 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9206}
9207
Alexey Bataevc5e02582014-06-16 07:08:35 +00009208namespace {
9209class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9210 DSAStackTy *Stack;
9211
9212public:
9213 bool VisitDeclRefExpr(DeclRefExpr *E) {
9214 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009215 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009216 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9217 return false;
9218 if (DVar.CKind != OMPC_unknown)
9219 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009220 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9221 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009222 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009223 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009224 return true;
9225 return false;
9226 }
9227 return false;
9228 }
9229 bool VisitStmt(Stmt *S) {
9230 for (auto Child : S->children()) {
9231 if (Child && Visit(Child))
9232 return true;
9233 }
9234 return false;
9235 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009236 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009237};
Alexey Bataev23b69422014-06-18 07:08:49 +00009238} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009239
Alexey Bataev60da77e2016-02-29 05:54:20 +00009240namespace {
9241// Transform MemberExpression for specified FieldDecl of current class to
9242// DeclRefExpr to specified OMPCapturedExprDecl.
9243class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9244 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9245 ValueDecl *Field;
9246 DeclRefExpr *CapturedExpr;
9247
9248public:
9249 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9250 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9251
9252 ExprResult TransformMemberExpr(MemberExpr *E) {
9253 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9254 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009255 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009256 return CapturedExpr;
9257 }
9258 return BaseTransform::TransformMemberExpr(E);
9259 }
9260 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9261};
9262} // namespace
9263
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009264template <typename T>
9265static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9266 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9267 for (auto &Set : Lookups) {
9268 for (auto *D : Set) {
9269 if (auto Res = Gen(cast<ValueDecl>(D)))
9270 return Res;
9271 }
9272 }
9273 return T();
9274}
9275
9276static ExprResult
9277buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9278 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9279 const DeclarationNameInfo &ReductionId, QualType Ty,
9280 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9281 if (ReductionIdScopeSpec.isInvalid())
9282 return ExprError();
9283 SmallVector<UnresolvedSet<8>, 4> Lookups;
9284 if (S) {
9285 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9286 Lookup.suppressDiagnostics();
9287 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9288 auto *D = Lookup.getRepresentativeDecl();
9289 do {
9290 S = S->getParent();
9291 } while (S && !S->isDeclScope(D));
9292 if (S)
9293 S = S->getParent();
9294 Lookups.push_back(UnresolvedSet<8>());
9295 Lookups.back().append(Lookup.begin(), Lookup.end());
9296 Lookup.clear();
9297 }
9298 } else if (auto *ULE =
9299 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9300 Lookups.push_back(UnresolvedSet<8>());
9301 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009302 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009303 if (D == PrevD)
9304 Lookups.push_back(UnresolvedSet<8>());
9305 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9306 Lookups.back().addDecl(DRD);
9307 PrevD = D;
9308 }
9309 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009310 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9311 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009312 Ty->containsUnexpandedParameterPack() ||
9313 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9314 return !D->isInvalidDecl() &&
9315 (D->getType()->isDependentType() ||
9316 D->getType()->isInstantiationDependentType() ||
9317 D->getType()->containsUnexpandedParameterPack());
9318 })) {
9319 UnresolvedSet<8> ResSet;
9320 for (auto &Set : Lookups) {
9321 ResSet.append(Set.begin(), Set.end());
9322 // The last item marks the end of all declarations at the specified scope.
9323 ResSet.addDecl(Set[Set.size() - 1]);
9324 }
9325 return UnresolvedLookupExpr::Create(
9326 SemaRef.Context, /*NamingClass=*/nullptr,
9327 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9328 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9329 }
9330 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9331 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9332 if (!D->isInvalidDecl() &&
9333 SemaRef.Context.hasSameType(D->getType(), Ty))
9334 return D;
9335 return nullptr;
9336 }))
9337 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9338 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9339 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9340 if (!D->isInvalidDecl() &&
9341 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9342 !Ty.isMoreQualifiedThan(D->getType()))
9343 return D;
9344 return nullptr;
9345 })) {
9346 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9347 /*DetectVirtual=*/false);
9348 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9349 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9350 VD->getType().getUnqualifiedType()))) {
9351 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9352 /*DiagID=*/0) !=
9353 Sema::AR_inaccessible) {
9354 SemaRef.BuildBasePathArray(Paths, BasePath);
9355 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9356 }
9357 }
9358 }
9359 }
9360 if (ReductionIdScopeSpec.isSet()) {
9361 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9362 return ExprError();
9363 }
9364 return ExprEmpty();
9365}
9366
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009367namespace {
9368/// Data for the reduction-based clauses.
9369struct ReductionData {
9370 /// List of original reduction items.
9371 SmallVector<Expr *, 8> Vars;
9372 /// List of private copies of the reduction items.
9373 SmallVector<Expr *, 8> Privates;
9374 /// LHS expressions for the reduction_op expressions.
9375 SmallVector<Expr *, 8> LHSs;
9376 /// RHS expressions for the reduction_op expressions.
9377 SmallVector<Expr *, 8> RHSs;
9378 /// Reduction operation expression.
9379 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009380 /// Taskgroup descriptors for the corresponding reduction items in
9381 /// in_reduction clauses.
9382 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009383 /// List of captures for clause.
9384 SmallVector<Decl *, 4> ExprCaptures;
9385 /// List of postupdate expressions.
9386 SmallVector<Expr *, 4> ExprPostUpdates;
9387 ReductionData() = delete;
9388 /// Reserves required memory for the reduction data.
9389 ReductionData(unsigned Size) {
9390 Vars.reserve(Size);
9391 Privates.reserve(Size);
9392 LHSs.reserve(Size);
9393 RHSs.reserve(Size);
9394 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009395 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009396 ExprCaptures.reserve(Size);
9397 ExprPostUpdates.reserve(Size);
9398 }
9399 /// Stores reduction item and reduction operation only (required for dependent
9400 /// reduction item).
9401 void push(Expr *Item, Expr *ReductionOp) {
9402 Vars.emplace_back(Item);
9403 Privates.emplace_back(nullptr);
9404 LHSs.emplace_back(nullptr);
9405 RHSs.emplace_back(nullptr);
9406 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009407 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009408 }
9409 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009410 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9411 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009412 Vars.emplace_back(Item);
9413 Privates.emplace_back(Private);
9414 LHSs.emplace_back(LHS);
9415 RHSs.emplace_back(RHS);
9416 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009417 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009418 }
9419};
9420} // namespace
9421
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009422static bool CheckOMPArraySectionConstantForReduction(
9423 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9424 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9425 const Expr *Length = OASE->getLength();
9426 if (Length == nullptr) {
9427 // For array sections of the form [1:] or [:], we would need to analyze
9428 // the lower bound...
9429 if (OASE->getColonLoc().isValid())
9430 return false;
9431
9432 // This is an array subscript which has implicit length 1!
9433 SingleElement = true;
9434 ArraySizes.push_back(llvm::APSInt::get(1));
9435 } else {
9436 llvm::APSInt ConstantLengthValue;
9437 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9438 return false;
9439
9440 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9441 ArraySizes.push_back(ConstantLengthValue);
9442 }
9443
9444 // Get the base of this array section and walk up from there.
9445 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9446
9447 // We require length = 1 for all array sections except the right-most to
9448 // guarantee that the memory region is contiguous and has no holes in it.
9449 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9450 Length = TempOASE->getLength();
9451 if (Length == nullptr) {
9452 // For array sections of the form [1:] or [:], we would need to analyze
9453 // the lower bound...
9454 if (OASE->getColonLoc().isValid())
9455 return false;
9456
9457 // This is an array subscript which has implicit length 1!
9458 ArraySizes.push_back(llvm::APSInt::get(1));
9459 } else {
9460 llvm::APSInt ConstantLengthValue;
9461 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9462 ConstantLengthValue.getSExtValue() != 1)
9463 return false;
9464
9465 ArraySizes.push_back(ConstantLengthValue);
9466 }
9467 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9468 }
9469
9470 // If we have a single element, we don't need to add the implicit lengths.
9471 if (!SingleElement) {
9472 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9473 // Has implicit length 1!
9474 ArraySizes.push_back(llvm::APSInt::get(1));
9475 Base = TempASE->getBase()->IgnoreParenImpCasts();
9476 }
9477 }
9478
9479 // This array section can be privatized as a single value or as a constant
9480 // sized array.
9481 return true;
9482}
9483
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009484static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009485 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9486 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9487 SourceLocation ColonLoc, SourceLocation EndLoc,
9488 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009489 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009490 auto DN = ReductionId.getName();
9491 auto OOK = DN.getCXXOverloadedOperator();
9492 BinaryOperatorKind BOK = BO_Comma;
9493
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009494 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009495 // OpenMP [2.14.3.6, reduction clause]
9496 // C
9497 // reduction-identifier is either an identifier or one of the following
9498 // operators: +, -, *, &, |, ^, && and ||
9499 // C++
9500 // reduction-identifier is either an id-expression or one of the following
9501 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009502 switch (OOK) {
9503 case OO_Plus:
9504 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009505 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009506 break;
9507 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009508 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009509 break;
9510 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009511 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009512 break;
9513 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009514 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009515 break;
9516 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009517 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009518 break;
9519 case OO_AmpAmp:
9520 BOK = BO_LAnd;
9521 break;
9522 case OO_PipePipe:
9523 BOK = BO_LOr;
9524 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009525 case OO_New:
9526 case OO_Delete:
9527 case OO_Array_New:
9528 case OO_Array_Delete:
9529 case OO_Slash:
9530 case OO_Percent:
9531 case OO_Tilde:
9532 case OO_Exclaim:
9533 case OO_Equal:
9534 case OO_Less:
9535 case OO_Greater:
9536 case OO_LessEqual:
9537 case OO_GreaterEqual:
9538 case OO_PlusEqual:
9539 case OO_MinusEqual:
9540 case OO_StarEqual:
9541 case OO_SlashEqual:
9542 case OO_PercentEqual:
9543 case OO_CaretEqual:
9544 case OO_AmpEqual:
9545 case OO_PipeEqual:
9546 case OO_LessLess:
9547 case OO_GreaterGreater:
9548 case OO_LessLessEqual:
9549 case OO_GreaterGreaterEqual:
9550 case OO_EqualEqual:
9551 case OO_ExclaimEqual:
9552 case OO_PlusPlus:
9553 case OO_MinusMinus:
9554 case OO_Comma:
9555 case OO_ArrowStar:
9556 case OO_Arrow:
9557 case OO_Call:
9558 case OO_Subscript:
9559 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009560 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009561 case NUM_OVERLOADED_OPERATORS:
9562 llvm_unreachable("Unexpected reduction identifier");
9563 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009564 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009565 if (II->isStr("max"))
9566 BOK = BO_GT;
9567 else if (II->isStr("min"))
9568 BOK = BO_LT;
9569 }
9570 break;
9571 }
9572 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009573 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009574 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009575 else
9576 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009577 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009578
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009579 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9580 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009581 for (auto RefExpr : VarList) {
9582 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009583 // OpenMP [2.1, C/C++]
9584 // A list item is a variable or array section, subject to the restrictions
9585 // specified in Section 2.4 on page 42 and in each of the sections
9586 // describing clauses and directives for which a list appears.
9587 // OpenMP [2.14.3.3, Restrictions, p.1]
9588 // A variable that is part of another variable (as an array or
9589 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009590 if (!FirstIter && IR != ER)
9591 ++IR;
9592 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009593 SourceLocation ELoc;
9594 SourceRange ERange;
9595 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009596 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009597 /*AllowArraySection=*/true);
9598 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009599 // Try to find 'declare reduction' corresponding construct before using
9600 // builtin/overloaded operators.
9601 QualType Type = Context.DependentTy;
9602 CXXCastPath BasePath;
9603 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009604 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009605 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009606 Expr *ReductionOp = nullptr;
9607 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009608 (DeclareReductionRef.isUnset() ||
9609 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009610 ReductionOp = DeclareReductionRef.get();
9611 // It will be analyzed later.
9612 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009613 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009614 ValueDecl *D = Res.first;
9615 if (!D)
9616 continue;
9617
Alexey Bataev88202be2017-07-27 13:20:36 +00009618 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009619 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009620 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9621 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9622 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009623 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009624 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009625 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9626 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9627 Type = ATy->getElementType();
9628 else
9629 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009630 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009631 } else
9632 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9633 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009634
Alexey Bataevc5e02582014-06-16 07:08:35 +00009635 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9636 // A variable that appears in a private clause must not have an incomplete
9637 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009638 if (S.RequireCompleteType(ELoc, Type,
9639 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009640 continue;
9641 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009642 // A list item that appears in a reduction clause must not be
9643 // const-qualified.
9644 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009645 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009646 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009647 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9648 VarDecl::DeclarationOnly;
9649 S.Diag(D->getLocation(),
9650 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009651 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009652 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009653 continue;
9654 }
9655 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9656 // If a list-item is a reference type then it must bind to the same object
9657 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009658 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009659 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009660 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009661 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009662 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009663 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9664 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009665 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009666 continue;
9667 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009668 }
9669 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009670
Alexey Bataevc5e02582014-06-16 07:08:35 +00009671 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9672 // in a Construct]
9673 // Variables with the predetermined data-sharing attributes may not be
9674 // listed in data-sharing attributes clauses, except for the cases
9675 // listed below. For these exceptions only, listing a predetermined
9676 // variable in a data-sharing attribute clause is allowed and overrides
9677 // the variable's predetermined data-sharing attributes.
9678 // OpenMP [2.14.3.6, Restrictions, p.3]
9679 // Any number of reduction clauses can be specified on the directive,
9680 // but a list item can appear only once in the reduction clauses for that
9681 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009682 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009683 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009684 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009685 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009686 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009687 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009688 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009689 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009690 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009691 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009692 << getOpenMPClauseName(DVar.CKind)
9693 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009694 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009695 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009696 }
9697
9698 // OpenMP [2.14.3.6, Restrictions, p.1]
9699 // A list item that appears in a reduction clause of a worksharing
9700 // construct must be shared in the parallel regions to which any of the
9701 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009702 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009703 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009704 !isOpenMPParallelDirective(CurrDir) &&
9705 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009706 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009707 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009708 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009709 << getOpenMPClauseName(OMPC_reduction)
9710 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009711 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009712 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009713 }
9714 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009715
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009716 // Try to find 'declare reduction' corresponding construct before using
9717 // builtin/overloaded operators.
9718 CXXCastPath BasePath;
9719 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009720 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009721 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9722 if (DeclareReductionRef.isInvalid())
9723 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009724 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009725 (DeclareReductionRef.isUnset() ||
9726 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009727 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009728 continue;
9729 }
9730 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9731 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009732 S.Diag(ReductionId.getLocStart(),
9733 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009734 << Type << ReductionIdRange;
9735 continue;
9736 }
9737
9738 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9739 // The type of a list item that appears in a reduction clause must be valid
9740 // for the reduction-identifier. For a max or min reduction in C, the type
9741 // of the list item must be an allowed arithmetic data type: char, int,
9742 // float, double, or _Bool, possibly modified with long, short, signed, or
9743 // unsigned. For a max or min reduction in C++, the type of the list item
9744 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9745 // double, or bool, possibly modified with long, short, signed, or unsigned.
9746 if (DeclareReductionRef.isUnset()) {
9747 if ((BOK == BO_GT || BOK == BO_LT) &&
9748 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009749 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9750 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009751 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009752 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009753 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9754 VarDecl::DeclarationOnly;
9755 S.Diag(D->getLocation(),
9756 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009757 << D;
9758 }
9759 continue;
9760 }
9761 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009762 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009763 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9764 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009765 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009766 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9767 VarDecl::DeclarationOnly;
9768 S.Diag(D->getLocation(),
9769 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009770 << D;
9771 }
9772 continue;
9773 }
9774 }
9775
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009776 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009777 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009778 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009779 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009780 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009781 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009782
9783 // Try if we can determine constant lengths for all array sections and avoid
9784 // the VLA.
9785 bool ConstantLengthOASE = false;
9786 if (OASE) {
9787 bool SingleElement;
9788 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
9789 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
9790 Context, OASE, SingleElement, ArraySizes);
9791
9792 // If we don't have a single element, we must emit a constant array type.
9793 if (ConstantLengthOASE && !SingleElement) {
9794 for (auto &Size : ArraySizes) {
9795 PrivateTy = Context.getConstantArrayType(
9796 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
9797 }
9798 }
9799 }
9800
9801 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +00009802 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +00009803 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009804 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009805 // Create pseudo array type for private copy. The size for this array will
9806 // be generated during codegen.
9807 // For array subscripts or single variables Private Ty is the same as Type
9808 // (type of the variable or single array element).
9809 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009810 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +00009811 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009812 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009813 } else if (!ASE && !OASE &&
9814 Context.getAsArrayType(D->getType().getNonReferenceType()))
9815 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009816 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009817 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009818 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009819 // Add initializer for private variable.
9820 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009821 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9822 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009823 if (DeclareReductionRef.isUsable()) {
9824 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9825 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9826 if (DRD->getInitializer()) {
9827 Init = DRDRef;
9828 RHSVD->setInit(DRDRef);
9829 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009830 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009831 } else {
9832 switch (BOK) {
9833 case BO_Add:
9834 case BO_Xor:
9835 case BO_Or:
9836 case BO_LOr:
9837 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9838 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009839 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009840 break;
9841 case BO_Mul:
9842 case BO_LAnd:
9843 if (Type->isScalarType() || Type->isAnyComplexType()) {
9844 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009845 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009846 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009847 break;
9848 case BO_And: {
9849 // '&' reduction op - initializer is '~0'.
9850 QualType OrigType = Type;
9851 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9852 Type = ComplexTy->getElementType();
9853 if (Type->isRealFloatingType()) {
9854 llvm::APFloat InitValue =
9855 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9856 /*isIEEE=*/true);
9857 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9858 Type, ELoc);
9859 } else if (Type->isScalarType()) {
9860 auto Size = Context.getTypeSize(Type);
9861 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9862 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9863 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9864 }
9865 if (Init && OrigType->isAnyComplexType()) {
9866 // Init = 0xFFFF + 0xFFFFi;
9867 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009868 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009869 }
9870 Type = OrigType;
9871 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009872 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009873 case BO_LT:
9874 case BO_GT: {
9875 // 'min' reduction op - initializer is 'Largest representable number in
9876 // the reduction list item type'.
9877 // 'max' reduction op - initializer is 'Least representable number in
9878 // the reduction list item type'.
9879 if (Type->isIntegerType() || Type->isPointerType()) {
9880 bool IsSigned = Type->hasSignedIntegerRepresentation();
9881 auto Size = Context.getTypeSize(Type);
9882 QualType IntTy =
9883 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9884 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009885 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9886 : llvm::APInt::getMinValue(Size)
9887 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9888 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009889 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9890 if (Type->isPointerType()) {
9891 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009892 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +00009893 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009894 if (CastExpr.isInvalid())
9895 continue;
9896 Init = CastExpr.get();
9897 }
9898 } else if (Type->isRealFloatingType()) {
9899 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9900 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9901 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9902 Type, ELoc);
9903 }
9904 break;
9905 }
9906 case BO_PtrMemD:
9907 case BO_PtrMemI:
9908 case BO_MulAssign:
9909 case BO_Div:
9910 case BO_Rem:
9911 case BO_Sub:
9912 case BO_Shl:
9913 case BO_Shr:
9914 case BO_LE:
9915 case BO_GE:
9916 case BO_EQ:
9917 case BO_NE:
9918 case BO_AndAssign:
9919 case BO_XorAssign:
9920 case BO_OrAssign:
9921 case BO_Assign:
9922 case BO_AddAssign:
9923 case BO_SubAssign:
9924 case BO_DivAssign:
9925 case BO_RemAssign:
9926 case BO_ShlAssign:
9927 case BO_ShrAssign:
9928 case BO_Comma:
9929 llvm_unreachable("Unexpected reduction operation");
9930 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009931 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009932 if (Init && DeclareReductionRef.isUnset())
9933 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9934 else if (!Init)
9935 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009936 if (RHSVD->isInvalidDecl())
9937 continue;
9938 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009939 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9940 << Type << ReductionIdRange;
9941 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9942 VarDecl::DeclarationOnly;
9943 S.Diag(D->getLocation(),
9944 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009945 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009946 continue;
9947 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009948 // Store initializer for single element in private copy. Will be used during
9949 // codegen.
9950 PrivateVD->setInit(RHSVD->getInit());
9951 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009952 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009953 ExprResult ReductionOp;
9954 if (DeclareReductionRef.isUsable()) {
9955 QualType RedTy = DeclareReductionRef.get()->getType();
9956 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009957 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9958 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009959 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009960 LHS = S.DefaultLvalueConversion(LHS.get());
9961 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009962 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9963 CK_UncheckedDerivedToBase, LHS.get(),
9964 &BasePath, LHS.get()->getValueKind());
9965 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9966 CK_UncheckedDerivedToBase, RHS.get(),
9967 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009968 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009969 FunctionProtoType::ExtProtoInfo EPI;
9970 QualType Params[] = {PtrRedTy, PtrRedTy};
9971 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9972 auto *OVE = new (Context) OpaqueValueExpr(
9973 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009974 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009975 Expr *Args[] = {LHS.get(), RHS.get()};
9976 ReductionOp = new (Context)
9977 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9978 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009979 ReductionOp = S.BuildBinOp(
9980 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009981 if (ReductionOp.isUsable()) {
9982 if (BOK != BO_LT && BOK != BO_GT) {
9983 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009984 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9985 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009986 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +00009987 auto *ConditionalOp = new (Context)
9988 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
9989 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009990 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009991 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9992 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009993 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009994 if (ReductionOp.isUsable())
9995 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009996 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009997 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009998 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009999 }
10000
Alexey Bataevfa312f32017-07-21 18:48:21 +000010001 // OpenMP [2.15.4.6, Restrictions, p.2]
10002 // A list item that appears in an in_reduction clause of a task construct
10003 // must appear in a task_reduction clause of a construct associated with a
10004 // taskgroup region that includes the participating task in its taskgroup
10005 // set. The construct associated with the innermost region that meets this
10006 // condition must specify the same reduction-identifier as the in_reduction
10007 // clause.
10008 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010009 SourceRange ParentSR;
10010 BinaryOperatorKind ParentBOK;
10011 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010012 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010013 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010014 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10015 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010016 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010017 Stack->getTopMostTaskgroupReductionData(
10018 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010019 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10020 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10021 if (!IsParentBOK && !IsParentReductionOp) {
10022 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10023 continue;
10024 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010025 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10026 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10027 IsParentReductionOp) {
10028 bool EmitError = true;
10029 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10030 llvm::FoldingSetNodeID RedId, ParentRedId;
10031 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10032 DeclareReductionRef.get()->Profile(RedId, Context,
10033 /*Canonical=*/true);
10034 EmitError = RedId != ParentRedId;
10035 }
10036 if (EmitError) {
10037 S.Diag(ReductionId.getLocStart(),
10038 diag::err_omp_reduction_identifier_mismatch)
10039 << ReductionIdRange << RefExpr->getSourceRange();
10040 S.Diag(ParentSR.getBegin(),
10041 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010042 << ParentSR
10043 << (IsParentBOK ? ParentBOKDSA.RefExpr
10044 : ParentReductionOpDSA.RefExpr)
10045 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010046 continue;
10047 }
10048 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010049 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10050 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010051 }
10052
Alexey Bataev60da77e2016-02-29 05:54:20 +000010053 DeclRefExpr *Ref = nullptr;
10054 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010055 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010056 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010057 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010058 VarsExpr =
10059 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10060 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010061 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010062 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010063 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010064 if (!S.IsOpenMPCapturedDecl(D)) {
10065 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010066 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010067 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010068 if (!RefRes.isUsable())
10069 continue;
10070 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010071 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10072 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010073 if (!PostUpdateRes.isUsable())
10074 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010075 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10076 Stack->getCurrentDirective() == OMPD_taskgroup) {
10077 S.Diag(RefExpr->getExprLoc(),
10078 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010079 << RefExpr->getSourceRange();
10080 continue;
10081 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010082 RD.ExprPostUpdates.emplace_back(
10083 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010084 }
10085 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010086 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010087 // All reduction items are still marked as reduction (to do not increase
10088 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010089 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010090 if (CurrDir == OMPD_taskgroup) {
10091 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010092 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10093 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010094 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010095 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010096 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010097 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10098 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010099 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010100 return RD.Vars.empty();
10101}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010102
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010103OMPClause *Sema::ActOnOpenMPReductionClause(
10104 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10105 SourceLocation ColonLoc, SourceLocation EndLoc,
10106 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10107 ArrayRef<Expr *> UnresolvedReductions) {
10108 ReductionData RD(VarList.size());
10109
Alexey Bataev169d96a2017-07-18 20:17:46 +000010110 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10111 StartLoc, LParenLoc, ColonLoc, EndLoc,
10112 ReductionIdScopeSpec, ReductionId,
10113 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010114 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010115
Alexey Bataevc5e02582014-06-16 07:08:35 +000010116 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010117 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10118 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10119 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10120 buildPreInits(Context, RD.ExprCaptures),
10121 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010122}
10123
Alexey Bataev169d96a2017-07-18 20:17:46 +000010124OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10125 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10126 SourceLocation ColonLoc, SourceLocation EndLoc,
10127 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10128 ArrayRef<Expr *> UnresolvedReductions) {
10129 ReductionData RD(VarList.size());
10130
10131 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10132 VarList, StartLoc, LParenLoc, ColonLoc,
10133 EndLoc, ReductionIdScopeSpec, ReductionId,
10134 UnresolvedReductions, RD))
10135 return nullptr;
10136
10137 return OMPTaskReductionClause::Create(
10138 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10139 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10140 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10141 buildPreInits(Context, RD.ExprCaptures),
10142 buildPostUpdate(*this, RD.ExprPostUpdates));
10143}
10144
Alexey Bataevfa312f32017-07-21 18:48:21 +000010145OMPClause *Sema::ActOnOpenMPInReductionClause(
10146 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10147 SourceLocation ColonLoc, SourceLocation EndLoc,
10148 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10149 ArrayRef<Expr *> UnresolvedReductions) {
10150 ReductionData RD(VarList.size());
10151
10152 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10153 StartLoc, LParenLoc, ColonLoc, EndLoc,
10154 ReductionIdScopeSpec, ReductionId,
10155 UnresolvedReductions, RD))
10156 return nullptr;
10157
10158 return OMPInReductionClause::Create(
10159 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10160 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010161 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010162 buildPreInits(Context, RD.ExprCaptures),
10163 buildPostUpdate(*this, RD.ExprPostUpdates));
10164}
10165
Alexey Bataevecba70f2016-04-12 11:02:11 +000010166bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10167 SourceLocation LinLoc) {
10168 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10169 LinKind == OMPC_LINEAR_unknown) {
10170 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10171 return true;
10172 }
10173 return false;
10174}
10175
10176bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10177 OpenMPLinearClauseKind LinKind,
10178 QualType Type) {
10179 auto *VD = dyn_cast_or_null<VarDecl>(D);
10180 // A variable must not have an incomplete type or a reference type.
10181 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10182 return true;
10183 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10184 !Type->isReferenceType()) {
10185 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10186 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10187 return true;
10188 }
10189 Type = Type.getNonReferenceType();
10190
10191 // A list item must not be const-qualified.
10192 if (Type.isConstant(Context)) {
10193 Diag(ELoc, diag::err_omp_const_variable)
10194 << getOpenMPClauseName(OMPC_linear);
10195 if (D) {
10196 bool IsDecl =
10197 !VD ||
10198 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10199 Diag(D->getLocation(),
10200 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10201 << D;
10202 }
10203 return true;
10204 }
10205
10206 // A list item must be of integral or pointer type.
10207 Type = Type.getUnqualifiedType().getCanonicalType();
10208 const auto *Ty = Type.getTypePtrOrNull();
10209 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10210 !Ty->isPointerType())) {
10211 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10212 if (D) {
10213 bool IsDecl =
10214 !VD ||
10215 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10216 Diag(D->getLocation(),
10217 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10218 << D;
10219 }
10220 return true;
10221 }
10222 return false;
10223}
10224
Alexey Bataev182227b2015-08-20 10:54:39 +000010225OMPClause *Sema::ActOnOpenMPLinearClause(
10226 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10227 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10228 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010229 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010230 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010231 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010232 SmallVector<Decl *, 4> ExprCaptures;
10233 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010234 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010235 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010236 for (auto &RefExpr : VarList) {
10237 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010238 SourceLocation ELoc;
10239 SourceRange ERange;
10240 Expr *SimpleRefExpr = RefExpr;
10241 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10242 /*AllowArraySection=*/false);
10243 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010244 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010245 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010246 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010247 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010248 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010249 ValueDecl *D = Res.first;
10250 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010251 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010252
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010253 QualType Type = D->getType();
10254 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010255
10256 // OpenMP [2.14.3.7, linear clause]
10257 // A list-item cannot appear in more than one linear clause.
10258 // A list-item that appears in a linear clause cannot appear in any
10259 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010260 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010261 if (DVar.RefExpr) {
10262 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10263 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010264 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010265 continue;
10266 }
10267
Alexey Bataevecba70f2016-04-12 11:02:11 +000010268 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010269 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010270 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010271
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010272 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010273 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10274 D->hasAttrs() ? &D->getAttrs() : nullptr);
10275 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010276 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010277 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010278 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010279 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010280 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010281 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10282 if (!IsOpenMPCapturedDecl(D)) {
10283 ExprCaptures.push_back(Ref->getDecl());
10284 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10285 ExprResult RefRes = DefaultLvalueConversion(Ref);
10286 if (!RefRes.isUsable())
10287 continue;
10288 ExprResult PostUpdateRes =
10289 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10290 SimpleRefExpr, RefRes.get());
10291 if (!PostUpdateRes.isUsable())
10292 continue;
10293 ExprPostUpdates.push_back(
10294 IgnoredValueConversions(PostUpdateRes.get()).get());
10295 }
10296 }
10297 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010298 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010299 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010300 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010301 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010302 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010303 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010304 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10305
10306 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010307 Vars.push_back((VD || CurContext->isDependentContext())
10308 ? RefExpr->IgnoreParens()
10309 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010310 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010311 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010312 }
10313
10314 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010315 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010316
10317 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010318 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010319 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10320 !Step->isInstantiationDependent() &&
10321 !Step->containsUnexpandedParameterPack()) {
10322 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010323 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010324 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010325 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010326 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010327
Alexander Musman3276a272015-03-21 10:12:56 +000010328 // Build var to save the step value.
10329 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010330 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010331 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010332 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010333 ExprResult CalcStep =
10334 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010335 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010336
Alexander Musman8dba6642014-04-22 13:09:42 +000010337 // Warn about zero linear step (it would be probably better specified as
10338 // making corresponding variables 'const').
10339 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010340 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10341 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010342 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10343 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010344 if (!IsConstant && CalcStep.isUsable()) {
10345 // Calculate the step beforehand instead of doing this on each iteration.
10346 // (This is not used if the number of iterations may be kfold-ed).
10347 CalcStepExpr = CalcStep.get();
10348 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010349 }
10350
Alexey Bataev182227b2015-08-20 10:54:39 +000010351 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10352 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010353 StepExpr, CalcStepExpr,
10354 buildPreInits(Context, ExprCaptures),
10355 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010356}
10357
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010358static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10359 Expr *NumIterations, Sema &SemaRef,
10360 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010361 // Walk the vars and build update/final expressions for the CodeGen.
10362 SmallVector<Expr *, 8> Updates;
10363 SmallVector<Expr *, 8> Finals;
10364 Expr *Step = Clause.getStep();
10365 Expr *CalcStep = Clause.getCalcStep();
10366 // OpenMP [2.14.3.7, linear clause]
10367 // If linear-step is not specified it is assumed to be 1.
10368 if (Step == nullptr)
10369 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010370 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010371 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010372 }
Alexander Musman3276a272015-03-21 10:12:56 +000010373 bool HasErrors = false;
10374 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010375 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010376 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010377 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010378 SourceLocation ELoc;
10379 SourceRange ERange;
10380 Expr *SimpleRefExpr = RefExpr;
10381 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10382 /*AllowArraySection=*/false);
10383 ValueDecl *D = Res.first;
10384 if (Res.second || !D) {
10385 Updates.push_back(nullptr);
10386 Finals.push_back(nullptr);
10387 HasErrors = true;
10388 continue;
10389 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010390 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010391 Expr *InitExpr = *CurInit;
10392
10393 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010394 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010395 Expr *CapturedRef;
10396 if (LinKind == OMPC_LINEAR_uval)
10397 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10398 else
10399 CapturedRef =
10400 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10401 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10402 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010403
10404 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010405 ExprResult Update;
10406 if (!Info.first) {
10407 Update =
10408 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10409 InitExpr, IV, Step, /* Subtract */ false);
10410 } else
10411 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010412 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10413 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010414
10415 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010416 ExprResult Final;
10417 if (!Info.first) {
10418 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10419 InitExpr, NumIterations, Step,
10420 /* Subtract */ false);
10421 } else
10422 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010423 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10424 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010425
Alexander Musman3276a272015-03-21 10:12:56 +000010426 if (!Update.isUsable() || !Final.isUsable()) {
10427 Updates.push_back(nullptr);
10428 Finals.push_back(nullptr);
10429 HasErrors = true;
10430 } else {
10431 Updates.push_back(Update.get());
10432 Finals.push_back(Final.get());
10433 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010434 ++CurInit;
10435 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010436 }
10437 Clause.setUpdates(Updates);
10438 Clause.setFinals(Finals);
10439 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010440}
10441
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010442OMPClause *Sema::ActOnOpenMPAlignedClause(
10443 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10444 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10445
10446 SmallVector<Expr *, 8> Vars;
10447 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010448 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10449 SourceLocation ELoc;
10450 SourceRange ERange;
10451 Expr *SimpleRefExpr = RefExpr;
10452 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10453 /*AllowArraySection=*/false);
10454 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010455 // It will be analyzed later.
10456 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010457 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010458 ValueDecl *D = Res.first;
10459 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010460 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010461
Alexey Bataev1efd1662016-03-29 10:59:56 +000010462 QualType QType = D->getType();
10463 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010464
10465 // OpenMP [2.8.1, simd construct, Restrictions]
10466 // The type of list items appearing in the aligned clause must be
10467 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010468 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010469 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010470 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010471 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010472 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010473 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010474 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010475 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010476 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010477 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010478 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010479 continue;
10480 }
10481
10482 // OpenMP [2.8.1, simd construct, Restrictions]
10483 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010484 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010485 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010486 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10487 << getOpenMPClauseName(OMPC_aligned);
10488 continue;
10489 }
10490
Alexey Bataev1efd1662016-03-29 10:59:56 +000010491 DeclRefExpr *Ref = nullptr;
10492 if (!VD && IsOpenMPCapturedDecl(D))
10493 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10494 Vars.push_back(DefaultFunctionArrayConversion(
10495 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10496 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010497 }
10498
10499 // OpenMP [2.8.1, simd construct, Description]
10500 // The parameter of the aligned clause, alignment, must be a constant
10501 // positive integer expression.
10502 // If no optional parameter is specified, implementation-defined default
10503 // alignments for SIMD instructions on the target platforms are assumed.
10504 if (Alignment != nullptr) {
10505 ExprResult AlignResult =
10506 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10507 if (AlignResult.isInvalid())
10508 return nullptr;
10509 Alignment = AlignResult.get();
10510 }
10511 if (Vars.empty())
10512 return nullptr;
10513
10514 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10515 EndLoc, Vars, Alignment);
10516}
10517
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010518OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10519 SourceLocation StartLoc,
10520 SourceLocation LParenLoc,
10521 SourceLocation EndLoc) {
10522 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010523 SmallVector<Expr *, 8> SrcExprs;
10524 SmallVector<Expr *, 8> DstExprs;
10525 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010526 for (auto &RefExpr : VarList) {
10527 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10528 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010529 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010530 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010531 SrcExprs.push_back(nullptr);
10532 DstExprs.push_back(nullptr);
10533 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010534 continue;
10535 }
10536
Alexey Bataeved09d242014-05-28 05:53:51 +000010537 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010538 // OpenMP [2.1, C/C++]
10539 // A list item is a variable name.
10540 // OpenMP [2.14.4.1, Restrictions, p.1]
10541 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010542 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010543 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010544 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10545 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010546 continue;
10547 }
10548
10549 Decl *D = DE->getDecl();
10550 VarDecl *VD = cast<VarDecl>(D);
10551
10552 QualType Type = VD->getType();
10553 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10554 // It will be analyzed later.
10555 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010556 SrcExprs.push_back(nullptr);
10557 DstExprs.push_back(nullptr);
10558 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010559 continue;
10560 }
10561
10562 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10563 // A list item that appears in a copyin clause must be threadprivate.
10564 if (!DSAStack->isThreadPrivate(VD)) {
10565 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010566 << getOpenMPClauseName(OMPC_copyin)
10567 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010568 continue;
10569 }
10570
10571 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10572 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010573 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010574 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010575 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010576 auto *SrcVD =
10577 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10578 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010579 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010580 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10581 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010582 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10583 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010584 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010585 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010586 // For arrays generate assignment operation for single element and replace
10587 // it by the original array element in CodeGen.
10588 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10589 PseudoDstExpr, PseudoSrcExpr);
10590 if (AssignmentOp.isInvalid())
10591 continue;
10592 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10593 /*DiscardedValue=*/true);
10594 if (AssignmentOp.isInvalid())
10595 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010596
10597 DSAStack->addDSA(VD, DE, OMPC_copyin);
10598 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010599 SrcExprs.push_back(PseudoSrcExpr);
10600 DstExprs.push_back(PseudoDstExpr);
10601 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010602 }
10603
Alexey Bataeved09d242014-05-28 05:53:51 +000010604 if (Vars.empty())
10605 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010606
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010607 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10608 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010609}
10610
Alexey Bataevbae9a792014-06-27 10:37:06 +000010611OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10612 SourceLocation StartLoc,
10613 SourceLocation LParenLoc,
10614 SourceLocation EndLoc) {
10615 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010616 SmallVector<Expr *, 8> SrcExprs;
10617 SmallVector<Expr *, 8> DstExprs;
10618 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010619 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010620 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10621 SourceLocation ELoc;
10622 SourceRange ERange;
10623 Expr *SimpleRefExpr = RefExpr;
10624 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10625 /*AllowArraySection=*/false);
10626 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010627 // It will be analyzed later.
10628 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010629 SrcExprs.push_back(nullptr);
10630 DstExprs.push_back(nullptr);
10631 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010632 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010633 ValueDecl *D = Res.first;
10634 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010635 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010636
Alexey Bataeve122da12016-03-17 10:50:17 +000010637 QualType Type = D->getType();
10638 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010639
10640 // OpenMP [2.14.4.2, Restrictions, p.2]
10641 // A list item that appears in a copyprivate clause may not appear in a
10642 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010643 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10644 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010645 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10646 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010647 Diag(ELoc, diag::err_omp_wrong_dsa)
10648 << getOpenMPClauseName(DVar.CKind)
10649 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010650 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010651 continue;
10652 }
10653
10654 // OpenMP [2.11.4.2, Restrictions, p.1]
10655 // All list items that appear in a copyprivate clause must be either
10656 // threadprivate or private in the enclosing context.
10657 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010658 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010659 if (DVar.CKind == OMPC_shared) {
10660 Diag(ELoc, diag::err_omp_required_access)
10661 << getOpenMPClauseName(OMPC_copyprivate)
10662 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010663 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010664 continue;
10665 }
10666 }
10667 }
10668
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010669 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010670 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010671 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010672 << getOpenMPClauseName(OMPC_copyprivate) << Type
10673 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010674 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010675 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010676 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010677 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010678 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010679 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010680 continue;
10681 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010682
Alexey Bataevbae9a792014-06-27 10:37:06 +000010683 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10684 // A variable of class type (or array thereof) that appears in a
10685 // copyin clause requires an accessible, unambiguous copy assignment
10686 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010687 Type = Context.getBaseElementType(Type.getNonReferenceType())
10688 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010689 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010690 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10691 D->hasAttrs() ? &D->getAttrs() : nullptr);
10692 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010693 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010694 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10695 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010696 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010697 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010698 PseudoDstExpr, PseudoSrcExpr);
10699 if (AssignmentOp.isInvalid())
10700 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010701 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010702 /*DiscardedValue=*/true);
10703 if (AssignmentOp.isInvalid())
10704 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010705
10706 // No need to mark vars as copyprivate, they are already threadprivate or
10707 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010708 assert(VD || IsOpenMPCapturedDecl(D));
10709 Vars.push_back(
10710 VD ? RefExpr->IgnoreParens()
10711 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010712 SrcExprs.push_back(PseudoSrcExpr);
10713 DstExprs.push_back(PseudoDstExpr);
10714 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010715 }
10716
10717 if (Vars.empty())
10718 return nullptr;
10719
Alexey Bataeva63048e2015-03-23 06:18:07 +000010720 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10721 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010722}
10723
Alexey Bataev6125da92014-07-21 11:26:11 +000010724OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10725 SourceLocation StartLoc,
10726 SourceLocation LParenLoc,
10727 SourceLocation EndLoc) {
10728 if (VarList.empty())
10729 return nullptr;
10730
10731 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10732}
Alexey Bataevdea47612014-07-23 07:46:59 +000010733
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010734OMPClause *
10735Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10736 SourceLocation DepLoc, SourceLocation ColonLoc,
10737 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10738 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010739 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010740 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010741 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010742 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010743 return nullptr;
10744 }
10745 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010746 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10747 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010748 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010749 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010750 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10751 /*Last=*/OMPC_DEPEND_unknown, Except)
10752 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010753 return nullptr;
10754 }
10755 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010756 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010757 llvm::APSInt DepCounter(/*BitWidth=*/32);
10758 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10759 if (DepKind == OMPC_DEPEND_sink) {
10760 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10761 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10762 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010763 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010764 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010765 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10766 DSAStack->getParentOrderedRegionParam()) {
10767 for (auto &RefExpr : VarList) {
10768 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010769 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010770 // It will be analyzed later.
10771 Vars.push_back(RefExpr);
10772 continue;
10773 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010774
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010775 SourceLocation ELoc = RefExpr->getExprLoc();
10776 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10777 if (DepKind == OMPC_DEPEND_sink) {
10778 if (DepCounter >= TotalDepCount) {
10779 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10780 continue;
10781 }
10782 ++DepCounter;
10783 // OpenMP [2.13.9, Summary]
10784 // depend(dependence-type : vec), where dependence-type is:
10785 // 'sink' and where vec is the iteration vector, which has the form:
10786 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10787 // where n is the value specified by the ordered clause in the loop
10788 // directive, xi denotes the loop iteration variable of the i-th nested
10789 // loop associated with the loop directive, and di is a constant
10790 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010791 if (CurContext->isDependentContext()) {
10792 // It will be analyzed later.
10793 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010794 continue;
10795 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010796 SimpleExpr = SimpleExpr->IgnoreImplicit();
10797 OverloadedOperatorKind OOK = OO_None;
10798 SourceLocation OOLoc;
10799 Expr *LHS = SimpleExpr;
10800 Expr *RHS = nullptr;
10801 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10802 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10803 OOLoc = BO->getOperatorLoc();
10804 LHS = BO->getLHS()->IgnoreParenImpCasts();
10805 RHS = BO->getRHS()->IgnoreParenImpCasts();
10806 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10807 OOK = OCE->getOperator();
10808 OOLoc = OCE->getOperatorLoc();
10809 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10810 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10811 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10812 OOK = MCE->getMethodDecl()
10813 ->getNameInfo()
10814 .getName()
10815 .getCXXOverloadedOperator();
10816 OOLoc = MCE->getCallee()->getExprLoc();
10817 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10818 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10819 }
10820 SourceLocation ELoc;
10821 SourceRange ERange;
10822 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10823 /*AllowArraySection=*/false);
10824 if (Res.second) {
10825 // It will be analyzed later.
10826 Vars.push_back(RefExpr);
10827 }
10828 ValueDecl *D = Res.first;
10829 if (!D)
10830 continue;
10831
10832 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10833 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10834 continue;
10835 }
10836 if (RHS) {
10837 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10838 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10839 if (RHSRes.isInvalid())
10840 continue;
10841 }
10842 if (!CurContext->isDependentContext() &&
10843 DSAStack->getParentOrderedRegionParam() &&
10844 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000010845 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
10846 DepCounter.getZExtValue());
10847 if (VD) {
10848 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10849 << 1 << VD;
10850 } else {
10851 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
10852 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010853 continue;
10854 }
10855 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010856 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010857 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010858 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010859 (ASE &&
10860 !ASE->getBase()
10861 ->getType()
10862 .getNonReferenceType()
10863 ->isPointerType() &&
10864 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000010865 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10866 << RefExpr->getSourceRange();
10867 continue;
10868 }
10869 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
10870 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000010871 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000010872 RefExpr->IgnoreParenImpCasts());
10873 getDiagnostics().setSuppressAllDiagnostics(Suppress);
10874 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
10875 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10876 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010877 continue;
10878 }
10879 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010880 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10881 }
10882
10883 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10884 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000010885 DSAStack->getParentOrderedRegionParam() &&
10886 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
10887 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010888 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10889 }
10890 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10891 Vars.empty())
10892 return nullptr;
10893 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010894 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10895 DepKind, DepLoc, ColonLoc, Vars);
10896 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10897 DSAStack->addDoacrossDependClause(C, OpsOffs);
10898 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010899}
Michael Wonge710d542015-08-07 16:16:36 +000010900
10901OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10902 SourceLocation LParenLoc,
10903 SourceLocation EndLoc) {
10904 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000010905 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000010906
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010907 // OpenMP [2.9.1, Restrictions]
10908 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010909 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10910 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010911 return nullptr;
10912
Alexey Bataev931e19b2017-10-02 16:32:39 +000010913 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10914 if (isOpenMPTargetExecutionDirective(DKind) &&
10915 !CurContext->isDependentContext()) {
10916 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10917 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10918 HelperValStmt = buildPreInits(Context, Captures);
10919 }
10920
10921 return new (Context)
10922 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000010923}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010924
Kelvin Li0bff7af2015-11-23 05:32:03 +000010925static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10926 DSAStackTy *Stack, QualType QTy) {
10927 NamedDecl *ND;
10928 if (QTy->isIncompleteType(&ND)) {
10929 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10930 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010931 }
10932 return true;
10933}
10934
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010935/// \brief Return true if it can be proven that the provided array expression
10936/// (array section or array subscript) does NOT specify the whole size of the
10937/// array whose base type is \a BaseQTy.
10938static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10939 const Expr *E,
10940 QualType BaseQTy) {
10941 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10942
10943 // If this is an array subscript, it refers to the whole size if the size of
10944 // the dimension is constant and equals 1. Also, an array section assumes the
10945 // format of an array subscript if no colon is used.
10946 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10947 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10948 return ATy->getSize().getSExtValue() != 1;
10949 // Size can't be evaluated statically.
10950 return false;
10951 }
10952
10953 assert(OASE && "Expecting array section if not an array subscript.");
10954 auto *LowerBound = OASE->getLowerBound();
10955 auto *Length = OASE->getLength();
10956
10957 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010958 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010959 if (LowerBound) {
10960 llvm::APSInt ConstLowerBound;
10961 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10962 return false; // Can't get the integer value as a constant.
10963 if (ConstLowerBound.getSExtValue())
10964 return true;
10965 }
10966
10967 // If we don't have a length we covering the whole dimension.
10968 if (!Length)
10969 return false;
10970
10971 // If the base is a pointer, we don't have a way to get the size of the
10972 // pointee.
10973 if (BaseQTy->isPointerType())
10974 return false;
10975
10976 // We can only check if the length is the same as the size of the dimension
10977 // if we have a constant array.
10978 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10979 if (!CATy)
10980 return false;
10981
10982 llvm::APSInt ConstLength;
10983 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10984 return false; // Can't get the integer value as a constant.
10985
10986 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10987}
10988
10989// Return true if it can be proven that the provided array expression (array
10990// section or array subscript) does NOT specify a single element of the array
10991// whose base type is \a BaseQTy.
10992static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010993 const Expr *E,
10994 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010995 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10996
10997 // An array subscript always refer to a single element. Also, an array section
10998 // assumes the format of an array subscript if no colon is used.
10999 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11000 return false;
11001
11002 assert(OASE && "Expecting array section if not an array subscript.");
11003 auto *Length = OASE->getLength();
11004
11005 // If we don't have a length we have to check if the array has unitary size
11006 // for this dimension. Also, we should always expect a length if the base type
11007 // is pointer.
11008 if (!Length) {
11009 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11010 return ATy->getSize().getSExtValue() != 1;
11011 // We cannot assume anything.
11012 return false;
11013 }
11014
11015 // Check if the length evaluates to 1.
11016 llvm::APSInt ConstLength;
11017 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11018 return false; // Can't get the integer value as a constant.
11019
11020 return ConstLength.getSExtValue() != 1;
11021}
11022
Samuel Antao661c0902016-05-26 17:39:58 +000011023// Return the expression of the base of the mappable expression or null if it
11024// cannot be determined and do all the necessary checks to see if the expression
11025// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011026// components of the expression.
11027static Expr *CheckMapClauseExpressionBase(
11028 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011029 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11030 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011031 SourceLocation ELoc = E->getExprLoc();
11032 SourceRange ERange = E->getSourceRange();
11033
11034 // The base of elements of list in a map clause have to be either:
11035 // - a reference to variable or field.
11036 // - a member expression.
11037 // - an array expression.
11038 //
11039 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11040 // reference to 'r'.
11041 //
11042 // If we have:
11043 //
11044 // struct SS {
11045 // Bla S;
11046 // foo() {
11047 // #pragma omp target map (S.Arr[:12]);
11048 // }
11049 // }
11050 //
11051 // We want to retrieve the member expression 'this->S';
11052
11053 Expr *RelevantExpr = nullptr;
11054
Samuel Antao5de996e2016-01-22 20:21:36 +000011055 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11056 // If a list item is an array section, it must specify contiguous storage.
11057 //
11058 // For this restriction it is sufficient that we make sure only references
11059 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011060 // exist except in the rightmost expression (unless they cover the whole
11061 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011062 //
11063 // r.ArrS[3:5].Arr[6:7]
11064 //
11065 // r.ArrS[3:5].x
11066 //
11067 // but these would be valid:
11068 // r.ArrS[3].Arr[6:7]
11069 //
11070 // r.ArrS[3].x
11071
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011072 bool AllowUnitySizeArraySection = true;
11073 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011074
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011075 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011076 E = E->IgnoreParenImpCasts();
11077
11078 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11079 if (!isa<VarDecl>(CurE->getDecl()))
11080 break;
11081
11082 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011083
11084 // If we got a reference to a declaration, we should not expect any array
11085 // section before that.
11086 AllowUnitySizeArraySection = false;
11087 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011088
11089 // Record the component.
11090 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
11091 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000011092 continue;
11093 }
11094
11095 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11096 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11097
11098 if (isa<CXXThisExpr>(BaseE))
11099 // We found a base expression: this->Val.
11100 RelevantExpr = CurE;
11101 else
11102 E = BaseE;
11103
11104 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11105 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11106 << CurE->getSourceRange();
11107 break;
11108 }
11109
11110 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11111
11112 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11113 // A bit-field cannot appear in a map clause.
11114 //
11115 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011116 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11117 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011118 break;
11119 }
11120
11121 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11122 // If the type of a list item is a reference to a type T then the type
11123 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011124 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011125
11126 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11127 // A list item cannot be a variable that is a member of a structure with
11128 // a union type.
11129 //
11130 if (auto *RT = CurType->getAs<RecordType>())
11131 if (RT->isUnionType()) {
11132 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11133 << CurE->getSourceRange();
11134 break;
11135 }
11136
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011137 // If we got a member expression, we should not expect any array section
11138 // before that:
11139 //
11140 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11141 // If a list item is an element of a structure, only the rightmost symbol
11142 // of the variable reference can be an array section.
11143 //
11144 AllowUnitySizeArraySection = false;
11145 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011146
11147 // Record the component.
11148 CurComponents.push_back(
11149 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000011150 continue;
11151 }
11152
11153 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11154 E = CurE->getBase()->IgnoreParenImpCasts();
11155
11156 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11157 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11158 << 0 << CurE->getSourceRange();
11159 break;
11160 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011161
11162 // If we got an array subscript that express the whole dimension we
11163 // can have any array expressions before. If it only expressing part of
11164 // the dimension, we can only have unitary-size array expressions.
11165 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11166 E->getType()))
11167 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011168
11169 // Record the component - we don't have any declaration associated.
11170 CurComponents.push_back(
11171 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011172 continue;
11173 }
11174
11175 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011176 E = CurE->getBase()->IgnoreParenImpCasts();
11177
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011178 auto CurType =
11179 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11180
Samuel Antao5de996e2016-01-22 20:21:36 +000011181 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11182 // If the type of a list item is a reference to a type T then the type
11183 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011184 if (CurType->isReferenceType())
11185 CurType = CurType->getPointeeType();
11186
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011187 bool IsPointer = CurType->isAnyPointerType();
11188
11189 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011190 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11191 << 0 << CurE->getSourceRange();
11192 break;
11193 }
11194
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011195 bool NotWhole =
11196 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11197 bool NotUnity =
11198 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11199
Samuel Antaodab51bb2016-07-18 23:22:11 +000011200 if (AllowWholeSizeArraySection) {
11201 // Any array section is currently allowed. Allowing a whole size array
11202 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011203 //
11204 // If this array section refers to the whole dimension we can still
11205 // accept other array sections before this one, except if the base is a
11206 // pointer. Otherwise, only unitary sections are accepted.
11207 if (NotWhole || IsPointer)
11208 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011209 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011210 // A unity or whole array section is not allowed and that is not
11211 // compatible with the properties of the current array section.
11212 SemaRef.Diag(
11213 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11214 << CurE->getSourceRange();
11215 break;
11216 }
Samuel Antao90927002016-04-26 14:54:23 +000011217
11218 // Record the component - we don't have any declaration associated.
11219 CurComponents.push_back(
11220 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011221 continue;
11222 }
11223
11224 // If nothing else worked, this is not a valid map clause expression.
11225 SemaRef.Diag(ELoc,
11226 diag::err_omp_expected_named_var_member_or_array_expression)
11227 << ERange;
11228 break;
11229 }
11230
11231 return RelevantExpr;
11232}
11233
11234// Return true if expression E associated with value VD has conflicts with other
11235// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011236static bool CheckMapConflicts(
11237 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11238 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011239 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11240 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011241 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011242 SourceLocation ELoc = E->getExprLoc();
11243 SourceRange ERange = E->getSourceRange();
11244
11245 // In order to easily check the conflicts we need to match each component of
11246 // the expression under test with the components of the expressions that are
11247 // already in the stack.
11248
Samuel Antao5de996e2016-01-22 20:21:36 +000011249 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011250 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011251 "Map clause expression with unexpected base!");
11252
11253 // Variables to help detecting enclosing problems in data environment nests.
11254 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011255 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011256
Samuel Antao90927002016-04-26 14:54:23 +000011257 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11258 VD, CurrentRegionOnly,
11259 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011260 StackComponents,
11261 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011262
Samuel Antao5de996e2016-01-22 20:21:36 +000011263 assert(!StackComponents.empty() &&
11264 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011265 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011266 "Map clause expression with unexpected base!");
11267
Samuel Antao90927002016-04-26 14:54:23 +000011268 // The whole expression in the stack.
11269 auto *RE = StackComponents.front().getAssociatedExpression();
11270
Samuel Antao5de996e2016-01-22 20:21:36 +000011271 // Expressions must start from the same base. Here we detect at which
11272 // point both expressions diverge from each other and see if we can
11273 // detect if the memory referred to both expressions is contiguous and
11274 // do not overlap.
11275 auto CI = CurComponents.rbegin();
11276 auto CE = CurComponents.rend();
11277 auto SI = StackComponents.rbegin();
11278 auto SE = StackComponents.rend();
11279 for (; CI != CE && SI != SE; ++CI, ++SI) {
11280
11281 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11282 // At most one list item can be an array item derived from a given
11283 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011284 if (CurrentRegionOnly &&
11285 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11286 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11287 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11288 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11289 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011290 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011291 << CI->getAssociatedExpression()->getSourceRange();
11292 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11293 diag::note_used_here)
11294 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011295 return true;
11296 }
11297
11298 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011299 if (CI->getAssociatedExpression()->getStmtClass() !=
11300 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011301 break;
11302
11303 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011304 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011305 break;
11306 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011307 // Check if the extra components of the expressions in the enclosing
11308 // data environment are redundant for the current base declaration.
11309 // If they are, the maps completely overlap, which is legal.
11310 for (; SI != SE; ++SI) {
11311 QualType Type;
11312 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011313 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011314 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011315 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11316 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011317 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11318 Type =
11319 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11320 }
11321 if (Type.isNull() || Type->isAnyPointerType() ||
11322 CheckArrayExpressionDoesNotReferToWholeSize(
11323 SemaRef, SI->getAssociatedExpression(), Type))
11324 break;
11325 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011326
11327 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11328 // List items of map clauses in the same construct must not share
11329 // original storage.
11330 //
11331 // If the expressions are exactly the same or one is a subset of the
11332 // other, it means they are sharing storage.
11333 if (CI == CE && SI == SE) {
11334 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011335 if (CKind == OMPC_map)
11336 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11337 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011338 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011339 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11340 << ERange;
11341 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011342 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11343 << RE->getSourceRange();
11344 return true;
11345 } else {
11346 // If we find the same expression in the enclosing data environment,
11347 // that is legal.
11348 IsEnclosedByDataEnvironmentExpr = true;
11349 return false;
11350 }
11351 }
11352
Samuel Antao90927002016-04-26 14:54:23 +000011353 QualType DerivedType =
11354 std::prev(CI)->getAssociatedDeclaration()->getType();
11355 SourceLocation DerivedLoc =
11356 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011357
11358 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11359 // If the type of a list item is a reference to a type T then the type
11360 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011361 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011362
11363 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11364 // A variable for which the type is pointer and an array section
11365 // derived from that variable must not appear as list items of map
11366 // clauses of the same construct.
11367 //
11368 // Also, cover one of the cases in:
11369 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11370 // If any part of the original storage of a list item has corresponding
11371 // storage in the device data environment, all of the original storage
11372 // must have corresponding storage in the device data environment.
11373 //
11374 if (DerivedType->isAnyPointerType()) {
11375 if (CI == CE || SI == SE) {
11376 SemaRef.Diag(
11377 DerivedLoc,
11378 diag::err_omp_pointer_mapped_along_with_derived_section)
11379 << DerivedLoc;
11380 } else {
11381 assert(CI != CE && SI != SE);
11382 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11383 << DerivedLoc;
11384 }
11385 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11386 << RE->getSourceRange();
11387 return true;
11388 }
11389
11390 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11391 // List items of map clauses in the same construct must not share
11392 // original storage.
11393 //
11394 // An expression is a subset of the other.
11395 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011396 if (CKind == OMPC_map)
11397 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11398 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011399 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011400 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11401 << ERange;
11402 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011403 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11404 << RE->getSourceRange();
11405 return true;
11406 }
11407
11408 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011409 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011410 if (!CurrentRegionOnly && SI != SE)
11411 EnclosingExpr = RE;
11412
11413 // The current expression is a subset of the expression in the data
11414 // environment.
11415 IsEnclosedByDataEnvironmentExpr |=
11416 (!CurrentRegionOnly && CI != CE && SI == SE);
11417
11418 return false;
11419 });
11420
11421 if (CurrentRegionOnly)
11422 return FoundError;
11423
11424 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11425 // If any part of the original storage of a list item has corresponding
11426 // storage in the device data environment, all of the original storage must
11427 // have corresponding storage in the device data environment.
11428 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11429 // If a list item is an element of a structure, and a different element of
11430 // the structure has a corresponding list item in the device data environment
11431 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011432 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011433 // data environment prior to the task encountering the construct.
11434 //
11435 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11436 SemaRef.Diag(ELoc,
11437 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11438 << ERange;
11439 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11440 << EnclosingExpr->getSourceRange();
11441 return true;
11442 }
11443
11444 return FoundError;
11445}
11446
Samuel Antao661c0902016-05-26 17:39:58 +000011447namespace {
11448// Utility struct that gathers all the related lists associated with a mappable
11449// expression.
11450struct MappableVarListInfo final {
11451 // The list of expressions.
11452 ArrayRef<Expr *> VarList;
11453 // The list of processed expressions.
11454 SmallVector<Expr *, 16> ProcessedVarList;
11455 // The mappble components for each expression.
11456 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11457 // The base declaration of the variable.
11458 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11459
11460 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11461 // We have a list of components and base declarations for each entry in the
11462 // variable list.
11463 VarComponents.reserve(VarList.size());
11464 VarBaseDeclarations.reserve(VarList.size());
11465 }
11466};
11467}
11468
11469// Check the validity of the provided variable list for the provided clause kind
11470// \a CKind. In the check process the valid expressions, and mappable expression
11471// components and variables are extracted and used to fill \a Vars,
11472// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11473// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11474static void
11475checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11476 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11477 SourceLocation StartLoc,
11478 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11479 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011480 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11481 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011482 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011483
Samuel Antao90927002016-04-26 14:54:23 +000011484 // Keep track of the mappable components and base declarations in this clause.
11485 // Each entry in the list is going to have a list of components associated. We
11486 // record each set of the components so that we can build the clause later on.
11487 // In the end we should have the same amount of declarations and component
11488 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011489
Samuel Antao661c0902016-05-26 17:39:58 +000011490 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011491 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011492 SourceLocation ELoc = RE->getExprLoc();
11493
Kelvin Li0bff7af2015-11-23 05:32:03 +000011494 auto *VE = RE->IgnoreParenLValueCasts();
11495
11496 if (VE->isValueDependent() || VE->isTypeDependent() ||
11497 VE->isInstantiationDependent() ||
11498 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011499 // We can only analyze this information once the missing information is
11500 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011501 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011502 continue;
11503 }
11504
11505 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011506
Samuel Antao5de996e2016-01-22 20:21:36 +000011507 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011508 SemaRef.Diag(ELoc,
11509 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011510 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011511 continue;
11512 }
11513
Samuel Antao90927002016-04-26 14:54:23 +000011514 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11515 ValueDecl *CurDeclaration = nullptr;
11516
11517 // Obtain the array or member expression bases if required. Also, fill the
11518 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011519 auto *BE =
11520 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011521 if (!BE)
11522 continue;
11523
Samuel Antao90927002016-04-26 14:54:23 +000011524 assert(!CurComponents.empty() &&
11525 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011526
Samuel Antao90927002016-04-26 14:54:23 +000011527 // For the following checks, we rely on the base declaration which is
11528 // expected to be associated with the last component. The declaration is
11529 // expected to be a variable or a field (if 'this' is being mapped).
11530 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11531 assert(CurDeclaration && "Null decl on map clause.");
11532 assert(
11533 CurDeclaration->isCanonicalDecl() &&
11534 "Expecting components to have associated only canonical declarations.");
11535
11536 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11537 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011538
11539 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011540 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011541
11542 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011543 // threadprivate variables cannot appear in a map clause.
11544 // OpenMP 4.5 [2.10.5, target update Construct]
11545 // threadprivate variables cannot appear in a from clause.
11546 if (VD && DSAS->isThreadPrivate(VD)) {
11547 auto DVar = DSAS->getTopDSA(VD, false);
11548 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11549 << getOpenMPClauseName(CKind);
11550 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011551 continue;
11552 }
11553
Samuel Antao5de996e2016-01-22 20:21:36 +000011554 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11555 // A list item cannot appear in both a map clause and a data-sharing
11556 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011557
Samuel Antao5de996e2016-01-22 20:21:36 +000011558 // Check conflicts with other map clause expressions. We check the conflicts
11559 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011560 // environment, because the restrictions are different. We only have to
11561 // check conflicts across regions for the map clauses.
11562 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11563 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011564 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011565 if (CKind == OMPC_map &&
11566 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11567 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011568 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011569
Samuel Antao661c0902016-05-26 17:39:58 +000011570 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011571 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11572 // If the type of a list item is a reference to a type T then the type will
11573 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011574 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011575
Samuel Antao661c0902016-05-26 17:39:58 +000011576 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11577 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011578 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011579 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011580 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11581 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011582 continue;
11583
Samuel Antao661c0902016-05-26 17:39:58 +000011584 if (CKind == OMPC_map) {
11585 // target enter data
11586 // OpenMP [2.10.2, Restrictions, p. 99]
11587 // A map-type must be specified in all map clauses and must be either
11588 // to or alloc.
11589 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11590 if (DKind == OMPD_target_enter_data &&
11591 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11592 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11593 << (IsMapTypeImplicit ? 1 : 0)
11594 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11595 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011596 continue;
11597 }
Samuel Antao661c0902016-05-26 17:39:58 +000011598
11599 // target exit_data
11600 // OpenMP [2.10.3, Restrictions, p. 102]
11601 // A map-type must be specified in all map clauses and must be either
11602 // from, release, or delete.
11603 if (DKind == OMPD_target_exit_data &&
11604 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11605 MapType == OMPC_MAP_delete)) {
11606 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11607 << (IsMapTypeImplicit ? 1 : 0)
11608 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11609 << getOpenMPDirectiveName(DKind);
11610 continue;
11611 }
11612
11613 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11614 // A list item cannot appear in both a map clause and a data-sharing
11615 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011616 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011617 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011618 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011619 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11620 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011621 auto DVar = DSAS->getTopDSA(VD, false);
11622 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011623 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011624 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011625 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011626 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11627 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11628 continue;
11629 }
11630 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011631 }
11632
Samuel Antao90927002016-04-26 14:54:23 +000011633 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011634 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011635
11636 // Store the components in the stack so that they can be used to check
11637 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011638 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11639 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011640
11641 // Save the components and declaration to create the clause. For purposes of
11642 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011643 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011644 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11645 MVLI.VarComponents.back().append(CurComponents.begin(),
11646 CurComponents.end());
11647 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11648 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011649 }
Samuel Antao661c0902016-05-26 17:39:58 +000011650}
11651
11652OMPClause *
11653Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11654 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11655 SourceLocation MapLoc, SourceLocation ColonLoc,
11656 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11657 SourceLocation LParenLoc, SourceLocation EndLoc) {
11658 MappableVarListInfo MVLI(VarList);
11659 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11660 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011661
Samuel Antao5de996e2016-01-22 20:21:36 +000011662 // We need to produce a map clause even if we don't have variables so that
11663 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011664 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11665 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11666 MVLI.VarComponents, MapTypeModifier, MapType,
11667 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011668}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011669
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011670QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11671 TypeResult ParsedType) {
11672 assert(ParsedType.isUsable());
11673
11674 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11675 if (ReductionType.isNull())
11676 return QualType();
11677
11678 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11679 // A type name in a declare reduction directive cannot be a function type, an
11680 // array type, a reference type, or a type qualified with const, volatile or
11681 // restrict.
11682 if (ReductionType.hasQualifiers()) {
11683 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11684 return QualType();
11685 }
11686
11687 if (ReductionType->isFunctionType()) {
11688 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11689 return QualType();
11690 }
11691 if (ReductionType->isReferenceType()) {
11692 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11693 return QualType();
11694 }
11695 if (ReductionType->isArrayType()) {
11696 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11697 return QualType();
11698 }
11699 return ReductionType;
11700}
11701
11702Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11703 Scope *S, DeclContext *DC, DeclarationName Name,
11704 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11705 AccessSpecifier AS, Decl *PrevDeclInScope) {
11706 SmallVector<Decl *, 8> Decls;
11707 Decls.reserve(ReductionTypes.size());
11708
11709 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000011710 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011711 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11712 // A reduction-identifier may not be re-declared in the current scope for the
11713 // same type or for a type that is compatible according to the base language
11714 // rules.
11715 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11716 OMPDeclareReductionDecl *PrevDRD = nullptr;
11717 bool InCompoundScope = true;
11718 if (S != nullptr) {
11719 // Find previous declaration with the same name not referenced in other
11720 // declarations.
11721 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11722 InCompoundScope =
11723 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11724 LookupName(Lookup, S);
11725 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11726 /*AllowInlineNamespace=*/false);
11727 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11728 auto Filter = Lookup.makeFilter();
11729 while (Filter.hasNext()) {
11730 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11731 if (InCompoundScope) {
11732 auto I = UsedAsPrevious.find(PrevDecl);
11733 if (I == UsedAsPrevious.end())
11734 UsedAsPrevious[PrevDecl] = false;
11735 if (auto *D = PrevDecl->getPrevDeclInScope())
11736 UsedAsPrevious[D] = true;
11737 }
11738 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11739 PrevDecl->getLocation();
11740 }
11741 Filter.done();
11742 if (InCompoundScope) {
11743 for (auto &PrevData : UsedAsPrevious) {
11744 if (!PrevData.second) {
11745 PrevDRD = PrevData.first;
11746 break;
11747 }
11748 }
11749 }
11750 } else if (PrevDeclInScope != nullptr) {
11751 auto *PrevDRDInScope = PrevDRD =
11752 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11753 do {
11754 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11755 PrevDRDInScope->getLocation();
11756 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11757 } while (PrevDRDInScope != nullptr);
11758 }
11759 for (auto &TyData : ReductionTypes) {
11760 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11761 bool Invalid = false;
11762 if (I != PreviousRedeclTypes.end()) {
11763 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11764 << TyData.first;
11765 Diag(I->second, diag::note_previous_definition);
11766 Invalid = true;
11767 }
11768 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11769 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11770 Name, TyData.first, PrevDRD);
11771 DC->addDecl(DRD);
11772 DRD->setAccess(AS);
11773 Decls.push_back(DRD);
11774 if (Invalid)
11775 DRD->setInvalidDecl();
11776 else
11777 PrevDRD = DRD;
11778 }
11779
11780 return DeclGroupPtrTy::make(
11781 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11782}
11783
11784void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11785 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11786
11787 // Enter new function scope.
11788 PushFunctionScope();
11789 getCurFunction()->setHasBranchProtectedScope();
11790 getCurFunction()->setHasOMPDeclareReductionCombiner();
11791
11792 if (S != nullptr)
11793 PushDeclContext(S, DRD);
11794 else
11795 CurContext = DRD;
11796
Faisal Valid143a0c2017-04-01 21:30:49 +000011797 PushExpressionEvaluationContext(
11798 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011799
11800 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011801 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11802 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11803 // uses semantics of argument handles by value, but it should be passed by
11804 // reference. C lang does not support references, so pass all parameters as
11805 // pointers.
11806 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011807 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011808 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011809 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11810 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11811 // uses semantics of argument handles by value, but it should be passed by
11812 // reference. C lang does not support references, so pass all parameters as
11813 // pointers.
11814 // Create 'T omp_out;' variable.
11815 auto *OmpOutParm =
11816 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11817 if (S != nullptr) {
11818 PushOnScopeChains(OmpInParm, S);
11819 PushOnScopeChains(OmpOutParm, S);
11820 } else {
11821 DRD->addDecl(OmpInParm);
11822 DRD->addDecl(OmpOutParm);
11823 }
11824}
11825
11826void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11827 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11828 DiscardCleanupsInEvaluationContext();
11829 PopExpressionEvaluationContext();
11830
11831 PopDeclContext();
11832 PopFunctionScopeInfo();
11833
11834 if (Combiner != nullptr)
11835 DRD->setCombiner(Combiner);
11836 else
11837 DRD->setInvalidDecl();
11838}
11839
Alexey Bataev070f43a2017-09-06 14:49:58 +000011840VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011841 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11842
11843 // Enter new function scope.
11844 PushFunctionScope();
11845 getCurFunction()->setHasBranchProtectedScope();
11846
11847 if (S != nullptr)
11848 PushDeclContext(S, DRD);
11849 else
11850 CurContext = DRD;
11851
Faisal Valid143a0c2017-04-01 21:30:49 +000011852 PushExpressionEvaluationContext(
11853 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011854
11855 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011856 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11857 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11858 // uses semantics of argument handles by value, but it should be passed by
11859 // reference. C lang does not support references, so pass all parameters as
11860 // pointers.
11861 // Create 'T omp_priv;' variable.
11862 auto *OmpPrivParm =
11863 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011864 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11865 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11866 // uses semantics of argument handles by value, but it should be passed by
11867 // reference. C lang does not support references, so pass all parameters as
11868 // pointers.
11869 // Create 'T omp_orig;' variable.
11870 auto *OmpOrigParm =
11871 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011872 if (S != nullptr) {
11873 PushOnScopeChains(OmpPrivParm, S);
11874 PushOnScopeChains(OmpOrigParm, S);
11875 } else {
11876 DRD->addDecl(OmpPrivParm);
11877 DRD->addDecl(OmpOrigParm);
11878 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000011879 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011880}
11881
Alexey Bataev070f43a2017-09-06 14:49:58 +000011882void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
11883 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011884 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11885 DiscardCleanupsInEvaluationContext();
11886 PopExpressionEvaluationContext();
11887
11888 PopDeclContext();
11889 PopFunctionScopeInfo();
11890
Alexey Bataev070f43a2017-09-06 14:49:58 +000011891 if (Initializer != nullptr) {
11892 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
11893 } else if (OmpPrivParm->hasInit()) {
11894 DRD->setInitializer(OmpPrivParm->getInit(),
11895 OmpPrivParm->isDirectInit()
11896 ? OMPDeclareReductionDecl::DirectInit
11897 : OMPDeclareReductionDecl::CopyInit);
11898 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011899 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000011900 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011901}
11902
11903Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11904 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11905 for (auto *D : DeclReductions.get()) {
11906 if (IsValid) {
11907 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11908 if (S != nullptr)
11909 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11910 } else
11911 D->setInvalidDecl();
11912 }
11913 return DeclReductions;
11914}
11915
David Majnemer9d168222016-08-05 17:44:54 +000011916OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011917 SourceLocation StartLoc,
11918 SourceLocation LParenLoc,
11919 SourceLocation EndLoc) {
11920 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011921 Stmt *HelperValStmt = nullptr;
11922 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011923
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011924 // OpenMP [teams Constrcut, Restrictions]
11925 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011926 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11927 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011928 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011929
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011930 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11931 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11932 if (CaptureRegion != OMPD_unknown) {
11933 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11934 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11935 HelperValStmt = buildPreInits(Context, Captures);
11936 }
11937
11938 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11939 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011940}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011941
11942OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11943 SourceLocation StartLoc,
11944 SourceLocation LParenLoc,
11945 SourceLocation EndLoc) {
11946 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011947 Stmt *HelperValStmt = nullptr;
11948 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011949
11950 // OpenMP [teams Constrcut, Restrictions]
11951 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011952 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11953 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011954 return nullptr;
11955
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011956 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11957 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11958 if (CaptureRegion != OMPD_unknown) {
11959 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11960 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11961 HelperValStmt = buildPreInits(Context, Captures);
11962 }
11963
11964 return new (Context) OMPThreadLimitClause(
11965 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011966}
Alexey Bataeva0569352015-12-01 10:17:31 +000011967
11968OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11969 SourceLocation StartLoc,
11970 SourceLocation LParenLoc,
11971 SourceLocation EndLoc) {
11972 Expr *ValExpr = Priority;
11973
11974 // OpenMP [2.9.1, task Constrcut]
11975 // The priority-value is a non-negative numerical scalar expression.
11976 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11977 /*StrictlyPositive=*/false))
11978 return nullptr;
11979
11980 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11981}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011982
11983OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11984 SourceLocation StartLoc,
11985 SourceLocation LParenLoc,
11986 SourceLocation EndLoc) {
11987 Expr *ValExpr = Grainsize;
11988
11989 // OpenMP [2.9.2, taskloop Constrcut]
11990 // The parameter of the grainsize clause must be a positive integer
11991 // expression.
11992 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11993 /*StrictlyPositive=*/true))
11994 return nullptr;
11995
11996 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11997}
Alexey Bataev382967a2015-12-08 12:06:20 +000011998
11999OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12000 SourceLocation StartLoc,
12001 SourceLocation LParenLoc,
12002 SourceLocation EndLoc) {
12003 Expr *ValExpr = NumTasks;
12004
12005 // OpenMP [2.9.2, taskloop Constrcut]
12006 // The parameter of the num_tasks clause must be a positive integer
12007 // expression.
12008 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12009 /*StrictlyPositive=*/true))
12010 return nullptr;
12011
12012 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12013}
12014
Alexey Bataev28c75412015-12-15 08:19:24 +000012015OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12016 SourceLocation LParenLoc,
12017 SourceLocation EndLoc) {
12018 // OpenMP [2.13.2, critical construct, Description]
12019 // ... where hint-expression is an integer constant expression that evaluates
12020 // to a valid lock hint.
12021 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12022 if (HintExpr.isInvalid())
12023 return nullptr;
12024 return new (Context)
12025 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12026}
12027
Carlo Bertollib4adf552016-01-15 18:50:31 +000012028OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12029 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12030 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12031 SourceLocation EndLoc) {
12032 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12033 std::string Values;
12034 Values += "'";
12035 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12036 Values += "'";
12037 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12038 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12039 return nullptr;
12040 }
12041 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012042 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012043 if (ChunkSize) {
12044 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12045 !ChunkSize->isInstantiationDependent() &&
12046 !ChunkSize->containsUnexpandedParameterPack()) {
12047 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12048 ExprResult Val =
12049 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12050 if (Val.isInvalid())
12051 return nullptr;
12052
12053 ValExpr = Val.get();
12054
12055 // OpenMP [2.7.1, Restrictions]
12056 // chunk_size must be a loop invariant integer expression with a positive
12057 // value.
12058 llvm::APSInt Result;
12059 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12060 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12061 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12062 << "dist_schedule" << ChunkSize->getSourceRange();
12063 return nullptr;
12064 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012065 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
12066 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000012067 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12068 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12069 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012070 }
12071 }
12072 }
12073
12074 return new (Context)
12075 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012076 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012077}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012078
12079OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12080 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12081 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12082 SourceLocation KindLoc, SourceLocation EndLoc) {
12083 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012084 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012085 std::string Value;
12086 SourceLocation Loc;
12087 Value += "'";
12088 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12089 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012090 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012091 Loc = MLoc;
12092 } else {
12093 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012094 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012095 Loc = KindLoc;
12096 }
12097 Value += "'";
12098 Diag(Loc, diag::err_omp_unexpected_clause_value)
12099 << Value << getOpenMPClauseName(OMPC_defaultmap);
12100 return nullptr;
12101 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012102 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012103
12104 return new (Context)
12105 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12106}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012107
12108bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12109 DeclContext *CurLexicalContext = getCurLexicalContext();
12110 if (!CurLexicalContext->isFileContext() &&
12111 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012112 !CurLexicalContext->isExternCXXContext() &&
12113 !isa<CXXRecordDecl>(CurLexicalContext) &&
12114 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12115 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12116 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012117 Diag(Loc, diag::err_omp_region_not_file_context);
12118 return false;
12119 }
12120 if (IsInOpenMPDeclareTargetContext) {
12121 Diag(Loc, diag::err_omp_enclosed_declare_target);
12122 return false;
12123 }
12124
12125 IsInOpenMPDeclareTargetContext = true;
12126 return true;
12127}
12128
12129void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12130 assert(IsInOpenMPDeclareTargetContext &&
12131 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12132
12133 IsInOpenMPDeclareTargetContext = false;
12134}
12135
David Majnemer9d168222016-08-05 17:44:54 +000012136void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12137 CXXScopeSpec &ScopeSpec,
12138 const DeclarationNameInfo &Id,
12139 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12140 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012141 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12142 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12143
12144 if (Lookup.isAmbiguous())
12145 return;
12146 Lookup.suppressDiagnostics();
12147
12148 if (!Lookup.isSingleResult()) {
12149 if (TypoCorrection Corrected =
12150 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12151 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12152 CTK_ErrorRecovery)) {
12153 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12154 << Id.getName());
12155 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12156 return;
12157 }
12158
12159 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12160 return;
12161 }
12162
12163 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12164 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12165 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12166 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12167
12168 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12169 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12170 ND->addAttr(A);
12171 if (ASTMutationListener *ML = Context.getASTMutationListener())
12172 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12173 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12174 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12175 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12176 << Id.getName();
12177 }
12178 } else
12179 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12180}
12181
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012182static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12183 Sema &SemaRef, Decl *D) {
12184 if (!D)
12185 return;
12186 Decl *LD = nullptr;
12187 if (isa<TagDecl>(D)) {
12188 LD = cast<TagDecl>(D)->getDefinition();
12189 } else if (isa<VarDecl>(D)) {
12190 LD = cast<VarDecl>(D)->getDefinition();
12191
12192 // If this is an implicit variable that is legal and we do not need to do
12193 // anything.
12194 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012195 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12196 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12197 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012198 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012199 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012200 return;
12201 }
12202
12203 } else if (isa<FunctionDecl>(D)) {
12204 const FunctionDecl *FD = nullptr;
12205 if (cast<FunctionDecl>(D)->hasBody(FD))
12206 LD = const_cast<FunctionDecl *>(FD);
12207
12208 // If the definition is associated with the current declaration in the
12209 // target region (it can be e.g. a lambda) that is legal and we do not need
12210 // to do anything else.
12211 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012212 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12213 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12214 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012215 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012216 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012217 return;
12218 }
12219 }
12220 if (!LD)
12221 LD = D;
12222 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12223 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12224 // Outlined declaration is not declared target.
12225 if (LD->isOutOfLine()) {
12226 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12227 SemaRef.Diag(SL, diag::note_used_here) << SR;
12228 } else {
12229 DeclContext *DC = LD->getDeclContext();
12230 while (DC) {
12231 if (isa<FunctionDecl>(DC) &&
12232 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12233 break;
12234 DC = DC->getParent();
12235 }
12236 if (DC)
12237 return;
12238
12239 // Is not declared in target context.
12240 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12241 SemaRef.Diag(SL, diag::note_used_here) << SR;
12242 }
12243 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012244 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12245 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12246 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012247 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012248 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012249 }
12250}
12251
12252static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12253 Sema &SemaRef, DSAStackTy *Stack,
12254 ValueDecl *VD) {
12255 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12256 return true;
12257 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12258 return false;
12259 return true;
12260}
12261
12262void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12263 if (!D || D->isInvalidDecl())
12264 return;
12265 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12266 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12267 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12268 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12269 if (DSAStack->isThreadPrivate(VD)) {
12270 Diag(SL, diag::err_omp_threadprivate_in_target);
12271 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12272 return;
12273 }
12274 }
12275 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12276 // Problem if any with var declared with incomplete type will be reported
12277 // as normal, so no need to check it here.
12278 if ((E || !VD->getType()->isIncompleteType()) &&
12279 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12280 // Mark decl as declared target to prevent further diagnostic.
12281 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012282 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12283 Context, OMPDeclareTargetDeclAttr::MT_To);
12284 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012285 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012286 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012287 }
12288 return;
12289 }
12290 }
12291 if (!E) {
12292 // Checking declaration inside declare target region.
12293 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12294 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012295 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12296 Context, OMPDeclareTargetDeclAttr::MT_To);
12297 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012298 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012299 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012300 }
12301 return;
12302 }
12303 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12304}
Samuel Antao661c0902016-05-26 17:39:58 +000012305
12306OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12307 SourceLocation StartLoc,
12308 SourceLocation LParenLoc,
12309 SourceLocation EndLoc) {
12310 MappableVarListInfo MVLI(VarList);
12311 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12312 if (MVLI.ProcessedVarList.empty())
12313 return nullptr;
12314
12315 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12316 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12317 MVLI.VarComponents);
12318}
Samuel Antaoec172c62016-05-26 17:49:04 +000012319
12320OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12321 SourceLocation StartLoc,
12322 SourceLocation LParenLoc,
12323 SourceLocation EndLoc) {
12324 MappableVarListInfo MVLI(VarList);
12325 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12326 if (MVLI.ProcessedVarList.empty())
12327 return nullptr;
12328
12329 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12330 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12331 MVLI.VarComponents);
12332}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012333
12334OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12335 SourceLocation StartLoc,
12336 SourceLocation LParenLoc,
12337 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012338 MappableVarListInfo MVLI(VarList);
12339 SmallVector<Expr *, 8> PrivateCopies;
12340 SmallVector<Expr *, 8> Inits;
12341
Carlo Bertolli2404b172016-07-13 15:37:16 +000012342 for (auto &RefExpr : VarList) {
12343 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12344 SourceLocation ELoc;
12345 SourceRange ERange;
12346 Expr *SimpleRefExpr = RefExpr;
12347 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12348 if (Res.second) {
12349 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012350 MVLI.ProcessedVarList.push_back(RefExpr);
12351 PrivateCopies.push_back(nullptr);
12352 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012353 }
12354 ValueDecl *D = Res.first;
12355 if (!D)
12356 continue;
12357
12358 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012359 Type = Type.getNonReferenceType().getUnqualifiedType();
12360
12361 auto *VD = dyn_cast<VarDecl>(D);
12362
12363 // Item should be a pointer or reference to pointer.
12364 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012365 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12366 << 0 << RefExpr->getSourceRange();
12367 continue;
12368 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012369
12370 // Build the private variable and the expression that refers to it.
12371 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12372 D->hasAttrs() ? &D->getAttrs() : nullptr);
12373 if (VDPrivate->isInvalidDecl())
12374 continue;
12375
12376 CurContext->addDecl(VDPrivate);
12377 auto VDPrivateRefExpr = buildDeclRefExpr(
12378 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12379
12380 // Add temporary variable to initialize the private copy of the pointer.
12381 auto *VDInit =
12382 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12383 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12384 RefExpr->getExprLoc());
12385 AddInitializerToDecl(VDPrivate,
12386 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012387 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012388
12389 // If required, build a capture to implement the privatization initialized
12390 // with the current list item value.
12391 DeclRefExpr *Ref = nullptr;
12392 if (!VD)
12393 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12394 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12395 PrivateCopies.push_back(VDPrivateRefExpr);
12396 Inits.push_back(VDInitRefExpr);
12397
12398 // We need to add a data sharing attribute for this variable to make sure it
12399 // is correctly captured. A variable that shows up in a use_device_ptr has
12400 // similar properties of a first private variable.
12401 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12402
12403 // Create a mappable component for the list item. List items in this clause
12404 // only need a component.
12405 MVLI.VarBaseDeclarations.push_back(D);
12406 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12407 MVLI.VarComponents.back().push_back(
12408 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012409 }
12410
Samuel Antaocc10b852016-07-28 14:23:26 +000012411 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012412 return nullptr;
12413
Samuel Antaocc10b852016-07-28 14:23:26 +000012414 return OMPUseDevicePtrClause::Create(
12415 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12416 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012417}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012418
12419OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12420 SourceLocation StartLoc,
12421 SourceLocation LParenLoc,
12422 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012423 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012424 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012425 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012426 SourceLocation ELoc;
12427 SourceRange ERange;
12428 Expr *SimpleRefExpr = RefExpr;
12429 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12430 if (Res.second) {
12431 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012432 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012433 }
12434 ValueDecl *D = Res.first;
12435 if (!D)
12436 continue;
12437
12438 QualType Type = D->getType();
12439 // item should be a pointer or array or reference to pointer or array
12440 if (!Type.getNonReferenceType()->isPointerType() &&
12441 !Type.getNonReferenceType()->isArrayType()) {
12442 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12443 << 0 << RefExpr->getSourceRange();
12444 continue;
12445 }
Samuel Antao6890b092016-07-28 14:25:09 +000012446
12447 // Check if the declaration in the clause does not show up in any data
12448 // sharing attribute.
12449 auto DVar = DSAStack->getTopDSA(D, false);
12450 if (isOpenMPPrivate(DVar.CKind)) {
12451 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12452 << getOpenMPClauseName(DVar.CKind)
12453 << getOpenMPClauseName(OMPC_is_device_ptr)
12454 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12455 ReportOriginalDSA(*this, DSAStack, D, DVar);
12456 continue;
12457 }
12458
12459 Expr *ConflictExpr;
12460 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012461 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012462 [&ConflictExpr](
12463 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12464 OpenMPClauseKind) -> bool {
12465 ConflictExpr = R.front().getAssociatedExpression();
12466 return true;
12467 })) {
12468 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12469 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12470 << ConflictExpr->getSourceRange();
12471 continue;
12472 }
12473
12474 // Store the components in the stack so that they can be used to check
12475 // against other clauses later on.
12476 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12477 DSAStack->addMappableExpressionComponents(
12478 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12479
12480 // Record the expression we've just processed.
12481 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12482
12483 // Create a mappable component for the list item. List items in this clause
12484 // only need a component. We use a null declaration to signal fields in
12485 // 'this'.
12486 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12487 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12488 "Unexpected device pointer expression!");
12489 MVLI.VarBaseDeclarations.push_back(
12490 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12491 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12492 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012493 }
12494
Samuel Antao6890b092016-07-28 14:25:09 +000012495 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012496 return nullptr;
12497
Samuel Antao6890b092016-07-28 14:25:09 +000012498 return OMPIsDevicePtrClause::Create(
12499 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12500 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012501}