blob: 6c56d0c185a68cc70417c29567824fd783731a22 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataevf47c4b42017-09-26 13:47:31 +000038static Expr *CheckMapClauseExpressionBase(
39 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41 OpenMPClauseKind CKind);
42
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
44/// \brief Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000046 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000048 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Alexey Bataev758e55e2013-09-06 18:03:48 +000057/// \brief Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000059class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000061 struct DSAVarData final {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataevf189cb72017-07-24 14:52:13 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000072 };
Alexey Bataev8b427062016-05-25 12:36:08 +000073 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
74 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000075
Alexey Bataev758e55e2013-09-06 18:03:48 +000076private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000077 struct DSAInfo final {
78 OpenMPClauseKind Attributes = OMPC_unknown;
79 /// Pointer to a reference expression and a flag which shows that the
80 /// variable is marked as lastprivate(true) or not (false).
81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
82 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000083 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000084 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000086 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000088 /// Struct that associates a component with the clause kind where they are
89 /// found.
90 struct MappedExprComponentTy {
91 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
92 OpenMPClauseKind Kind = OMPC_unknown;
93 };
94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000095 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000096 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000098 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
99 DoacrossDependMapTy;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 struct ReductionData {
Alexey Bataevf87fa882017-07-21 19:26:22 +0000101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 ReductionData() = default;
105 void set(BinaryOperatorKind BO, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = BO;
108 }
109 void set(const Expr *RefExpr, SourceRange RR) {
110 ReductionRange = RR;
111 ReductionOp = RefExpr;
112 }
113 };
114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000115
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000116 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000117 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000118 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000119 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000120 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000121 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000123 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
125 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000127 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000129 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
131 /// get the data (loop counters etc.) about enclosing loop-based construct.
132 /// This data is required during codegen.
133 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000134 /// \brief first argument (Expr *) contains optional argument of the
135 /// 'ordered' clause, the second one is true if the regions has 'ordered'
136 /// clause, false otherwise.
137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000138 bool NowaitRegion = false;
139 bool CancelRegion = false;
140 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000141 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000142 /// Reference to the taskgroup task_reduction reference expression.
143 Expr *TaskgroupReductionRef = nullptr;
Alexey Bataeved09d242014-05-28 05:53:51 +0000144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000145 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
147 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000148 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 };
150
Axel Naumann323862e2016-02-03 10:45:22 +0000151 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000152
153 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000154 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000157 /// \brief true, if check for DSA must be from parent directive, false, if
158 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000159 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000160 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000161 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000162 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
165
David Majnemer9d168222016-08-05 17:44:54 +0000166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000167
168 /// \brief Checks if the variable is a local for OpenMP region.
169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000170
Alexey Bataev4b465392017-04-26 15:06:24 +0000171 bool isStackEmpty() const {
172 return Stack.empty() ||
173 Stack.back().second != CurrentNonCapturingFunctionScope ||
174 Stack.back().first.empty();
175 }
176
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000178 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000179
Alexey Bataevaac108a2015-06-23 04:51:00 +0000180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
181 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000182
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000183 bool isForceVarCapturing() const { return ForceCapturing; }
184 void setForceVarCapturing(bool V) { ForceCapturing = V; }
185
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000187 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000188 if (Stack.empty() ||
189 Stack.back().second != CurrentNonCapturingFunctionScope)
190 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
191 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
192 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000193 }
194
195 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000196 assert(!Stack.back().first.empty() &&
197 "Data-sharing attributes stack is empty!");
198 Stack.back().first.pop_back();
199 }
200
201 /// Start new OpenMP region stack in new non-capturing function.
202 void pushFunction() {
203 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
204 assert(!isa<CapturingScopeInfo>(CurFnScope));
205 CurrentNonCapturingFunctionScope = CurFnScope;
206 }
207 /// Pop region stack for non-capturing function.
208 void popFunction(const FunctionScopeInfo *OldFSI) {
209 if (!Stack.empty() && Stack.back().second == OldFSI) {
210 assert(Stack.back().first.empty());
211 Stack.pop_back();
212 }
213 CurrentNonCapturingFunctionScope = nullptr;
214 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
215 if (!isa<CapturingScopeInfo>(FSI)) {
216 CurrentNonCapturingFunctionScope = FSI;
217 break;
218 }
219 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220 }
221
Alexey Bataev28c75412015-12-15 08:19:24 +0000222 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
223 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
224 }
225 const std::pair<OMPCriticalDirective *, llvm::APSInt>
226 getCriticalWithHint(const DeclarationNameInfo &Name) const {
227 auto I = Criticals.find(Name.getAsString());
228 if (I != Criticals.end())
229 return I->second;
230 return std::make_pair(nullptr, llvm::APSInt());
231 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000232 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000233 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000234 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000235 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000236
Alexey Bataev9c821032015-04-30 04:23:23 +0000237 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000238 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000239 /// \brief Check if the specified variable is a loop control variable for
240 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000241 /// \return The index of the loop control variable in the list of associated
242 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000243 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000244 /// \brief Check if the specified variable is a loop control variable for
245 /// parent region.
246 /// \return The index of the loop control variable in the list of associated
247 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000248 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000249 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
250 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000251 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000252
Alexey Bataev758e55e2013-09-06 18:03:48 +0000253 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000254 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
255 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256
Alexey Bataevfa312f32017-07-21 18:48:21 +0000257 /// Adds additional information for the reduction items with the reduction id
258 /// represented as an operator.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000259 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
260 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000261 /// Adds additional information for the reduction items with the reduction id
262 /// represented as reduction identifier.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000265 /// Returns the location and reduction operation from the innermost parent
266 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000267 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000268 BinaryOperatorKind &BOK,
269 Expr *&TaskgroupDescriptor);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000270 /// Returns the location and reduction operation from the innermost parent
271 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000272 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000273 const Expr *&ReductionRef,
274 Expr *&TaskgroupDescriptor);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000275 /// Return reduction reference expression for the current taskgroup.
276 Expr *getTaskgroupReductionRef() const {
277 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
278 "taskgroup reference expression requested for non taskgroup "
279 "directive.");
280 return Stack.back().first.back().TaskgroupReductionRef;
281 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000282 /// Checks if the given \p VD declaration is actually a taskgroup reduction
283 /// descriptor variable at the \p Level of OpenMP regions.
284 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
285 return Stack.back().first[Level].TaskgroupReductionRef &&
286 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
287 ->getDecl() == VD;
288 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000289
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 /// \brief Returns data sharing attributes from top of the stack for the
291 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000292 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000293 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000294 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000295 /// \brief Checks if the specified variables has data-sharing attributes which
296 /// match specified \a CPred predicate in any directive which matches \a DPred
297 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000298 DSAVarData hasDSA(ValueDecl *D,
299 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
300 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
301 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000302 /// \brief Checks if the specified variables has data-sharing attributes which
303 /// match specified \a CPred predicate in any innermost directive which
304 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000305 DSAVarData
306 hasInnermostDSA(ValueDecl *D,
307 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
308 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
309 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000310 /// \brief Checks if the specified variables has explicit data-sharing
311 /// attributes which match specified \a CPred predicate at the specified
312 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000313 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000314 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000315 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000316
317 /// \brief Returns true if the directive at level \Level matches in the
318 /// specified \a DPred predicate.
319 bool hasExplicitDirective(
320 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
321 unsigned Level);
322
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000323 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000324 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
325 const DeclarationNameInfo &,
326 SourceLocation)> &DPred,
327 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000328
Alexey Bataev758e55e2013-09-06 18:03:48 +0000329 /// \brief Returns currently analyzed directive.
330 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000331 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000332 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000333 /// \brief Returns parent directive.
334 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 if (isStackEmpty() || Stack.back().first.size() == 1)
336 return OMPD_unknown;
337 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000338 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000339
340 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000341 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000342 assert(!isStackEmpty());
343 Stack.back().first.back().DefaultAttr = DSA_none;
344 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000345 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000346 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000347 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000348 assert(!isStackEmpty());
349 Stack.back().first.back().DefaultAttr = DSA_shared;
350 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000351 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000352 /// Set default data mapping attribute to 'tofrom:scalar'.
353 void setDefaultDMAToFromScalar(SourceLocation Loc) {
354 assert(!isStackEmpty());
355 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
356 Stack.back().first.back().DefaultMapAttrLoc = Loc;
357 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000358
359 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000360 return isStackEmpty() ? DSA_unspecified
361 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000362 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000363 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000364 return isStackEmpty() ? SourceLocation()
365 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000366 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000367 DefaultMapAttributes getDefaultDMA() const {
368 return isStackEmpty() ? DMA_unspecified
369 : Stack.back().first.back().DefaultMapAttr;
370 }
371 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
372 return Stack.back().first[Level].DefaultMapAttr;
373 }
374 SourceLocation getDefaultDMALocation() const {
375 return isStackEmpty() ? SourceLocation()
376 : Stack.back().first.back().DefaultMapAttrLoc;
377 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000378
Alexey Bataevf29276e2014-06-18 04:14:57 +0000379 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000380 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000381 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000382 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000383 }
384
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000385 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000386 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000387 assert(!isStackEmpty());
388 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
389 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000390 }
391 /// \brief Returns true, if parent region is ordered (has associated
392 /// 'ordered' clause), false - otherwise.
393 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000394 if (isStackEmpty() || Stack.back().first.size() == 1)
395 return false;
396 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000397 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000398 /// \brief Returns optional parameter for the ordered region.
399 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000400 if (isStackEmpty() || Stack.back().first.size() == 1)
401 return nullptr;
402 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000403 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000404 /// \brief Marks current region as nowait (it has a 'nowait' clause).
405 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000406 assert(!isStackEmpty());
407 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000408 }
409 /// \brief Returns true, if parent region is nowait (has associated
410 /// 'nowait' clause), false - otherwise.
411 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000412 if (isStackEmpty() || Stack.back().first.size() == 1)
413 return false;
414 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000415 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000416 /// \brief Marks parent region as cancel region.
417 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000418 if (!isStackEmpty() && Stack.back().first.size() > 1) {
419 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
420 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
421 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000422 }
423 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000424 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000425 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000426 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000427
Alexey Bataev9c821032015-04-30 04:23:23 +0000428 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000429 void setAssociatedLoops(unsigned Val) {
430 assert(!isStackEmpty());
431 Stack.back().first.back().AssociatedLoops = Val;
432 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000433 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000434 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000435 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000436 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000437
Alexey Bataev13314bf2014-10-09 04:18:56 +0000438 /// \brief Marks current target region as one with closely nested teams
439 /// region.
440 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000441 if (!isStackEmpty() && Stack.back().first.size() > 1) {
442 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
443 TeamsRegionLoc;
444 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000445 }
446 /// \brief Returns true, if current region has closely nested teams region.
447 bool hasInnerTeamsRegion() const {
448 return getInnerTeamsRegionLoc().isValid();
449 }
450 /// \brief Returns location of the nested teams region (if any).
451 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000452 return isStackEmpty() ? SourceLocation()
453 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000454 }
455
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000456 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000457 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000458 }
459 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000460 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000461 }
462 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000463 return isStackEmpty() ? SourceLocation()
464 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000465 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000466
Samuel Antao4c8035b2016-12-12 18:00:20 +0000467 /// Do the check specified in \a Check to all component lists and return true
468 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000469 bool checkMappableExprComponentListsForDecl(
470 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000471 const llvm::function_ref<
472 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
473 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000474 if (isStackEmpty())
475 return false;
476 auto SI = Stack.back().first.rbegin();
477 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000478
479 if (SI == SE)
480 return false;
481
482 if (CurrentRegionOnly) {
483 SE = std::next(SI);
484 } else {
485 ++SI;
486 }
487
488 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000489 auto MI = SI->MappedExprComponents.find(VD);
490 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000491 for (auto &L : MI->second.Components)
492 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000493 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000494 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000495 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000496 }
497
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000498 /// Do the check specified in \a Check to all component lists at a given level
499 /// and return true if any issue is found.
500 bool checkMappableExprComponentListsForDeclAtLevel(
501 ValueDecl *VD, unsigned Level,
502 const llvm::function_ref<
503 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
504 OpenMPClauseKind)> &Check) {
505 if (isStackEmpty())
506 return false;
507
508 auto StartI = Stack.back().first.begin();
509 auto EndI = Stack.back().first.end();
510 if (std::distance(StartI, EndI) <= (int)Level)
511 return false;
512 std::advance(StartI, Level);
513
514 auto MI = StartI->MappedExprComponents.find(VD);
515 if (MI != StartI->MappedExprComponents.end())
516 for (auto &L : MI->second.Components)
517 if (Check(L, MI->second.Kind))
518 return true;
519 return false;
520 }
521
Samuel Antao4c8035b2016-12-12 18:00:20 +0000522 /// Create a new mappable expression component list associated with a given
523 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000524 void addMappableExpressionComponents(
525 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000526 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
527 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000528 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000529 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000530 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000531 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000532 MEC.Components.resize(MEC.Components.size() + 1);
533 MEC.Components.back().append(Components.begin(), Components.end());
534 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000535 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000536
537 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000538 assert(!isStackEmpty());
539 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000540 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000541 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000542 assert(!isStackEmpty() && Stack.back().first.size() > 1);
543 auto &StackElem = *std::next(Stack.back().first.rbegin());
544 assert(isOpenMPWorksharingDirective(StackElem.Directive));
545 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000546 }
547 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
548 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000549 assert(!isStackEmpty());
550 auto &StackElem = Stack.back().first.back();
551 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
552 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000553 return llvm::make_range(Ref.begin(), Ref.end());
554 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000555 return llvm::make_range(StackElem.DoacrossDepends.end(),
556 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000557 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000558};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000559bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000560 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
561 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000562}
Alexey Bataeved09d242014-05-28 05:53:51 +0000563} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000564
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000565static Expr *getExprAsWritten(Expr *E) {
566 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
567 E = ExprTemp->getSubExpr();
568
569 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
570 E = MTE->GetTemporaryExpr();
571
572 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
573 E = Binder->getSubExpr();
574
575 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
576 E = ICE->getSubExprAsWritten();
577 return E->IgnoreParens();
578}
579
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000580static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000581 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
582 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
583 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000584 auto *VD = dyn_cast<VarDecl>(D);
585 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000586 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000587 VD = VD->getCanonicalDecl();
588 D = VD;
589 } else {
590 assert(FD);
591 FD = FD->getCanonicalDecl();
592 D = FD;
593 }
594 return D;
595}
596
David Majnemer9d168222016-08-05 17:44:54 +0000597DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000598 ValueDecl *D) {
599 D = getCanonicalDecl(D);
600 auto *VD = dyn_cast<VarDecl>(D);
601 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000602 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000603 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000604 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
605 // in a region but not in construct]
606 // File-scope or namespace-scope variables referenced in called routines
607 // in the region are shared unless they appear in a threadprivate
608 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000609 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000610 DVar.CKind = OMPC_shared;
611
612 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
613 // in a region but not in construct]
614 // Variables with static storage duration that are declared in called
615 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000616 if (VD && VD->hasGlobalStorage())
617 DVar.CKind = OMPC_shared;
618
619 // Non-static data members are shared by default.
620 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000621 DVar.CKind = OMPC_shared;
622
Alexey Bataev758e55e2013-09-06 18:03:48 +0000623 return DVar;
624 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000625
Alexey Bataevec3da872014-01-31 05:15:34 +0000626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
627 // in a Construct, C/C++, predetermined, p.1]
628 // Variables with automatic storage duration that are declared in a scope
629 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000630 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
631 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000632 DVar.CKind = OMPC_private;
633 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000634 }
635
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000636 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000637 // Explicitly specified attributes and local variables with predetermined
638 // attributes.
639 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000640 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000641 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000642 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000643 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000644 return DVar;
645 }
646
647 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
648 // in a Construct, C/C++, implicitly determined, p.1]
649 // In a parallel or task construct, the data-sharing attributes of these
650 // variables are determined by the default clause, if present.
651 switch (Iter->DefaultAttr) {
652 case DSA_shared:
653 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000654 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000655 return DVar;
656 case DSA_none:
657 return DVar;
658 case DSA_unspecified:
659 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
660 // in a Construct, implicitly determined, p.2]
661 // In a parallel construct, if no default clause is present, these
662 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000664 if (isOpenMPParallelDirective(DVar.DKind) ||
665 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000666 DVar.CKind = OMPC_shared;
667 return DVar;
668 }
669
670 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
671 // in a Construct, implicitly determined, p.4]
672 // In a task construct, if no default clause is present, a variable that in
673 // the enclosing context is determined to be shared by all implicit tasks
674 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000675 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000676 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000677 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000678 do {
679 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000680 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000681 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000682 // In a task construct, if no default clause is present, a variable
683 // whose data-sharing attribute is not determined by the rules above is
684 // firstprivate.
685 DVarTemp = getDSA(I, D);
686 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000687 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000688 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000689 return DVar;
690 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000691 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000692 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000693 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 return DVar;
695 }
696 }
697 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
698 // in a Construct, implicitly determined, p.3]
699 // For constructs other than task, if no default clause is present, these
700 // variables inherit their data-sharing attributes from the enclosing
701 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000702 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000703}
704
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000705Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000706 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000707 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000708 auto &StackElem = Stack.back().first.back();
709 auto It = StackElem.AlignedMap.find(D);
710 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000711 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000712 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000713 return nullptr;
714 } else {
715 assert(It->second && "Unexpected nullptr expr in the aligned map");
716 return It->second;
717 }
718 return nullptr;
719}
720
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000721void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000722 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000723 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000724 auto &StackElem = Stack.back().first.back();
725 StackElem.LCVMap.insert(
726 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000727}
728
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000729DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000730 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000731 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000732 auto &StackElem = Stack.back().first.back();
733 auto It = StackElem.LCVMap.find(D);
734 if (It != StackElem.LCVMap.end())
735 return It->second;
736 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000737}
738
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000739DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000740 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
741 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000742 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000743 auto &StackElem = *std::next(Stack.back().first.rbegin());
744 auto It = StackElem.LCVMap.find(D);
745 if (It != StackElem.LCVMap.end())
746 return It->second;
747 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000748}
749
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000750ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000751 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
752 "Data-sharing attributes stack is empty");
753 auto &StackElem = *std::next(Stack.back().first.rbegin());
754 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000755 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000756 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000757 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000758 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000759 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000760}
761
Alexey Bataev90c228f2016-02-08 09:29:13 +0000762void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
763 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000764 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000765 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000766 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000767 Data.Attributes = A;
768 Data.RefExpr.setPointer(E);
769 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000770 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000771 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
772 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
774 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
775 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
776 (isLoopControlVariable(D).first && A == OMPC_private));
777 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
778 Data.RefExpr.setInt(/*IntVal=*/true);
779 return;
780 }
781 const bool IsLastprivate =
782 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
783 Data.Attributes = A;
784 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
785 Data.PrivateCopy = PrivateCopy;
786 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000787 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000788 Data.Attributes = A;
789 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
790 Data.PrivateCopy = nullptr;
791 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000792 }
793}
794
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000795/// \brief Build a variable declaration for OpenMP loop iteration variable.
796static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
797 StringRef Name, const AttrVec *Attrs = nullptr) {
798 DeclContext *DC = SemaRef.CurContext;
799 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
800 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
801 VarDecl *Decl =
802 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
803 if (Attrs) {
804 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
805 I != E; ++I)
806 Decl->addAttr(*I);
807 }
808 Decl->setImplicit();
809 return Decl;
810}
811
812static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
813 SourceLocation Loc,
814 bool RefersToCapture = false) {
815 D->setReferenced();
816 D->markUsed(S.Context);
817 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
818 SourceLocation(), D, RefersToCapture, Loc, Ty,
819 VK_LValue);
820}
821
822void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
823 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000824 D = getCanonicalDecl(D);
825 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000826 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000827 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000828 "Additional reduction info may be specified only for reduction items.");
829 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
830 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000831 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000832 "Additional reduction info may be specified only once for reduction "
833 "items.");
834 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000835 Expr *&TaskgroupReductionRef =
836 Stack.back().first.back().TaskgroupReductionRef;
837 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000838 auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000839 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000840 TaskgroupReductionRef =
841 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000842 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000843}
844
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000845void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
846 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000847 D = getCanonicalDecl(D);
848 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000849 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000850 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000851 "Additional reduction info may be specified only for reduction items.");
852 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
853 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000854 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000855 "Additional reduction info may be specified only once for reduction "
856 "items.");
857 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000858 Expr *&TaskgroupReductionRef =
859 Stack.back().first.back().TaskgroupReductionRef;
860 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000861 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
862 ".task_red.");
863 TaskgroupReductionRef =
864 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000865 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000866}
867
Alexey Bataevf189cb72017-07-24 14:52:13 +0000868DSAStackTy::DSAVarData
869DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000870 BinaryOperatorKind &BOK,
871 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000872 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000873 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
874 if (Stack.back().first.empty())
875 return DSAVarData();
876 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000877 E = Stack.back().first.rend();
878 I != E; std::advance(I, 1)) {
879 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000880 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000881 continue;
882 auto &ReductionData = I->ReductionMap[D];
883 if (!ReductionData.ReductionOp ||
884 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000885 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000887 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000888 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
889 "expression for the descriptor is not "
890 "set.");
891 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000892 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
893 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000894 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000895 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000896}
897
Alexey Bataevf189cb72017-07-24 14:52:13 +0000898DSAStackTy::DSAVarData
899DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000900 const Expr *&ReductionRef,
901 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000902 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000903 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
904 if (Stack.back().first.empty())
905 return DSAVarData();
906 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000907 E = Stack.back().first.rend();
908 I != E; std::advance(I, 1)) {
909 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000910 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000911 continue;
912 auto &ReductionData = I->ReductionMap[D];
913 if (!ReductionData.ReductionOp ||
914 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000915 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000916 SR = ReductionData.ReductionRange;
917 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000918 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
919 "expression for the descriptor is not "
920 "set.");
921 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000922 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
923 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000924 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000925 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000926}
927
Alexey Bataeved09d242014-05-28 05:53:51 +0000928bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000929 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000930 if (!isStackEmpty() && Stack.back().first.size() > 1) {
931 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000932 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000933 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000934 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000935 if (I == E)
936 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000937 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000938 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000939 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000940 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000941 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000942 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000943 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000944}
945
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000946DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
947 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000948 DSAVarData DVar;
949
950 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
951 // in a Construct, C/C++, predetermined, p.1]
952 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000953 auto *VD = dyn_cast<VarDecl>(D);
954 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
955 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000956 SemaRef.getLangOpts().OpenMPUseTLS &&
957 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000958 (VD && VD->getStorageClass() == SC_Register &&
959 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
960 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000961 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000962 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000963 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000964 auto TI = Threadprivates.find(D);
965 if (TI != Threadprivates.end()) {
966 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000967 DVar.CKind = OMPC_threadprivate;
968 return DVar;
Alexey Bataev817d7f32017-11-14 21:01:01 +0000969 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
970 DVar.RefExpr = buildDeclRefExpr(
971 SemaRef, VD, D->getType().getNonReferenceType(),
972 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
973 DVar.CKind = OMPC_threadprivate;
974 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 }
976
Alexey Bataev4b465392017-04-26 15:06:24 +0000977 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000978 // Not in OpenMP execution region and top scope was already checked.
979 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000980
Alexey Bataev758e55e2013-09-06 18:03:48 +0000981 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000982 // in a Construct, C/C++, predetermined, p.4]
983 // Static data members are shared.
984 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
985 // in a Construct, C/C++, predetermined, p.7]
986 // Variables with static storage duration that are declared in a scope
987 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000988 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000989 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000990 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000991 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000992 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000993
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000994 DVar.CKind = OMPC_shared;
995 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000996 }
997
998 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000999 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1000 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001001 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1002 // in a Construct, C/C++, predetermined, p.6]
1003 // Variables with const qualified type having no mutable member are
1004 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001005 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001006 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001007 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1008 if (auto *CTD = CTSD->getSpecializedTemplate())
1009 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001010 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001011 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1012 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001013 // Variables with const-qualified type having no mutable member may be
1014 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001015 DSAVarData DVarTemp = hasDSA(
1016 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1017 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001018 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1019 return DVar;
1020
Alexey Bataev758e55e2013-09-06 18:03:48 +00001021 DVar.CKind = OMPC_shared;
1022 return DVar;
1023 }
1024
Alexey Bataev758e55e2013-09-06 18:03:48 +00001025 // Explicitly specified attributes and local variables with predetermined
1026 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001027 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001028 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001029 if (FromParent && I != EndI)
1030 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001031 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001032 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001033 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001034 DVar.CKind = I->SharingMap[D].Attributes;
1035 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001036 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001037 }
1038
1039 return DVar;
1040}
1041
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001042DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1043 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001044 if (isStackEmpty()) {
1045 StackTy::reverse_iterator I;
1046 return getDSA(I, D);
1047 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001048 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001049 auto StartI = Stack.back().first.rbegin();
1050 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001051 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001052 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001053 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054}
1055
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001056DSAStackTy::DSAVarData
1057DSAStackTy::hasDSA(ValueDecl *D,
1058 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1059 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1060 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001061 if (isStackEmpty())
1062 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001063 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001064 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001065 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001066 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001067 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001068 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001069 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001070 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001071 auto NewI = I;
1072 DSAVarData DVar = getDSA(NewI, D);
1073 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001074 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001075 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001076 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001077}
1078
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001079DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1080 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1081 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1082 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001083 if (isStackEmpty())
1084 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001085 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001086 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001087 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001088 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001089 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001090 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001091 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001092 auto NewI = StartI;
1093 DSAVarData DVar = getDSA(NewI, D);
1094 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001095}
1096
Alexey Bataevaac108a2015-06-23 04:51:00 +00001097bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001098 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001099 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001100 if (CPred(ClauseKindMode))
1101 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 if (isStackEmpty())
1103 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001105 auto StartI = Stack.back().first.begin();
1106 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001107 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001108 return false;
1109 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001110 return (StartI->SharingMap.count(D) > 0) &&
1111 StartI->SharingMap[D].RefExpr.getPointer() &&
1112 CPred(StartI->SharingMap[D].Attributes) &&
1113 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001114}
1115
Samuel Antao4be30e92015-10-02 17:14:03 +00001116bool DSAStackTy::hasExplicitDirective(
1117 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1118 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001119 if (isStackEmpty())
1120 return false;
1121 auto StartI = Stack.back().first.begin();
1122 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001123 if (std::distance(StartI, EndI) <= (int)Level)
1124 return false;
1125 std::advance(StartI, Level);
1126 return DPred(StartI->Directive);
1127}
1128
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001129bool DSAStackTy::hasDirective(
1130 const llvm::function_ref<bool(OpenMPDirectiveKind,
1131 const DeclarationNameInfo &, SourceLocation)>
1132 &DPred,
1133 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001134 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001135 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001136 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001137 auto StartI = std::next(Stack.back().first.rbegin());
1138 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001139 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001140 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001141 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1142 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1143 return true;
1144 }
1145 return false;
1146}
1147
Alexey Bataev758e55e2013-09-06 18:03:48 +00001148void Sema::InitDataSharingAttributesStack() {
1149 VarDataSharingAttributesStack = new DSAStackTy(*this);
1150}
1151
1152#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1153
Alexey Bataev4b465392017-04-26 15:06:24 +00001154void Sema::pushOpenMPFunctionRegion() {
1155 DSAStack->pushFunction();
1156}
1157
1158void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1159 DSAStack->popFunction(OldFSI);
1160}
1161
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001162bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001163 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1164
1165 auto &Ctx = getASTContext();
1166 bool IsByRef = true;
1167
1168 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001169 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001170 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001171
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001172 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001173 // This table summarizes how a given variable should be passed to the device
1174 // given its type and the clauses where it appears. This table is based on
1175 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1176 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1177 //
1178 // =========================================================================
1179 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1180 // | |(tofrom:scalar)| | pvt | | | |
1181 // =========================================================================
1182 // | scl | | | | - | | bycopy|
1183 // | scl | | - | x | - | - | bycopy|
1184 // | scl | | x | - | - | - | null |
1185 // | scl | x | | | - | | byref |
1186 // | scl | x | - | x | - | - | bycopy|
1187 // | scl | x | x | - | - | - | null |
1188 // | scl | | - | - | - | x | byref |
1189 // | scl | x | - | - | - | x | byref |
1190 //
1191 // | agg | n.a. | | | - | | byref |
1192 // | agg | n.a. | - | x | - | - | byref |
1193 // | agg | n.a. | x | - | - | - | null |
1194 // | agg | n.a. | - | - | - | x | byref |
1195 // | agg | n.a. | - | - | - | x[] | byref |
1196 //
1197 // | ptr | n.a. | | | - | | bycopy|
1198 // | ptr | n.a. | - | x | - | - | bycopy|
1199 // | ptr | n.a. | x | - | - | - | null |
1200 // | ptr | n.a. | - | - | - | x | byref |
1201 // | ptr | n.a. | - | - | - | x[] | bycopy|
1202 // | ptr | n.a. | - | - | x | | bycopy|
1203 // | ptr | n.a. | - | - | x | x | bycopy|
1204 // | ptr | n.a. | - | - | x | x[] | bycopy|
1205 // =========================================================================
1206 // Legend:
1207 // scl - scalar
1208 // ptr - pointer
1209 // agg - aggregate
1210 // x - applies
1211 // - - invalid in this combination
1212 // [] - mapped with an array section
1213 // byref - should be mapped by reference
1214 // byval - should be mapped by value
1215 // null - initialize a local variable to null on the device
1216 //
1217 // Observations:
1218 // - All scalar declarations that show up in a map clause have to be passed
1219 // by reference, because they may have been mapped in the enclosing data
1220 // environment.
1221 // - If the scalar value does not fit the size of uintptr, it has to be
1222 // passed by reference, regardless the result in the table above.
1223 // - For pointers mapped by value that have either an implicit map or an
1224 // array section, the runtime library may pass the NULL value to the
1225 // device instead of the value passed to it by the compiler.
1226
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001227 if (Ty->isReferenceType())
1228 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001229
1230 // Locate map clauses and see if the variable being captured is referred to
1231 // in any of those clauses. Here we only care about variables, not fields,
1232 // because fields are part of aggregates.
1233 bool IsVariableUsedInMapClause = false;
1234 bool IsVariableAssociatedWithSection = false;
1235
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001236 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1237 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001238 MapExprComponents,
1239 OpenMPClauseKind WhereFoundClauseKind) {
1240 // Only the map clause information influences how a variable is
1241 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001242 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001243 if (WhereFoundClauseKind != OMPC_map)
1244 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001245
1246 auto EI = MapExprComponents.rbegin();
1247 auto EE = MapExprComponents.rend();
1248
1249 assert(EI != EE && "Invalid map expression!");
1250
1251 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1252 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1253
1254 ++EI;
1255 if (EI == EE)
1256 return false;
1257
1258 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1259 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1260 isa<MemberExpr>(EI->getAssociatedExpression())) {
1261 IsVariableAssociatedWithSection = true;
1262 // There is nothing more we need to know about this variable.
1263 return true;
1264 }
1265
1266 // Keep looking for more map info.
1267 return false;
1268 });
1269
1270 if (IsVariableUsedInMapClause) {
1271 // If variable is identified in a map clause it is always captured by
1272 // reference except if it is a pointer that is dereferenced somehow.
1273 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1274 } else {
1275 // By default, all the data that has a scalar type is mapped by copy.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001276 IsByRef = !Ty->isScalarType() ||
1277 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
Samuel Antao86ace552016-04-27 22:40:57 +00001278 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001279 }
1280
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001281 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1282 IsByRef = !DSAStack->hasExplicitDSA(
1283 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1284 Level, /*NotLastprivate=*/true);
1285 }
1286
Samuel Antao86ace552016-04-27 22:40:57 +00001287 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001288 // and alignment, because the runtime library only deals with uintptr types.
1289 // If it does not fit the uintptr size, we need to pass the data by reference
1290 // instead.
1291 if (!IsByRef &&
1292 (Ctx.getTypeSizeInChars(Ty) >
1293 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001294 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001295 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001296 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001297
1298 return IsByRef;
1299}
1300
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001301unsigned Sema::getOpenMPNestingLevel() const {
1302 assert(getLangOpts().OpenMP);
1303 return DSAStack->getNestingLevel();
1304}
1305
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001306bool Sema::isInOpenMPTargetExecutionDirective() const {
1307 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1308 !DSAStack->isClauseParsingMode()) ||
1309 DSAStack->hasDirective(
1310 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1311 SourceLocation) -> bool {
1312 return isOpenMPTargetExecutionDirective(K);
1313 },
1314 false);
1315}
1316
Alexey Bataev90c228f2016-02-08 09:29:13 +00001317VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001318 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001319 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001320
1321 // If we are attempting to capture a global variable in a directive with
1322 // 'target' we return true so that this global is also mapped to the device.
1323 //
1324 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1325 // then it should not be captured. Therefore, an extra check has to be
1326 // inserted here once support for 'declare target' is added.
1327 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001328 auto *VD = dyn_cast<VarDecl>(D);
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001329 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
1330 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001331
Alexey Bataev48977c32015-08-04 08:10:48 +00001332 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1333 (!DSAStack->isClauseParsingMode() ||
1334 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001335 auto &&Info = DSAStack->isLoopControlVariable(D);
1336 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001337 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001338 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001339 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001340 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001341 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001342 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001343 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001344 DVarPrivate = DSAStack->hasDSA(
1345 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1346 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001347 if (DVarPrivate.CKind != OMPC_unknown)
1348 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001349 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001350 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001351}
1352
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001353bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001354 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1355 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001356 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1357 Level) ||
1358 // Consider taskgroup reduction descriptor variable a private to avoid
1359 // possible capture in the region.
1360 (DSAStack->hasExplicitDirective(
1361 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1362 Level) &&
1363 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001364}
1365
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001366void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1367 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1368 D = getCanonicalDecl(D);
1369 OpenMPClauseKind OMPC = OMPC_unknown;
1370 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1371 const unsigned NewLevel = I - 1;
1372 if (DSAStack->hasExplicitDSA(D,
1373 [&OMPC](const OpenMPClauseKind K) {
1374 if (isOpenMPPrivate(K)) {
1375 OMPC = K;
1376 return true;
1377 }
1378 return false;
1379 },
1380 NewLevel))
1381 break;
1382 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1383 D, NewLevel,
1384 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1385 OpenMPClauseKind) { return true; })) {
1386 OMPC = OMPC_map;
1387 break;
1388 }
1389 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1390 NewLevel)) {
1391 OMPC = OMPC_firstprivate;
1392 break;
1393 }
1394 }
1395 if (OMPC != OMPC_unknown)
1396 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1397}
1398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001399bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001400 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1401 // Return true if the current level is no longer enclosed in a target region.
1402
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 auto *VD = dyn_cast<VarDecl>(D);
1404 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001405 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1406 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001407}
1408
Alexey Bataeved09d242014-05-28 05:53:51 +00001409void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001410
1411void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1412 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001413 Scope *CurScope, SourceLocation Loc) {
1414 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001415 PushExpressionEvaluationContext(
1416 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001417}
1418
Alexey Bataevaac108a2015-06-23 04:51:00 +00001419void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1420 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001421}
1422
Alexey Bataevaac108a2015-06-23 04:51:00 +00001423void Sema::EndOpenMPClause() {
1424 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001425}
1426
Alexey Bataev758e55e2013-09-06 18:03:48 +00001427void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001428 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1429 // A variable of class type (or array thereof) that appears in a lastprivate
1430 // clause requires an accessible, unambiguous default constructor for the
1431 // class type, unless the list item is also specified in a firstprivate
1432 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001433 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001434 for (auto *C : D->clauses()) {
1435 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1436 SmallVector<Expr *, 8> PrivateCopies;
1437 for (auto *DE : Clause->varlists()) {
1438 if (DE->isValueDependent() || DE->isTypeDependent()) {
1439 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001440 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001441 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001442 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001443 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1444 QualType Type = VD->getType().getNonReferenceType();
1445 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001446 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001447 // Generate helper private variable and initialize it with the
1448 // default value. The address of the original variable is replaced
1449 // by the address of the new private variable in CodeGen. This new
1450 // variable is not added to IdResolver, so the code in the OpenMP
1451 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001452 auto *VDPrivate = buildVarDecl(
1453 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001454 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001455 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001456 if (VDPrivate->isInvalidDecl())
1457 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001458 PrivateCopies.push_back(buildDeclRefExpr(
1459 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001460 } else {
1461 // The variable is also a firstprivate, so initialization sequence
1462 // for private copy is generated already.
1463 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001464 }
1465 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001466 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001467 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001468 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001469 }
1470 }
1471 }
1472
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 DSAStack->pop();
1474 DiscardCleanupsInEvaluationContext();
1475 PopExpressionEvaluationContext();
1476}
1477
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001478static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1479 Expr *NumIterations, Sema &SemaRef,
1480 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001481
Alexey Bataeva769e072013-03-22 06:34:35 +00001482namespace {
1483
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001484class VarDeclFilterCCC : public CorrectionCandidateCallback {
1485private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001486 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001487
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001488public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001489 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001490 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001491 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001492 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001493 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001494 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1495 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001496 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001497 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001498 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001499};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001500
1501class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1502private:
1503 Sema &SemaRef;
1504
1505public:
1506 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1507 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1508 NamedDecl *ND = Candidate.getCorrectionDecl();
1509 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1510 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1511 SemaRef.getCurScope());
1512 }
1513 return false;
1514 }
1515};
1516
Alexey Bataeved09d242014-05-28 05:53:51 +00001517} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001518
1519ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1520 CXXScopeSpec &ScopeSpec,
1521 const DeclarationNameInfo &Id) {
1522 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1523 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1524
1525 if (Lookup.isAmbiguous())
1526 return ExprError();
1527
1528 VarDecl *VD;
1529 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001530 if (TypoCorrection Corrected = CorrectTypo(
1531 Id, LookupOrdinaryName, CurScope, nullptr,
1532 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001533 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001534 PDiag(Lookup.empty()
1535 ? diag::err_undeclared_var_use_suggest
1536 : diag::err_omp_expected_var_arg_suggest)
1537 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001538 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001539 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001540 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1541 : diag::err_omp_expected_var_arg)
1542 << Id.getName();
1543 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001544 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001545 } else {
1546 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001547 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001548 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1549 return ExprError();
1550 }
1551 }
1552 Lookup.suppressDiagnostics();
1553
1554 // OpenMP [2.9.2, Syntax, C/C++]
1555 // Variables must be file-scope, namespace-scope, or static block-scope.
1556 if (!VD->hasGlobalStorage()) {
1557 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001558 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1559 bool IsDecl =
1560 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001561 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001562 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1563 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001564 return ExprError();
1565 }
1566
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001567 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1568 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001569 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1570 // A threadprivate directive for file-scope variables must appear outside
1571 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001572 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1573 !getCurLexicalContext()->isTranslationUnit()) {
1574 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001575 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1576 bool IsDecl =
1577 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1578 Diag(VD->getLocation(),
1579 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1580 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001581 return ExprError();
1582 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001583 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1584 // A threadprivate directive for static class member variables must appear
1585 // in the class definition, in the same scope in which the member
1586 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001587 if (CanonicalVD->isStaticDataMember() &&
1588 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1589 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001590 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1591 bool IsDecl =
1592 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1593 Diag(VD->getLocation(),
1594 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1595 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001596 return ExprError();
1597 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001598 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1599 // A threadprivate directive for namespace-scope variables must appear
1600 // outside any definition or declaration other than the namespace
1601 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001602 if (CanonicalVD->getDeclContext()->isNamespace() &&
1603 (!getCurLexicalContext()->isFileContext() ||
1604 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1605 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001606 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1607 bool IsDecl =
1608 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1609 Diag(VD->getLocation(),
1610 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1611 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001612 return ExprError();
1613 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001614 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1615 // A threadprivate directive for static block-scope variables must appear
1616 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001617 if (CanonicalVD->isStaticLocal() && CurScope &&
1618 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001619 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001620 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1621 bool IsDecl =
1622 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1623 Diag(VD->getLocation(),
1624 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1625 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001626 return ExprError();
1627 }
1628
1629 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1630 // A threadprivate directive must lexically precede all references to any
1631 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001632 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001633 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001634 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001635 return ExprError();
1636 }
1637
1638 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001639 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1640 SourceLocation(), VD,
1641 /*RefersToEnclosingVariableOrCapture=*/false,
1642 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001643}
1644
Alexey Bataeved09d242014-05-28 05:53:51 +00001645Sema::DeclGroupPtrTy
1646Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1647 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001648 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001649 CurContext->addDecl(D);
1650 return DeclGroupPtrTy::make(DeclGroupRef(D));
1651 }
David Blaikie0403cb12016-01-15 23:43:25 +00001652 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001653}
1654
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001655namespace {
1656class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1657 Sema &SemaRef;
1658
1659public:
1660 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001661 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001662 if (VD->hasLocalStorage()) {
1663 SemaRef.Diag(E->getLocStart(),
1664 diag::err_omp_local_var_in_threadprivate_init)
1665 << E->getSourceRange();
1666 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1667 << VD << VD->getSourceRange();
1668 return true;
1669 }
1670 }
1671 return false;
1672 }
1673 bool VisitStmt(const Stmt *S) {
1674 for (auto Child : S->children()) {
1675 if (Child && Visit(Child))
1676 return true;
1677 }
1678 return false;
1679 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001680 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001681};
1682} // namespace
1683
Alexey Bataeved09d242014-05-28 05:53:51 +00001684OMPThreadPrivateDecl *
1685Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001686 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001687 for (auto &RefExpr : VarList) {
1688 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001689 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1690 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001691
Alexey Bataev376b4a42016-02-09 09:41:09 +00001692 // Mark variable as used.
1693 VD->setReferenced();
1694 VD->markUsed(Context);
1695
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001696 QualType QType = VD->getType();
1697 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1698 // It will be analyzed later.
1699 Vars.push_back(DE);
1700 continue;
1701 }
1702
Alexey Bataeva769e072013-03-22 06:34:35 +00001703 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1704 // A threadprivate variable must not have an incomplete type.
1705 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001706 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001707 continue;
1708 }
1709
1710 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1711 // A threadprivate variable must not have a reference type.
1712 if (VD->getType()->isReferenceType()) {
1713 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001714 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1715 bool IsDecl =
1716 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1717 Diag(VD->getLocation(),
1718 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1719 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001720 continue;
1721 }
1722
Samuel Antaof8b50122015-07-13 22:54:53 +00001723 // Check if this is a TLS variable. If TLS is not being supported, produce
1724 // the corresponding diagnostic.
1725 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1726 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1727 getLangOpts().OpenMPUseTLS &&
1728 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001729 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1730 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001731 Diag(ILoc, diag::err_omp_var_thread_local)
1732 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001733 bool IsDecl =
1734 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1735 Diag(VD->getLocation(),
1736 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1737 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001738 continue;
1739 }
1740
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001741 // Check if initial value of threadprivate variable reference variable with
1742 // local storage (it is not supported by runtime).
1743 if (auto Init = VD->getAnyInitializer()) {
1744 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001745 if (Checker.Visit(Init))
1746 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001747 }
1748
Alexey Bataeved09d242014-05-28 05:53:51 +00001749 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001750 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001751 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1752 Context, SourceRange(Loc, Loc)));
1753 if (auto *ML = Context.getASTMutationListener())
1754 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001755 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001756 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001757 if (!Vars.empty()) {
1758 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1759 Vars);
1760 D->setAccess(AS_public);
1761 }
1762 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001763}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001764
Alexey Bataev7ff55242014-06-19 09:13:45 +00001765static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001766 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001767 bool IsLoopIterVar = false) {
1768 if (DVar.RefExpr) {
1769 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1770 << getOpenMPClauseName(DVar.CKind);
1771 return;
1772 }
1773 enum {
1774 PDSA_StaticMemberShared,
1775 PDSA_StaticLocalVarShared,
1776 PDSA_LoopIterVarPrivate,
1777 PDSA_LoopIterVarLinear,
1778 PDSA_LoopIterVarLastprivate,
1779 PDSA_ConstVarShared,
1780 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001781 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001782 PDSA_LocalVarPrivate,
1783 PDSA_Implicit
1784 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001785 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001786 auto ReportLoc = D->getLocation();
1787 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001788 if (IsLoopIterVar) {
1789 if (DVar.CKind == OMPC_private)
1790 Reason = PDSA_LoopIterVarPrivate;
1791 else if (DVar.CKind == OMPC_lastprivate)
1792 Reason = PDSA_LoopIterVarLastprivate;
1793 else
1794 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001795 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1796 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001797 Reason = PDSA_TaskVarFirstprivate;
1798 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001799 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001800 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001801 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001802 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001803 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001804 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001805 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001806 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001807 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001808 ReportHint = true;
1809 Reason = PDSA_LocalVarPrivate;
1810 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001811 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001812 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001813 << Reason << ReportHint
1814 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1815 } else if (DVar.ImplicitDSALoc.isValid()) {
1816 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1817 << getOpenMPClauseName(DVar.CKind);
1818 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001819}
1820
Alexey Bataev758e55e2013-09-06 18:03:48 +00001821namespace {
1822class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1823 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001824 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001825 bool ErrorFound;
1826 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001827 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001828 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001829 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001830 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001831
Alexey Bataev758e55e2013-09-06 18:03:48 +00001832public:
1833 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001834 if (E->isTypeDependent() || E->isValueDependent() ||
1835 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1836 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001837 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001838 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001839 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001840 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001841 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001842
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001843 auto DVar = Stack->getTopDSA(VD, false);
1844 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001845 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001846 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001847
Alexey Bataevafe50572017-10-06 17:00:28 +00001848 // Skip internally declared static variables.
1849 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1850 return;
1851
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001852 auto ELoc = E->getExprLoc();
1853 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001854 // The default(none) clause requires that each variable that is referenced
1855 // in the construct, and does not have a predetermined data-sharing
1856 // attribute, must have its data-sharing attribute explicitly determined
1857 // by being listed in a data-sharing attribute clause.
1858 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001859 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001860 VarsWithInheritedDSA.count(VD) == 0) {
1861 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001862 return;
1863 }
1864
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001865 if (isOpenMPTargetExecutionDirective(DKind) &&
1866 !Stack->isLoopControlVariable(VD).first) {
1867 if (!Stack->checkMappableExprComponentListsForDecl(
1868 VD, /*CurrentRegionOnly=*/true,
1869 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1870 StackComponents,
1871 OpenMPClauseKind) {
1872 // Variable is used if it has been marked as an array, array
1873 // section or the variable iself.
1874 return StackComponents.size() == 1 ||
1875 std::all_of(
1876 std::next(StackComponents.rbegin()),
1877 StackComponents.rend(),
1878 [](const OMPClauseMappableExprCommon::
1879 MappableComponent &MC) {
1880 return MC.getAssociatedDeclaration() ==
1881 nullptr &&
1882 (isa<OMPArraySectionExpr>(
1883 MC.getAssociatedExpression()) ||
1884 isa<ArraySubscriptExpr>(
1885 MC.getAssociatedExpression()));
1886 });
1887 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001888 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001889 // By default lambdas are captured as firstprivates.
1890 if (const auto *RD =
1891 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001892 IsFirstprivate = RD->isLambda();
1893 IsFirstprivate =
1894 IsFirstprivate ||
1895 (VD->getType().getNonReferenceType()->isScalarType() &&
1896 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1897 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001898 ImplicitFirstprivate.emplace_back(E);
1899 else
1900 ImplicitMap.emplace_back(E);
1901 return;
1902 }
1903 }
1904
Alexey Bataev758e55e2013-09-06 18:03:48 +00001905 // OpenMP [2.9.3.6, Restrictions, p.2]
1906 // A list item that appears in a reduction clause of the innermost
1907 // enclosing worksharing or parallel construct may not be accessed in an
1908 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001909 DVar = Stack->hasInnermostDSA(
1910 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1911 [](OpenMPDirectiveKind K) -> bool {
1912 return isOpenMPParallelDirective(K) ||
1913 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1914 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001915 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001916 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001917 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001918 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1919 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001920 return;
1921 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001922
1923 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001924 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001925 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1926 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001927 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001928 }
1929 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001930 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001931 if (E->isTypeDependent() || E->isValueDependent() ||
1932 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1933 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001934 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1935 if (!FD)
1936 return;
1937 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001938 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001939 auto DVar = Stack->getTopDSA(FD, false);
1940 // Check if the variable has explicit DSA set and stop analysis if it
1941 // so.
1942 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1943 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001944
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001945 if (isOpenMPTargetExecutionDirective(DKind) &&
1946 !Stack->isLoopControlVariable(FD).first &&
1947 !Stack->checkMappableExprComponentListsForDecl(
1948 FD, /*CurrentRegionOnly=*/true,
1949 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1950 StackComponents,
1951 OpenMPClauseKind) {
1952 return isa<CXXThisExpr>(
1953 cast<MemberExpr>(
1954 StackComponents.back().getAssociatedExpression())
1955 ->getBase()
1956 ->IgnoreParens());
1957 })) {
1958 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1959 // A bit-field cannot appear in a map clause.
1960 //
1961 if (FD->isBitField()) {
1962 SemaRef.Diag(E->getMemberLoc(),
1963 diag::err_omp_bit_fields_forbidden_in_clause)
1964 << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001965 return;
1966 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001967 ImplicitMap.emplace_back(E);
1968 return;
1969 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001970
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001971 auto ELoc = E->getExprLoc();
1972 // OpenMP [2.9.3.6, Restrictions, p.2]
1973 // A list item that appears in a reduction clause of the innermost
1974 // enclosing worksharing or parallel construct may not be accessed in
1975 // an explicit task.
1976 DVar = Stack->hasInnermostDSA(
1977 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1978 [](OpenMPDirectiveKind K) -> bool {
1979 return isOpenMPParallelDirective(K) ||
1980 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1981 },
1982 /*FromParent=*/true);
1983 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1984 ErrorFound = true;
1985 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1986 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1987 return;
1988 }
1989
1990 // Define implicit data-sharing attributes for task.
1991 DVar = Stack->getImplicitDSA(FD, false);
1992 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1993 !Stack->isLoopControlVariable(FD).first)
1994 ImplicitFirstprivate.push_back(E);
1995 return;
1996 }
1997 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
1998 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
1999 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
2000 auto *VD = cast<ValueDecl>(
2001 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2002 if (!Stack->checkMappableExprComponentListsForDecl(
2003 VD, /*CurrentRegionOnly=*/true,
2004 [&CurComponents](
2005 OMPClauseMappableExprCommon::MappableExprComponentListRef
2006 StackComponents,
2007 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002008 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002009 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002010 for (const auto &SC : llvm::reverse(StackComponents)) {
2011 // Do both expressions have the same kind?
2012 if (CCI->getAssociatedExpression()->getStmtClass() !=
2013 SC.getAssociatedExpression()->getStmtClass())
2014 if (!(isa<OMPArraySectionExpr>(
2015 SC.getAssociatedExpression()) &&
2016 isa<ArraySubscriptExpr>(
2017 CCI->getAssociatedExpression())))
2018 return false;
2019
2020 Decl *CCD = CCI->getAssociatedDeclaration();
2021 Decl *SCD = SC.getAssociatedDeclaration();
2022 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2023 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2024 if (SCD != CCD)
2025 return false;
2026 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002027 if (CCI == CCE)
2028 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002029 }
2030 return true;
2031 })) {
2032 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002033 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002034 } else
2035 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002036 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002037 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002038 for (auto *C : S->clauses()) {
2039 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002040 // for task|target directives.
2041 // Skip analysis of arguments of implicitly defined map clause for target
2042 // directives.
2043 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2044 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002045 for (auto *CC : C->children()) {
2046 if (CC)
2047 Visit(CC);
2048 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002049 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002050 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002051 }
2052 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002053 for (auto *C : S->children()) {
2054 if (C && !isa<OMPExecutableDirective>(C))
2055 Visit(C);
2056 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002057 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002058
2059 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002060 ArrayRef<Expr *> getImplicitFirstprivate() const {
2061 return ImplicitFirstprivate;
2062 }
2063 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002064 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002065 return VarsWithInheritedDSA;
2066 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002067
Alexey Bataev7ff55242014-06-19 09:13:45 +00002068 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2069 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002070};
Alexey Bataeved09d242014-05-28 05:53:51 +00002071} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002072
Alexey Bataevbae9a792014-06-27 10:37:06 +00002073void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002074 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002075 case OMPD_parallel:
2076 case OMPD_parallel_for:
2077 case OMPD_parallel_for_simd:
2078 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002079 case OMPD_teams:
2080 case OMPD_teams_distribute: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002081 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002082 QualType KmpInt32PtrTy =
2083 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002084 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002085 std::make_pair(".global_tid.", KmpInt32PtrTy),
2086 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2087 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002088 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002089 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2090 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002091 break;
2092 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002093 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002094 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002095 case OMPD_target_parallel_for:
2096 case OMPD_target_parallel_for_simd: {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002097 Sema::CapturedParamNameType ParamsTarget[] = {
2098 std::make_pair(StringRef(), QualType()) // __context with shared vars
2099 };
2100 // Start a captured region for 'target' with no implicit parameters.
2101 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2102 ParamsTarget);
2103 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2104 QualType KmpInt32PtrTy =
2105 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002106 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002107 std::make_pair(".global_tid.", KmpInt32PtrTy),
2108 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2109 std::make_pair(StringRef(), QualType()) // __context with shared vars
2110 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002111 // Start a captured region for 'teams' or 'parallel'. Both regions have
2112 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002113 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002114 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002115 break;
2116 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002117 case OMPD_simd:
2118 case OMPD_for:
2119 case OMPD_for_simd:
2120 case OMPD_sections:
2121 case OMPD_section:
2122 case OMPD_single:
2123 case OMPD_master:
2124 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002125 case OMPD_taskgroup:
2126 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00002127 case OMPD_ordered:
2128 case OMPD_atomic:
2129 case OMPD_target_data:
2130 case OMPD_target:
Kelvin Li986330c2016-07-20 22:57:10 +00002131 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002132 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002133 std::make_pair(StringRef(), QualType()) // __context with shared vars
2134 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002135 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2136 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002137 break;
2138 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002139 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002140 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002141 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2142 FunctionProtoType::ExtProtoInfo EPI;
2143 EPI.Variadic = true;
2144 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002145 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002146 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002147 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2148 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2149 std::make_pair(".copy_fn.",
2150 Context.getPointerType(CopyFnType).withConst()),
2151 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002152 std::make_pair(StringRef(), QualType()) // __context with shared vars
2153 };
2154 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2155 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002156 // Mark this captured region as inlined, because we don't use outlined
2157 // function directly.
2158 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2159 AlwaysInlineAttr::CreateImplicit(
2160 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002161 break;
2162 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002163 case OMPD_taskloop:
2164 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002165 QualType KmpInt32Ty =
2166 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2167 QualType KmpUInt64Ty =
2168 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2169 QualType KmpInt64Ty =
2170 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2171 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2172 FunctionProtoType::ExtProtoInfo EPI;
2173 EPI.Variadic = true;
2174 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002175 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002176 std::make_pair(".global_tid.", KmpInt32Ty),
2177 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2178 std::make_pair(".privates.",
2179 Context.VoidPtrTy.withConst().withRestrict()),
2180 std::make_pair(
2181 ".copy_fn.",
2182 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2183 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2184 std::make_pair(".lb.", KmpUInt64Ty),
2185 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2186 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002187 std::make_pair(".reductions.",
2188 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002189 std::make_pair(StringRef(), QualType()) // __context with shared vars
2190 };
2191 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2192 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002193 // Mark this captured region as inlined, because we don't use outlined
2194 // function directly.
2195 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2196 AlwaysInlineAttr::CreateImplicit(
2197 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002198 break;
2199 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002200 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00002201 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00002202 case OMPD_distribute_parallel_for:
Kelvin Li579e41c2016-11-30 23:51:03 +00002203 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00002204 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li80e8f562016-12-29 22:16:30 +00002205 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00002206 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00002207 case OMPD_target_teams_distribute_parallel_for_simd:
2208 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002209 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2210 QualType KmpInt32PtrTy =
2211 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2212 Sema::CapturedParamNameType Params[] = {
2213 std::make_pair(".global_tid.", KmpInt32PtrTy),
2214 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2215 std::make_pair(".previous.lb.", Context.getSizeType()),
2216 std::make_pair(".previous.ub.", Context.getSizeType()),
2217 std::make_pair(StringRef(), QualType()) // __context with shared vars
2218 };
2219 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2220 Params);
2221 break;
2222 }
Carlo Bertolli62fae152017-11-20 20:46:39 +00002223 case OMPD_teams_distribute_parallel_for: {
2224 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2225 QualType KmpInt32PtrTy =
2226 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2227
2228 Sema::CapturedParamNameType ParamsTeams[] = {
2229 std::make_pair(".global_tid.", KmpInt32PtrTy),
2230 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2231 std::make_pair(StringRef(), QualType()) // __context with shared vars
2232 };
2233 // Start a captured region for 'target' with no implicit parameters.
2234 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2235 ParamsTeams);
2236
2237 Sema::CapturedParamNameType ParamsParallel[] = {
2238 std::make_pair(".global_tid.", KmpInt32PtrTy),
2239 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2240 std::make_pair(".previous.lb.", Context.getSizeType()),
2241 std::make_pair(".previous.ub.", Context.getSizeType()),
2242 std::make_pair(StringRef(), QualType()) // __context with shared vars
2243 };
2244 // Start a captured region for 'teams' or 'parallel'. Both regions have
2245 // the same implicit parameters.
2246 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2247 ParamsParallel);
2248 break;
2249 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002250 case OMPD_target_update:
2251 case OMPD_target_enter_data:
2252 case OMPD_target_exit_data: {
2253 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2254 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2255 FunctionProtoType::ExtProtoInfo EPI;
2256 EPI.Variadic = true;
2257 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2258 Sema::CapturedParamNameType Params[] = {
2259 std::make_pair(".global_tid.", KmpInt32Ty),
2260 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2261 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2262 std::make_pair(".copy_fn.",
2263 Context.getPointerType(CopyFnType).withConst()),
2264 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2265 std::make_pair(StringRef(), QualType()) // __context with shared vars
2266 };
2267 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2268 Params);
2269 // Mark this captured region as inlined, because we don't use outlined
2270 // function directly.
2271 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2272 AlwaysInlineAttr::CreateImplicit(
2273 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2274 break;
2275 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002276 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002277 case OMPD_taskyield:
2278 case OMPD_barrier:
2279 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002280 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002281 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002282 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002283 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002284 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002285 case OMPD_declare_target:
2286 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002287 llvm_unreachable("OpenMP Directive is not allowed");
2288 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002289 llvm_unreachable("Unknown OpenMP directive");
2290 }
2291}
2292
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002293int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2294 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2295 getOpenMPCaptureRegions(CaptureRegions, DKind);
2296 return CaptureRegions.size();
2297}
2298
Alexey Bataev3392d762016-02-16 11:18:12 +00002299static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002300 Expr *CaptureExpr, bool WithInit,
2301 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002302 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002303 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002304 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002305 QualType Ty = Init->getType();
2306 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2307 if (S.getLangOpts().CPlusPlus)
2308 Ty = C.getLValueReferenceType(Ty);
2309 else {
2310 Ty = C.getPointerType(Ty);
2311 ExprResult Res =
2312 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2313 if (!Res.isUsable())
2314 return nullptr;
2315 Init = Res.get();
2316 }
Alexey Bataev61205072016-03-02 04:57:40 +00002317 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002318 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002319 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2320 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002321 if (!WithInit)
2322 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002323 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002324 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002325 return CED;
2326}
2327
Alexey Bataev61205072016-03-02 04:57:40 +00002328static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2329 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002330 OMPCapturedExprDecl *CD;
2331 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2332 CD = cast<OMPCapturedExprDecl>(VD);
2333 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002334 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2335 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002336 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002337 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002338}
2339
Alexey Bataev5a3af132016-03-29 08:58:54 +00002340static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2341 if (!Ref) {
2342 auto *CD =
2343 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2344 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2345 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2346 CaptureExpr->getExprLoc());
2347 }
2348 ExprResult Res = Ref;
2349 if (!S.getLangOpts().CPlusPlus &&
2350 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2351 Ref->getType()->isPointerType())
2352 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2353 if (!Res.isUsable())
2354 return ExprError();
2355 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002356}
2357
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002358namespace {
2359// OpenMP directives parsed in this section are represented as a
2360// CapturedStatement with an associated statement. If a syntax error
2361// is detected during the parsing of the associated statement, the
2362// compiler must abort processing and close the CapturedStatement.
2363//
2364// Combined directives such as 'target parallel' have more than one
2365// nested CapturedStatements. This RAII ensures that we unwind out
2366// of all the nested CapturedStatements when an error is found.
2367class CaptureRegionUnwinderRAII {
2368private:
2369 Sema &S;
2370 bool &ErrorFound;
2371 OpenMPDirectiveKind DKind;
2372
2373public:
2374 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2375 OpenMPDirectiveKind DKind)
2376 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2377 ~CaptureRegionUnwinderRAII() {
2378 if (ErrorFound) {
2379 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2380 while (--ThisCaptureLevel >= 0)
2381 S.ActOnCapturedRegionError();
2382 }
2383 }
2384};
2385} // namespace
2386
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002387StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2388 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002389 bool ErrorFound = false;
2390 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2391 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002392 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002393 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002394 return StmtError();
2395 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002396
2397 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002398 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002399 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002400 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002401 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002402 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002403 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2404 Clause->getClauseKind() == OMPC_in_reduction) {
2405 // Capture taskgroup task_reduction descriptors inside the tasking regions
2406 // with the corresponding in_reduction items.
2407 auto *IRC = cast<OMPInReductionClause>(Clause);
2408 for (auto *E : IRC->taskgroup_descriptors())
2409 if (E)
2410 MarkDeclarationsReferencedInExpr(E);
2411 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002412 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002413 Clause->getClauseKind() == OMPC_copyprivate ||
2414 (getLangOpts().OpenMPUseTLS &&
2415 getASTContext().getTargetInfo().isTLSSupported() &&
2416 Clause->getClauseKind() == OMPC_copyin)) {
2417 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002418 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002419 for (auto *VarRef : Clause->children()) {
2420 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002421 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002422 }
2423 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002424 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002425 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002426 if (auto *C = OMPClauseWithPreInit::get(Clause))
2427 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002428 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2429 if (auto *E = C->getPostUpdateExpr())
2430 MarkDeclarationsReferencedInExpr(E);
2431 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002432 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002433 if (Clause->getClauseKind() == OMPC_schedule)
2434 SC = cast<OMPScheduleClause>(Clause);
2435 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002436 OC = cast<OMPOrderedClause>(Clause);
2437 else if (Clause->getClauseKind() == OMPC_linear)
2438 LCs.push_back(cast<OMPLinearClause>(Clause));
2439 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002440 // OpenMP, 2.7.1 Loop Construct, Restrictions
2441 // The nonmonotonic modifier cannot be specified if an ordered clause is
2442 // specified.
2443 if (SC &&
2444 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2445 SC->getSecondScheduleModifier() ==
2446 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2447 OC) {
2448 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2449 ? SC->getFirstScheduleModifierLoc()
2450 : SC->getSecondScheduleModifierLoc(),
2451 diag::err_omp_schedule_nonmonotonic_ordered)
2452 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2453 ErrorFound = true;
2454 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002455 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2456 for (auto *C : LCs) {
2457 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2458 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2459 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002460 ErrorFound = true;
2461 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002462 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2463 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2464 OC->getNumForLoops()) {
2465 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2466 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2467 ErrorFound = true;
2468 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002469 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002470 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002471 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002472 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002473 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2474 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2475 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2476 // Mark all variables in private list clauses as used in inner region.
2477 // Required for proper codegen of combined directives.
2478 // TODO: add processing for other clauses.
2479 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2480 for (auto *C : PICs) {
2481 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2482 // Find the particular capture region for the clause if the
2483 // directive is a combined one with multiple capture regions.
2484 // If the directive is not a combined one, the capture region
2485 // associated with the clause is OMPD_unknown and is generated
2486 // only once.
2487 if (CaptureRegion == ThisCaptureRegion ||
2488 CaptureRegion == OMPD_unknown) {
2489 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2490 for (auto *D : DS->decls())
2491 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2492 }
2493 }
2494 }
2495 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002496 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002497 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002498 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002499}
2500
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002501static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2502 OpenMPDirectiveKind CancelRegion,
2503 SourceLocation StartLoc) {
2504 // CancelRegion is only needed for cancel and cancellation_point.
2505 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2506 return false;
2507
2508 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2509 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2510 return false;
2511
2512 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2513 << getOpenMPDirectiveName(CancelRegion);
2514 return true;
2515}
2516
2517static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002518 OpenMPDirectiveKind CurrentRegion,
2519 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002520 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002521 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002522 if (Stack->getCurScope()) {
2523 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002524 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002525 bool NestingProhibited = false;
2526 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002527 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002528 enum {
2529 NoRecommend,
2530 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002531 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002532 ShouldBeInTargetRegion,
2533 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002534 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002535 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002536 // OpenMP [2.16, Nesting of Regions]
2537 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002538 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002539 // An ordered construct with the simd clause is the only OpenMP
2540 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002541 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002542 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2543 // message.
2544 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2545 ? diag::err_omp_prohibited_region_simd
2546 : diag::warn_omp_nesting_simd);
2547 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002548 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002549 if (ParentRegion == OMPD_atomic) {
2550 // OpenMP [2.16, Nesting of Regions]
2551 // OpenMP constructs may not be nested inside an atomic region.
2552 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2553 return true;
2554 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002555 if (CurrentRegion == OMPD_section) {
2556 // OpenMP [2.7.2, sections Construct, Restrictions]
2557 // Orphaned section directives are prohibited. That is, the section
2558 // directives must appear within the sections construct and must not be
2559 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002560 if (ParentRegion != OMPD_sections &&
2561 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002562 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2563 << (ParentRegion != OMPD_unknown)
2564 << getOpenMPDirectiveName(ParentRegion);
2565 return true;
2566 }
2567 return false;
2568 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002569 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002570 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002571 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002572 if (ParentRegion == OMPD_unknown &&
2573 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002574 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002575 if (CurrentRegion == OMPD_cancellation_point ||
2576 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002577 // OpenMP [2.16, Nesting of Regions]
2578 // A cancellation point construct for which construct-type-clause is
2579 // taskgroup must be nested inside a task construct. A cancellation
2580 // point construct for which construct-type-clause is not taskgroup must
2581 // be closely nested inside an OpenMP construct that matches the type
2582 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002583 // A cancel construct for which construct-type-clause is taskgroup must be
2584 // nested inside a task construct. A cancel construct for which
2585 // construct-type-clause is not taskgroup must be closely nested inside an
2586 // OpenMP construct that matches the type specified in
2587 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002588 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002589 !((CancelRegion == OMPD_parallel &&
2590 (ParentRegion == OMPD_parallel ||
2591 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002592 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002593 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2594 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002595 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2596 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002597 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2598 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002599 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002600 // OpenMP [2.16, Nesting of Regions]
2601 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002602 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002603 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002604 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002605 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2606 // OpenMP [2.16, Nesting of Regions]
2607 // A critical region may not be nested (closely or otherwise) inside a
2608 // critical region with the same name. Note that this restriction is not
2609 // sufficient to prevent deadlock.
2610 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002611 bool DeadLock = Stack->hasDirective(
2612 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2613 const DeclarationNameInfo &DNI,
2614 SourceLocation Loc) -> bool {
2615 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2616 PreviousCriticalLoc = Loc;
2617 return true;
2618 } else
2619 return false;
2620 },
2621 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002622 if (DeadLock) {
2623 SemaRef.Diag(StartLoc,
2624 diag::err_omp_prohibited_region_critical_same_name)
2625 << CurrentName.getName();
2626 if (PreviousCriticalLoc.isValid())
2627 SemaRef.Diag(PreviousCriticalLoc,
2628 diag::note_omp_previous_critical_region);
2629 return true;
2630 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002631 } else if (CurrentRegion == OMPD_barrier) {
2632 // OpenMP [2.16, Nesting of Regions]
2633 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002634 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002635 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2636 isOpenMPTaskingDirective(ParentRegion) ||
2637 ParentRegion == OMPD_master ||
2638 ParentRegion == OMPD_critical ||
2639 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002640 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002641 !isOpenMPParallelDirective(CurrentRegion) &&
2642 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002643 // OpenMP [2.16, Nesting of Regions]
2644 // A worksharing region may not be closely nested inside a worksharing,
2645 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002646 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2647 isOpenMPTaskingDirective(ParentRegion) ||
2648 ParentRegion == OMPD_master ||
2649 ParentRegion == OMPD_critical ||
2650 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002651 Recommend = ShouldBeInParallelRegion;
2652 } else if (CurrentRegion == OMPD_ordered) {
2653 // OpenMP [2.16, Nesting of Regions]
2654 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002655 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002656 // An ordered region must be closely nested inside a loop region (or
2657 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002658 // OpenMP [2.8.1,simd Construct, Restrictions]
2659 // An ordered construct with the simd clause is the only OpenMP construct
2660 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002661 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002662 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002663 !(isOpenMPSimdDirective(ParentRegion) ||
2664 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002665 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002666 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002667 // OpenMP [2.16, Nesting of Regions]
2668 // If specified, a teams construct must be contained within a target
2669 // construct.
2670 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002671 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002672 Recommend = ShouldBeInTargetRegion;
2673 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2674 }
Kelvin Libf594a52016-12-17 05:48:59 +00002675 if (!NestingProhibited &&
2676 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2677 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2678 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002679 // OpenMP [2.16, Nesting of Regions]
2680 // distribute, parallel, parallel sections, parallel workshare, and the
2681 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2682 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002683 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2684 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002685 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002686 }
David Majnemer9d168222016-08-05 17:44:54 +00002687 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002688 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002689 // OpenMP 4.5 [2.17 Nesting of Regions]
2690 // The region associated with the distribute construct must be strictly
2691 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002692 NestingProhibited =
2693 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002694 Recommend = ShouldBeInTeamsRegion;
2695 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002696 if (!NestingProhibited &&
2697 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2698 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2699 // OpenMP 4.5 [2.17 Nesting of Regions]
2700 // If a target, target update, target data, target enter data, or
2701 // target exit data construct is encountered during execution of a
2702 // target region, the behavior is unspecified.
2703 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002704 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2705 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002706 if (isOpenMPTargetExecutionDirective(K)) {
2707 OffendingRegion = K;
2708 return true;
2709 } else
2710 return false;
2711 },
2712 false /* don't skip top directive */);
2713 CloseNesting = false;
2714 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002715 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002716 if (OrphanSeen) {
2717 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2718 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2719 } else {
2720 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2721 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2722 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2723 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002724 return true;
2725 }
2726 }
2727 return false;
2728}
2729
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002730static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2731 ArrayRef<OMPClause *> Clauses,
2732 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2733 bool ErrorFound = false;
2734 unsigned NamedModifiersNumber = 0;
2735 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2736 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002737 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002738 for (const auto *C : Clauses) {
2739 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2740 // At most one if clause without a directive-name-modifier can appear on
2741 // the directive.
2742 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2743 if (FoundNameModifiers[CurNM]) {
2744 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2745 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2746 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2747 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002748 } else if (CurNM != OMPD_unknown) {
2749 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002750 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002751 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002752 FoundNameModifiers[CurNM] = IC;
2753 if (CurNM == OMPD_unknown)
2754 continue;
2755 // Check if the specified name modifier is allowed for the current
2756 // directive.
2757 // At most one if clause with the particular directive-name-modifier can
2758 // appear on the directive.
2759 bool MatchFound = false;
2760 for (auto NM : AllowedNameModifiers) {
2761 if (CurNM == NM) {
2762 MatchFound = true;
2763 break;
2764 }
2765 }
2766 if (!MatchFound) {
2767 S.Diag(IC->getNameModifierLoc(),
2768 diag::err_omp_wrong_if_directive_name_modifier)
2769 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2770 ErrorFound = true;
2771 }
2772 }
2773 }
2774 // If any if clause on the directive includes a directive-name-modifier then
2775 // all if clauses on the directive must include a directive-name-modifier.
2776 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2777 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2778 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2779 diag::err_omp_no_more_if_clause);
2780 } else {
2781 std::string Values;
2782 std::string Sep(", ");
2783 unsigned AllowedCnt = 0;
2784 unsigned TotalAllowedNum =
2785 AllowedNameModifiers.size() - NamedModifiersNumber;
2786 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2787 ++Cnt) {
2788 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2789 if (!FoundNameModifiers[NM]) {
2790 Values += "'";
2791 Values += getOpenMPDirectiveName(NM);
2792 Values += "'";
2793 if (AllowedCnt + 2 == TotalAllowedNum)
2794 Values += " or ";
2795 else if (AllowedCnt + 1 != TotalAllowedNum)
2796 Values += Sep;
2797 ++AllowedCnt;
2798 }
2799 }
2800 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2801 diag::err_omp_unnamed_if_clause)
2802 << (TotalAllowedNum > 1) << Values;
2803 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002804 for (auto Loc : NameModifierLoc) {
2805 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2806 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002807 ErrorFound = true;
2808 }
2809 return ErrorFound;
2810}
2811
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002812StmtResult Sema::ActOnOpenMPExecutableDirective(
2813 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2814 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2815 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002816 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002817 // First check CancelRegion which is then used in checkNestingOfRegions.
2818 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2819 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002820 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002821 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002822
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002823 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002824 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002825 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002826 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002827 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002828 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2829
2830 // Check default data sharing attributes for referenced variables.
2831 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002832 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2833 Stmt *S = AStmt;
2834 while (--ThisCaptureLevel >= 0)
2835 S = cast<CapturedStmt>(S)->getCapturedStmt();
2836 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002837 if (DSAChecker.isErrorFound())
2838 return StmtError();
2839 // Generate list of implicitly defined firstprivate variables.
2840 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002841
Alexey Bataev88202be2017-07-27 13:20:36 +00002842 SmallVector<Expr *, 4> ImplicitFirstprivates(
2843 DSAChecker.getImplicitFirstprivate().begin(),
2844 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002845 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2846 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002847 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2848 for (auto *C : Clauses) {
2849 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2850 for (auto *E : IRC->taskgroup_descriptors())
2851 if (E)
2852 ImplicitFirstprivates.emplace_back(E);
2853 }
2854 }
2855 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002856 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002857 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2858 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002859 ClausesWithImplicit.push_back(Implicit);
2860 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002861 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002862 } else
2863 ErrorFound = true;
2864 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002865 if (!ImplicitMaps.empty()) {
2866 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2867 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2868 SourceLocation(), SourceLocation(), ImplicitMaps,
2869 SourceLocation(), SourceLocation(), SourceLocation())) {
2870 ClausesWithImplicit.emplace_back(Implicit);
2871 ErrorFound |=
2872 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2873 } else
2874 ErrorFound = true;
2875 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002876 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002877
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002878 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002879 switch (Kind) {
2880 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002881 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2882 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002883 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002884 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002885 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002886 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2887 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002888 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002889 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002890 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2891 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002892 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002893 case OMPD_for_simd:
2894 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2895 EndLoc, VarsWithInheritedDSA);
2896 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002897 case OMPD_sections:
2898 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2899 EndLoc);
2900 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002901 case OMPD_section:
2902 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002903 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002904 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2905 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002906 case OMPD_single:
2907 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2908 EndLoc);
2909 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002910 case OMPD_master:
2911 assert(ClausesWithImplicit.empty() &&
2912 "No clauses are allowed for 'omp master' directive");
2913 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2914 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002915 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002916 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2917 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002918 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002919 case OMPD_parallel_for:
2920 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2921 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002922 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002923 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002924 case OMPD_parallel_for_simd:
2925 Res = ActOnOpenMPParallelForSimdDirective(
2926 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002927 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002928 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002929 case OMPD_parallel_sections:
2930 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2931 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002932 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002933 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002934 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002935 Res =
2936 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002937 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002938 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002939 case OMPD_taskyield:
2940 assert(ClausesWithImplicit.empty() &&
2941 "No clauses are allowed for 'omp taskyield' directive");
2942 assert(AStmt == nullptr &&
2943 "No associated statement allowed for 'omp taskyield' directive");
2944 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2945 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002946 case OMPD_barrier:
2947 assert(ClausesWithImplicit.empty() &&
2948 "No clauses are allowed for 'omp barrier' directive");
2949 assert(AStmt == nullptr &&
2950 "No associated statement allowed for 'omp barrier' directive");
2951 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2952 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002953 case OMPD_taskwait:
2954 assert(ClausesWithImplicit.empty() &&
2955 "No clauses are allowed for 'omp taskwait' directive");
2956 assert(AStmt == nullptr &&
2957 "No associated statement allowed for 'omp taskwait' directive");
2958 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2959 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002960 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002961 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2962 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002963 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002964 case OMPD_flush:
2965 assert(AStmt == nullptr &&
2966 "No associated statement allowed for 'omp flush' directive");
2967 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2968 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002969 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002970 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2971 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002972 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002973 case OMPD_atomic:
2974 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2975 EndLoc);
2976 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002977 case OMPD_teams:
2978 Res =
2979 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2980 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002981 case OMPD_target:
2982 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2983 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002984 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002985 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002986 case OMPD_target_parallel:
2987 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2988 StartLoc, EndLoc);
2989 AllowedNameModifiers.push_back(OMPD_target);
2990 AllowedNameModifiers.push_back(OMPD_parallel);
2991 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002992 case OMPD_target_parallel_for:
2993 Res = ActOnOpenMPTargetParallelForDirective(
2994 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2995 AllowedNameModifiers.push_back(OMPD_target);
2996 AllowedNameModifiers.push_back(OMPD_parallel);
2997 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002998 case OMPD_cancellation_point:
2999 assert(ClausesWithImplicit.empty() &&
3000 "No clauses are allowed for 'omp cancellation point' directive");
3001 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3002 "cancellation point' directive");
3003 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3004 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003005 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003006 assert(AStmt == nullptr &&
3007 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003008 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3009 CancelRegion);
3010 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003011 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003012 case OMPD_target_data:
3013 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3014 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003015 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003016 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003017 case OMPD_target_enter_data:
3018 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003019 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003020 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3021 break;
Samuel Antao72590762016-01-19 20:04:50 +00003022 case OMPD_target_exit_data:
3023 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003024 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003025 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3026 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003027 case OMPD_taskloop:
3028 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3029 EndLoc, VarsWithInheritedDSA);
3030 AllowedNameModifiers.push_back(OMPD_taskloop);
3031 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003032 case OMPD_taskloop_simd:
3033 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3034 EndLoc, VarsWithInheritedDSA);
3035 AllowedNameModifiers.push_back(OMPD_taskloop);
3036 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003037 case OMPD_distribute:
3038 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3039 EndLoc, VarsWithInheritedDSA);
3040 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003041 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003042 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3043 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003044 AllowedNameModifiers.push_back(OMPD_target_update);
3045 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003046 case OMPD_distribute_parallel_for:
3047 Res = ActOnOpenMPDistributeParallelForDirective(
3048 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3049 AllowedNameModifiers.push_back(OMPD_parallel);
3050 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003051 case OMPD_distribute_parallel_for_simd:
3052 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3053 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3054 AllowedNameModifiers.push_back(OMPD_parallel);
3055 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003056 case OMPD_distribute_simd:
3057 Res = ActOnOpenMPDistributeSimdDirective(
3058 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3059 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003060 case OMPD_target_parallel_for_simd:
3061 Res = ActOnOpenMPTargetParallelForSimdDirective(
3062 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3063 AllowedNameModifiers.push_back(OMPD_target);
3064 AllowedNameModifiers.push_back(OMPD_parallel);
3065 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003066 case OMPD_target_simd:
3067 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3068 EndLoc, VarsWithInheritedDSA);
3069 AllowedNameModifiers.push_back(OMPD_target);
3070 break;
Kelvin Li02532872016-08-05 14:37:37 +00003071 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003072 Res = ActOnOpenMPTeamsDistributeDirective(
3073 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003074 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003075 case OMPD_teams_distribute_simd:
3076 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3077 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3078 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003079 case OMPD_teams_distribute_parallel_for_simd:
3080 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3081 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3082 AllowedNameModifiers.push_back(OMPD_parallel);
3083 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003084 case OMPD_teams_distribute_parallel_for:
3085 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3086 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3087 AllowedNameModifiers.push_back(OMPD_parallel);
3088 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003089 case OMPD_target_teams:
3090 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3091 EndLoc);
3092 AllowedNameModifiers.push_back(OMPD_target);
3093 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003094 case OMPD_target_teams_distribute:
3095 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3096 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3097 AllowedNameModifiers.push_back(OMPD_target);
3098 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003099 case OMPD_target_teams_distribute_parallel_for:
3100 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3101 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3102 AllowedNameModifiers.push_back(OMPD_target);
3103 AllowedNameModifiers.push_back(OMPD_parallel);
3104 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003105 case OMPD_target_teams_distribute_parallel_for_simd:
3106 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3107 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3108 AllowedNameModifiers.push_back(OMPD_target);
3109 AllowedNameModifiers.push_back(OMPD_parallel);
3110 break;
Kelvin Lida681182017-01-10 18:08:18 +00003111 case OMPD_target_teams_distribute_simd:
3112 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3113 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3114 AllowedNameModifiers.push_back(OMPD_target);
3115 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003116 case OMPD_declare_target:
3117 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003118 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003119 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003120 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003121 llvm_unreachable("OpenMP Directive is not allowed");
3122 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003123 llvm_unreachable("Unknown OpenMP directive");
3124 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003125
Alexey Bataev4acb8592014-07-07 13:01:15 +00003126 for (auto P : VarsWithInheritedDSA) {
3127 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3128 << P.first << P.second->getSourceRange();
3129 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003130 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3131
3132 if (!AllowedNameModifiers.empty())
3133 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3134 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003135
Alexey Bataeved09d242014-05-28 05:53:51 +00003136 if (ErrorFound)
3137 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003138 return Res;
3139}
3140
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003141Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3142 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003143 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003144 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3145 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003146 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003147 assert(Linears.size() == LinModifiers.size());
3148 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003149 if (!DG || DG.get().isNull())
3150 return DeclGroupPtrTy();
3151
3152 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003153 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003154 return DG;
3155 }
3156 auto *ADecl = DG.get().getSingleDecl();
3157 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3158 ADecl = FTD->getTemplatedDecl();
3159
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003160 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3161 if (!FD) {
3162 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003163 return DeclGroupPtrTy();
3164 }
3165
Alexey Bataev2af33e32016-04-07 12:45:37 +00003166 // OpenMP [2.8.2, declare simd construct, Description]
3167 // The parameter of the simdlen clause must be a constant positive integer
3168 // expression.
3169 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003170 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003171 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003172 // OpenMP [2.8.2, declare simd construct, Description]
3173 // The special this pointer can be used as if was one of the arguments to the
3174 // function in any of the linear, aligned, or uniform clauses.
3175 // The uniform clause declares one or more arguments to have an invariant
3176 // value for all concurrent invocations of the function in the execution of a
3177 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003178 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3179 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003180 for (auto *E : Uniforms) {
3181 E = E->IgnoreParenImpCasts();
3182 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3183 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3184 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3185 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003186 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3187 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003188 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003189 }
3190 if (isa<CXXThisExpr>(E)) {
3191 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003192 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003193 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003194 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3195 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003196 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003197 // OpenMP [2.8.2, declare simd construct, Description]
3198 // The aligned clause declares that the object to which each list item points
3199 // is aligned to the number of bytes expressed in the optional parameter of
3200 // the aligned clause.
3201 // The special this pointer can be used as if was one of the arguments to the
3202 // function in any of the linear, aligned, or uniform clauses.
3203 // The type of list items appearing in the aligned clause must be array,
3204 // pointer, reference to array, or reference to pointer.
3205 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3206 Expr *AlignedThis = nullptr;
3207 for (auto *E : Aligneds) {
3208 E = E->IgnoreParenImpCasts();
3209 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3210 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3211 auto *CanonPVD = PVD->getCanonicalDecl();
3212 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3213 FD->getParamDecl(PVD->getFunctionScopeIndex())
3214 ->getCanonicalDecl() == CanonPVD) {
3215 // OpenMP [2.8.1, simd construct, Restrictions]
3216 // A list-item cannot appear in more than one aligned clause.
3217 if (AlignedArgs.count(CanonPVD) > 0) {
3218 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3219 << 1 << E->getSourceRange();
3220 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3221 diag::note_omp_explicit_dsa)
3222 << getOpenMPClauseName(OMPC_aligned);
3223 continue;
3224 }
3225 AlignedArgs[CanonPVD] = E;
3226 QualType QTy = PVD->getType()
3227 .getNonReferenceType()
3228 .getUnqualifiedType()
3229 .getCanonicalType();
3230 const Type *Ty = QTy.getTypePtrOrNull();
3231 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3232 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3233 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3234 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3235 }
3236 continue;
3237 }
3238 }
3239 if (isa<CXXThisExpr>(E)) {
3240 if (AlignedThis) {
3241 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3242 << 2 << E->getSourceRange();
3243 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3244 << getOpenMPClauseName(OMPC_aligned);
3245 }
3246 AlignedThis = E;
3247 continue;
3248 }
3249 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3250 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3251 }
3252 // The optional parameter of the aligned clause, alignment, must be a constant
3253 // positive integer expression. If no optional parameter is specified,
3254 // implementation-defined default alignments for SIMD instructions on the
3255 // target platforms are assumed.
3256 SmallVector<Expr *, 4> NewAligns;
3257 for (auto *E : Alignments) {
3258 ExprResult Align;
3259 if (E)
3260 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3261 NewAligns.push_back(Align.get());
3262 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003263 // OpenMP [2.8.2, declare simd construct, Description]
3264 // The linear clause declares one or more list items to be private to a SIMD
3265 // lane and to have a linear relationship with respect to the iteration space
3266 // of a loop.
3267 // The special this pointer can be used as if was one of the arguments to the
3268 // function in any of the linear, aligned, or uniform clauses.
3269 // When a linear-step expression is specified in a linear clause it must be
3270 // either a constant integer expression or an integer-typed parameter that is
3271 // specified in a uniform clause on the directive.
3272 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3273 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3274 auto MI = LinModifiers.begin();
3275 for (auto *E : Linears) {
3276 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3277 ++MI;
3278 E = E->IgnoreParenImpCasts();
3279 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3280 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3281 auto *CanonPVD = PVD->getCanonicalDecl();
3282 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3283 FD->getParamDecl(PVD->getFunctionScopeIndex())
3284 ->getCanonicalDecl() == CanonPVD) {
3285 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3286 // A list-item cannot appear in more than one linear clause.
3287 if (LinearArgs.count(CanonPVD) > 0) {
3288 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3289 << getOpenMPClauseName(OMPC_linear)
3290 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3291 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3292 diag::note_omp_explicit_dsa)
3293 << getOpenMPClauseName(OMPC_linear);
3294 continue;
3295 }
3296 // Each argument can appear in at most one uniform or linear clause.
3297 if (UniformedArgs.count(CanonPVD) > 0) {
3298 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3299 << getOpenMPClauseName(OMPC_linear)
3300 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3301 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3302 diag::note_omp_explicit_dsa)
3303 << getOpenMPClauseName(OMPC_uniform);
3304 continue;
3305 }
3306 LinearArgs[CanonPVD] = E;
3307 if (E->isValueDependent() || E->isTypeDependent() ||
3308 E->isInstantiationDependent() ||
3309 E->containsUnexpandedParameterPack())
3310 continue;
3311 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3312 PVD->getOriginalType());
3313 continue;
3314 }
3315 }
3316 if (isa<CXXThisExpr>(E)) {
3317 if (UniformedLinearThis) {
3318 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3319 << getOpenMPClauseName(OMPC_linear)
3320 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3321 << E->getSourceRange();
3322 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3323 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3324 : OMPC_linear);
3325 continue;
3326 }
3327 UniformedLinearThis = E;
3328 if (E->isValueDependent() || E->isTypeDependent() ||
3329 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3330 continue;
3331 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3332 E->getType());
3333 continue;
3334 }
3335 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3336 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3337 }
3338 Expr *Step = nullptr;
3339 Expr *NewStep = nullptr;
3340 SmallVector<Expr *, 4> NewSteps;
3341 for (auto *E : Steps) {
3342 // Skip the same step expression, it was checked already.
3343 if (Step == E || !E) {
3344 NewSteps.push_back(E ? NewStep : nullptr);
3345 continue;
3346 }
3347 Step = E;
3348 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3349 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3350 auto *CanonPVD = PVD->getCanonicalDecl();
3351 if (UniformedArgs.count(CanonPVD) == 0) {
3352 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3353 << Step->getSourceRange();
3354 } else if (E->isValueDependent() || E->isTypeDependent() ||
3355 E->isInstantiationDependent() ||
3356 E->containsUnexpandedParameterPack() ||
3357 CanonPVD->getType()->hasIntegerRepresentation())
3358 NewSteps.push_back(Step);
3359 else {
3360 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3361 << Step->getSourceRange();
3362 }
3363 continue;
3364 }
3365 NewStep = Step;
3366 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3367 !Step->isInstantiationDependent() &&
3368 !Step->containsUnexpandedParameterPack()) {
3369 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3370 .get();
3371 if (NewStep)
3372 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3373 }
3374 NewSteps.push_back(NewStep);
3375 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003376 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3377 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003378 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003379 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3380 const_cast<Expr **>(Linears.data()), Linears.size(),
3381 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3382 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003383 ADecl->addAttr(NewAttr);
3384 return ConvertDeclToDeclGroup(ADecl);
3385}
3386
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003387StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3388 Stmt *AStmt,
3389 SourceLocation StartLoc,
3390 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003391 if (!AStmt)
3392 return StmtError();
3393
Alexey Bataev9959db52014-05-06 10:08:46 +00003394 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3395 // 1.2.2 OpenMP Language Terminology
3396 // Structured block - An executable statement with a single entry at the
3397 // top and a single exit at the bottom.
3398 // The point of exit cannot be a branch out of the structured block.
3399 // longjmp() and throw() must not violate the entry/exit criteria.
3400 CS->getCapturedDecl()->setNothrow();
3401
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003402 getCurFunction()->setHasBranchProtectedScope();
3403
Alexey Bataev25e5b442015-09-15 12:52:43 +00003404 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3405 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003406}
3407
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003408namespace {
3409/// \brief Helper class for checking canonical form of the OpenMP loops and
3410/// extracting iteration space of each loop in the loop nest, that will be used
3411/// for IR generation.
3412class OpenMPIterationSpaceChecker {
3413 /// \brief Reference to Sema.
3414 Sema &SemaRef;
3415 /// \brief A location for diagnostics (when there is no some better location).
3416 SourceLocation DefaultLoc;
3417 /// \brief A location for diagnostics (when increment is not compatible).
3418 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003419 /// \brief A source location for referring to loop init later.
3420 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003421 /// \brief A source location for referring to condition later.
3422 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003423 /// \brief A source location for referring to increment later.
3424 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003425 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003426 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003427 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003428 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003429 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003430 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003431 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003432 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003433 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003434 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003435 /// \brief This flag is true when condition is one of:
3436 /// Var < UB
3437 /// Var <= UB
3438 /// UB > Var
3439 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003440 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003441 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003442 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003443 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003444 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003445
3446public:
3447 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003449 /// \brief Check init-expr for canonical loop form and save loop counter
3450 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003451 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003452 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3453 /// for less/greater and for strict/non-strict comparison.
3454 bool CheckCond(Expr *S);
3455 /// \brief Check incr-expr for canonical loop form and return true if it
3456 /// does not conform, otherwise save loop step (#Step).
3457 bool CheckInc(Expr *S);
3458 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003459 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003460 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003461 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003462 /// \brief Source range of the loop init.
3463 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3464 /// \brief Source range of the loop condition.
3465 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3466 /// \brief Source range of the loop increment.
3467 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3468 /// \brief True if the step should be subtracted.
3469 bool ShouldSubtractStep() const { return SubtractStep; }
3470 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003471 Expr *
3472 BuildNumIterations(Scope *S, const bool LimitedType,
3473 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003474 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003475 Expr *BuildPreCond(Scope *S, Expr *Cond,
3476 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003477 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003478 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3479 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003480 /// \brief Build reference expression to the private counter be used for
3481 /// codegen.
3482 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003483 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003484 Expr *BuildCounterInit() const;
3485 /// \brief Build step of the counter be used for codegen.
3486 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003487 /// \brief Return true if any expression is dependent.
3488 bool Dependent() const;
3489
3490private:
3491 /// \brief Check the right-hand side of an assignment in the increment
3492 /// expression.
3493 bool CheckIncRHS(Expr *RHS);
3494 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003495 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003496 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003497 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003498 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003499 /// \brief Helper to set loop increment.
3500 bool SetStep(Expr *NewStep, bool Subtract);
3501};
3502
3503bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003504 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003505 assert(!LB && !UB && !Step);
3506 return false;
3507 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003508 return LCDecl->getType()->isDependentType() ||
3509 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3510 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003511}
3512
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003513bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3514 Expr *NewLCRefExpr,
3515 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003516 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003517 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003518 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003519 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003520 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003521 LCDecl = getCanonicalDecl(NewLCDecl);
3522 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003523 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3524 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003525 if ((Ctor->isCopyOrMoveConstructor() ||
3526 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3527 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003528 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003529 LB = NewLB;
3530 return false;
3531}
3532
3533bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003534 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003535 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003536 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3537 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003538 if (!NewUB)
3539 return true;
3540 UB = NewUB;
3541 TestIsLessOp = LessOp;
3542 TestIsStrictOp = StrictOp;
3543 ConditionSrcRange = SR;
3544 ConditionLoc = SL;
3545 return false;
3546}
3547
3548bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3549 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003550 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003551 if (!NewStep)
3552 return true;
3553 if (!NewStep->isValueDependent()) {
3554 // Check that the step is integer expression.
3555 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003556 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3557 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003558 if (Val.isInvalid())
3559 return true;
3560 NewStep = Val.get();
3561
3562 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3563 // If test-expr is of form var relational-op b and relational-op is < or
3564 // <= then incr-expr must cause var to increase on each iteration of the
3565 // loop. If test-expr is of form var relational-op b and relational-op is
3566 // > or >= then incr-expr must cause var to decrease on each iteration of
3567 // the loop.
3568 // If test-expr is of form b relational-op var and relational-op is < or
3569 // <= then incr-expr must cause var to decrease on each iteration of the
3570 // loop. If test-expr is of form b relational-op var and relational-op is
3571 // > or >= then incr-expr must cause var to increase on each iteration of
3572 // the loop.
3573 llvm::APSInt Result;
3574 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3575 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3576 bool IsConstNeg =
3577 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003578 bool IsConstPos =
3579 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003580 bool IsConstZero = IsConstant && !Result.getBoolValue();
3581 if (UB && (IsConstZero ||
3582 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003583 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003584 SemaRef.Diag(NewStep->getExprLoc(),
3585 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003586 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003587 SemaRef.Diag(ConditionLoc,
3588 diag::note_omp_loop_cond_requres_compatible_incr)
3589 << TestIsLessOp << ConditionSrcRange;
3590 return true;
3591 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003592 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003593 NewStep =
3594 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3595 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003596 Subtract = !Subtract;
3597 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003598 }
3599
3600 Step = NewStep;
3601 SubtractStep = Subtract;
3602 return false;
3603}
3604
Alexey Bataev9c821032015-04-30 04:23:23 +00003605bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003606 // Check init-expr for canonical loop form and save loop counter
3607 // variable - #Var and its initialization value - #LB.
3608 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3609 // var = lb
3610 // integer-type var = lb
3611 // random-access-iterator-type var = lb
3612 // pointer-type var = lb
3613 //
3614 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003615 if (EmitDiags) {
3616 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3617 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003618 return true;
3619 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003620 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3621 if (!ExprTemp->cleanupsHaveSideEffects())
3622 S = ExprTemp->getSubExpr();
3623
Alexander Musmana5f070a2014-10-01 06:03:56 +00003624 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003625 if (Expr *E = dyn_cast<Expr>(S))
3626 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003627 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003628 if (BO->getOpcode() == BO_Assign) {
3629 auto *LHS = BO->getLHS()->IgnoreParens();
3630 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3631 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3632 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3633 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3634 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3635 }
3636 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3637 if (ME->isArrow() &&
3638 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3639 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3640 }
3641 }
David Majnemer9d168222016-08-05 17:44:54 +00003642 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003643 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003644 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003645 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003646 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003647 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003648 SemaRef.Diag(S->getLocStart(),
3649 diag::ext_omp_loop_not_canonical_init)
3650 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003651 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003652 }
3653 }
3654 }
David Majnemer9d168222016-08-05 17:44:54 +00003655 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003656 if (CE->getOperator() == OO_Equal) {
3657 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003658 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003659 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3660 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3661 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3662 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3663 }
3664 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3665 if (ME->isArrow() &&
3666 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3667 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3668 }
3669 }
3670 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003671
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003672 if (Dependent() || SemaRef.CurContext->isDependentContext())
3673 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003674 if (EmitDiags) {
3675 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3676 << S->getSourceRange();
3677 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003678 return true;
3679}
3680
Alexey Bataev23b69422014-06-18 07:08:49 +00003681/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003682/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003683static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003684 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003685 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003686 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003687 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3688 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003689 if ((Ctor->isCopyOrMoveConstructor() ||
3690 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3691 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003692 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003693 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003694 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003695 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003696 }
3697 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3698 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3699 return getCanonicalDecl(ME->getMemberDecl());
3700 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003701}
3702
3703bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3704 // Check test-expr for canonical form, save upper-bound UB, flags for
3705 // less/greater and for strict/non-strict comparison.
3706 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3707 // var relational-op b
3708 // b relational-op var
3709 //
3710 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003711 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003712 return true;
3713 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003714 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003715 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003716 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003717 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003718 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003719 return SetUB(BO->getRHS(),
3720 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3721 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3722 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003723 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003724 return SetUB(BO->getLHS(),
3725 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3726 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3727 BO->getSourceRange(), BO->getOperatorLoc());
3728 }
David Majnemer9d168222016-08-05 17:44:54 +00003729 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003730 if (CE->getNumArgs() == 2) {
3731 auto Op = CE->getOperator();
3732 switch (Op) {
3733 case OO_Greater:
3734 case OO_GreaterEqual:
3735 case OO_Less:
3736 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003737 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003738 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3739 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3740 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003741 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003742 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3743 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3744 CE->getOperatorLoc());
3745 break;
3746 default:
3747 break;
3748 }
3749 }
3750 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003751 if (Dependent() || SemaRef.CurContext->isDependentContext())
3752 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003753 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003754 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003755 return true;
3756}
3757
3758bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3759 // RHS of canonical loop form increment can be:
3760 // var + incr
3761 // incr + var
3762 // var - incr
3763 //
3764 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003765 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003766 if (BO->isAdditiveOp()) {
3767 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003768 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003769 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003770 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003771 return SetStep(BO->getLHS(), false);
3772 }
David Majnemer9d168222016-08-05 17:44:54 +00003773 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003774 bool IsAdd = CE->getOperator() == OO_Plus;
3775 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003776 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003777 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003778 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003779 return SetStep(CE->getArg(0), false);
3780 }
3781 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003782 if (Dependent() || SemaRef.CurContext->isDependentContext())
3783 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003784 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003785 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003786 return true;
3787}
3788
3789bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3790 // Check incr-expr for canonical loop form and return true if it
3791 // does not conform.
3792 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3793 // ++var
3794 // var++
3795 // --var
3796 // var--
3797 // var += incr
3798 // var -= incr
3799 // var = var + incr
3800 // var = incr + var
3801 // var = var - incr
3802 //
3803 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003804 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003805 return true;
3806 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003807 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3808 if (!ExprTemp->cleanupsHaveSideEffects())
3809 S = ExprTemp->getSubExpr();
3810
Alexander Musmana5f070a2014-10-01 06:03:56 +00003811 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003812 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003813 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003814 if (UO->isIncrementDecrementOp() &&
3815 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003816 return SetStep(SemaRef
3817 .ActOnIntegerConstant(UO->getLocStart(),
3818 (UO->isDecrementOp() ? -1 : 1))
3819 .get(),
3820 false);
3821 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003822 switch (BO->getOpcode()) {
3823 case BO_AddAssign:
3824 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003825 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003826 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3827 break;
3828 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003829 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003830 return CheckIncRHS(BO->getRHS());
3831 break;
3832 default:
3833 break;
3834 }
David Majnemer9d168222016-08-05 17:44:54 +00003835 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003836 switch (CE->getOperator()) {
3837 case OO_PlusPlus:
3838 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003839 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003840 return SetStep(SemaRef
3841 .ActOnIntegerConstant(
3842 CE->getLocStart(),
3843 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3844 .get(),
3845 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003846 break;
3847 case OO_PlusEqual:
3848 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003849 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003850 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3851 break;
3852 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003853 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003854 return CheckIncRHS(CE->getArg(1));
3855 break;
3856 default:
3857 break;
3858 }
3859 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003860 if (Dependent() || SemaRef.CurContext->isDependentContext())
3861 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003862 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003863 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003864 return true;
3865}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003866
Alexey Bataev5a3af132016-03-29 08:58:54 +00003867static ExprResult
3868tryBuildCapture(Sema &SemaRef, Expr *Capture,
3869 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003870 if (SemaRef.CurContext->isDependentContext())
3871 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003872 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3873 return SemaRef.PerformImplicitConversion(
3874 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3875 /*AllowExplicit=*/true);
3876 auto I = Captures.find(Capture);
3877 if (I != Captures.end())
3878 return buildCapture(SemaRef, Capture, I->second);
3879 DeclRefExpr *Ref = nullptr;
3880 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3881 Captures[Capture] = Ref;
3882 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003883}
3884
Alexander Musmana5f070a2014-10-01 06:03:56 +00003885/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003886Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3887 Scope *S, const bool LimitedType,
3888 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003889 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003890 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003891 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892 SemaRef.getLangOpts().CPlusPlus) {
3893 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003894 auto *UBExpr = TestIsLessOp ? UB : LB;
3895 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003896 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3897 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003898 if (!Upper || !Lower)
3899 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003900
3901 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3902
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003903 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003904 // BuildBinOp already emitted error, this one is to point user to upper
3905 // and lower bound, and to tell what is passed to 'operator-'.
3906 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3907 << Upper->getSourceRange() << Lower->getSourceRange();
3908 return nullptr;
3909 }
3910 }
3911
3912 if (!Diff.isUsable())
3913 return nullptr;
3914
3915 // Upper - Lower [- 1]
3916 if (TestIsStrictOp)
3917 Diff = SemaRef.BuildBinOp(
3918 S, DefaultLoc, BO_Sub, Diff.get(),
3919 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3920 if (!Diff.isUsable())
3921 return nullptr;
3922
3923 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003924 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3925 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003926 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003927 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003928 if (!Diff.isUsable())
3929 return nullptr;
3930
3931 // Parentheses (for dumping/debugging purposes only).
3932 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3933 if (!Diff.isUsable())
3934 return nullptr;
3935
3936 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003937 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003938 if (!Diff.isUsable())
3939 return nullptr;
3940
Alexander Musman174b3ca2014-10-06 11:16:29 +00003941 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003942 QualType Type = Diff.get()->getType();
3943 auto &C = SemaRef.Context;
3944 bool UseVarType = VarType->hasIntegerRepresentation() &&
3945 C.getTypeSize(Type) > C.getTypeSize(VarType);
3946 if (!Type->isIntegerType() || UseVarType) {
3947 unsigned NewSize =
3948 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3949 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3950 : Type->hasSignedIntegerRepresentation();
3951 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003952 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3953 Diff = SemaRef.PerformImplicitConversion(
3954 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3955 if (!Diff.isUsable())
3956 return nullptr;
3957 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003958 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003959 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003960 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3961 if (NewSize != C.getTypeSize(Type)) {
3962 if (NewSize < C.getTypeSize(Type)) {
3963 assert(NewSize == 64 && "incorrect loop var size");
3964 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3965 << InitSrcRange << ConditionSrcRange;
3966 }
3967 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003968 NewSize, Type->hasSignedIntegerRepresentation() ||
3969 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003970 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3971 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3972 Sema::AA_Converting, true);
3973 if (!Diff.isUsable())
3974 return nullptr;
3975 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003976 }
3977 }
3978
Alexander Musmana5f070a2014-10-01 06:03:56 +00003979 return Diff.get();
3980}
3981
Alexey Bataev5a3af132016-03-29 08:58:54 +00003982Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3983 Scope *S, Expr *Cond,
3984 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003985 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3986 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3987 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003988
Alexey Bataev5a3af132016-03-29 08:58:54 +00003989 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3990 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3991 if (!NewLB.isUsable() || !NewUB.isUsable())
3992 return nullptr;
3993
Alexey Bataev62dbb972015-04-22 11:59:37 +00003994 auto CondExpr = SemaRef.BuildBinOp(
3995 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3996 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003997 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003998 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003999 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4000 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004001 CondExpr = SemaRef.PerformImplicitConversion(
4002 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4003 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004004 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004005 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4006 // Otherwise use original loop conditon and evaluate it in runtime.
4007 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4008}
4009
Alexander Musmana5f070a2014-10-01 06:03:56 +00004010/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004011DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004012 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004013 auto *VD = dyn_cast<VarDecl>(LCDecl);
4014 if (!VD) {
4015 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4016 auto *Ref = buildDeclRefExpr(
4017 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004018 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4019 // If the loop control decl is explicitly marked as private, do not mark it
4020 // as captured again.
4021 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4022 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004023 return Ref;
4024 }
4025 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004026 DefaultLoc);
4027}
4028
4029Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004030 if (LCDecl && !LCDecl->isInvalidDecl()) {
4031 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004032 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004033 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4034 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004035 if (PrivateVar->isInvalidDecl())
4036 return nullptr;
4037 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4038 }
4039 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004040}
4041
Samuel Antao4c8035b2016-12-12 18:00:20 +00004042/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004043Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4044
4045/// \brief Build step of the counter be used for codegen.
4046Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4047
4048/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004049struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004050 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004051 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004052 /// \brief This expression calculates the number of iterations in the loop.
4053 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004054 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004055 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004056 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004057 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004058 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004059 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004060 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004061 /// \brief This is step for the #CounterVar used to generate its update:
4062 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004063 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004064 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004065 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004066 /// \brief Source range of the loop init.
4067 SourceRange InitSrcRange;
4068 /// \brief Source range of the loop condition.
4069 SourceRange CondSrcRange;
4070 /// \brief Source range of the loop increment.
4071 SourceRange IncSrcRange;
4072};
4073
Alexey Bataev23b69422014-06-18 07:08:49 +00004074} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004075
Alexey Bataev9c821032015-04-30 04:23:23 +00004076void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4077 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4078 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004079 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4080 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004081 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4082 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004083 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4084 if (auto *D = ISC.GetLoopDecl()) {
4085 auto *VD = dyn_cast<VarDecl>(D);
4086 if (!VD) {
4087 if (auto *Private = IsOpenMPCapturedDecl(D))
4088 VD = Private;
4089 else {
4090 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4091 /*WithInit=*/false);
4092 VD = cast<VarDecl>(Ref->getDecl());
4093 }
4094 }
4095 DSAStack->addLoopControlVariable(D, VD);
4096 }
4097 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004098 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004099 }
4100}
4101
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004102/// \brief Called on a for stmt to check and extract its iteration space
4103/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004104static bool CheckOpenMPIterationSpace(
4105 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4106 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004107 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004108 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004109 LoopIterationSpace &ResultIterSpace,
4110 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004111 // OpenMP [2.6, Canonical Loop Form]
4112 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004113 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004114 if (!For) {
4115 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004116 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4117 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4118 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4119 if (NestedLoopCount > 1) {
4120 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4121 SemaRef.Diag(DSA.getConstructLoc(),
4122 diag::note_omp_collapse_ordered_expr)
4123 << 2 << CollapseLoopCountExpr->getSourceRange()
4124 << OrderedLoopCountExpr->getSourceRange();
4125 else if (CollapseLoopCountExpr)
4126 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4127 diag::note_omp_collapse_ordered_expr)
4128 << 0 << CollapseLoopCountExpr->getSourceRange();
4129 else
4130 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4131 diag::note_omp_collapse_ordered_expr)
4132 << 1 << OrderedLoopCountExpr->getSourceRange();
4133 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004134 return true;
4135 }
4136 assert(For->getBody());
4137
4138 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4139
4140 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004141 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004142 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004143 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004144
4145 bool HasErrors = false;
4146
4147 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004148 if (auto *LCDecl = ISC.GetLoopDecl()) {
4149 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004150
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004151 // OpenMP [2.6, Canonical Loop Form]
4152 // Var is one of the following:
4153 // A variable of signed or unsigned integer type.
4154 // For C++, a variable of a random access iterator type.
4155 // For C, a variable of a pointer type.
4156 auto VarType = LCDecl->getType().getNonReferenceType();
4157 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4158 !VarType->isPointerType() &&
4159 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4160 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4161 << SemaRef.getLangOpts().CPlusPlus;
4162 HasErrors = true;
4163 }
4164
4165 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4166 // a Construct
4167 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4168 // parallel for construct is (are) private.
4169 // The loop iteration variable in the associated for-loop of a simd
4170 // construct with just one associated for-loop is linear with a
4171 // constant-linear-step that is the increment of the associated for-loop.
4172 // Exclude loop var from the list of variables with implicitly defined data
4173 // sharing attributes.
4174 VarsWithImplicitDSA.erase(LCDecl);
4175
4176 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4177 // in a Construct, C/C++].
4178 // The loop iteration variable in the associated for-loop of a simd
4179 // construct with just one associated for-loop may be listed in a linear
4180 // clause with a constant-linear-step that is the increment of the
4181 // associated for-loop.
4182 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4183 // parallel for construct may be listed in a private or lastprivate clause.
4184 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4185 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4186 // declared in the loop and it is predetermined as a private.
4187 auto PredeterminedCKind =
4188 isOpenMPSimdDirective(DKind)
4189 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4190 : OMPC_private;
4191 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4192 DVar.CKind != PredeterminedCKind) ||
4193 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4194 isOpenMPDistributeDirective(DKind)) &&
4195 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4196 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4197 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4198 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4199 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4200 << getOpenMPClauseName(PredeterminedCKind);
4201 if (DVar.RefExpr == nullptr)
4202 DVar.CKind = PredeterminedCKind;
4203 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4204 HasErrors = true;
4205 } else if (LoopDeclRefExpr != nullptr) {
4206 // Make the loop iteration variable private (for worksharing constructs),
4207 // linear (for simd directives with the only one associated loop) or
4208 // lastprivate (for simd directives with several collapsed or ordered
4209 // loops).
4210 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004211 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4212 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004213 /*FromParent=*/false);
4214 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4215 }
4216
4217 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4218
4219 // Check test-expr.
4220 HasErrors |= ISC.CheckCond(For->getCond());
4221
4222 // Check incr-expr.
4223 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004224 }
4225
Alexander Musmana5f070a2014-10-01 06:03:56 +00004226 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004227 return HasErrors;
4228
Alexander Musmana5f070a2014-10-01 06:03:56 +00004229 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004230 ResultIterSpace.PreCond =
4231 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004232 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004233 DSA.getCurScope(),
4234 (isOpenMPWorksharingDirective(DKind) ||
4235 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4236 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004237 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004238 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004239 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4240 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4241 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4242 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4243 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4244 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4245
Alexey Bataev62dbb972015-04-22 11:59:37 +00004246 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4247 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004248 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004249 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004250 ResultIterSpace.CounterInit == nullptr ||
4251 ResultIterSpace.CounterStep == nullptr);
4252
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004253 return HasErrors;
4254}
4255
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004256/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004257static ExprResult
4258BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4259 ExprResult Start,
4260 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004261 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004262 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4263 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004264 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004265 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004266 VarRef.get()->getType())) {
4267 NewStart = SemaRef.PerformImplicitConversion(
4268 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4269 /*AllowExplicit=*/true);
4270 if (!NewStart.isUsable())
4271 return ExprError();
4272 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004273
4274 auto Init =
4275 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4276 return Init;
4277}
4278
Alexander Musmana5f070a2014-10-01 06:03:56 +00004279/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004280static ExprResult
4281BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4282 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4283 ExprResult Step, bool Subtract,
4284 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004285 // Add parentheses (for debugging purposes only).
4286 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4287 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4288 !Step.isUsable())
4289 return ExprError();
4290
Alexey Bataev5a3af132016-03-29 08:58:54 +00004291 ExprResult NewStep = Step;
4292 if (Captures)
4293 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004294 if (NewStep.isInvalid())
4295 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004296 ExprResult Update =
4297 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004298 if (!Update.isUsable())
4299 return ExprError();
4300
Alexey Bataevc0214e02016-02-16 12:13:49 +00004301 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4302 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004303 ExprResult NewStart = Start;
4304 if (Captures)
4305 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004306 if (NewStart.isInvalid())
4307 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004308
Alexey Bataevc0214e02016-02-16 12:13:49 +00004309 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4310 ExprResult SavedUpdate = Update;
4311 ExprResult UpdateVal;
4312 if (VarRef.get()->getType()->isOverloadableType() ||
4313 NewStart.get()->getType()->isOverloadableType() ||
4314 Update.get()->getType()->isOverloadableType()) {
4315 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4316 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4317 Update =
4318 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4319 if (Update.isUsable()) {
4320 UpdateVal =
4321 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4322 VarRef.get(), SavedUpdate.get());
4323 if (UpdateVal.isUsable()) {
4324 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4325 UpdateVal.get());
4326 }
4327 }
4328 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4329 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004330
Alexey Bataevc0214e02016-02-16 12:13:49 +00004331 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4332 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4333 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4334 NewStart.get(), SavedUpdate.get());
4335 if (!Update.isUsable())
4336 return ExprError();
4337
Alexey Bataev11481f52016-02-17 10:29:05 +00004338 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4339 VarRef.get()->getType())) {
4340 Update = SemaRef.PerformImplicitConversion(
4341 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4342 if (!Update.isUsable())
4343 return ExprError();
4344 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004345
4346 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4347 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004348 return Update;
4349}
4350
4351/// \brief Convert integer expression \a E to make it have at least \a Bits
4352/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004353static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004354 if (E == nullptr)
4355 return ExprError();
4356 auto &C = SemaRef.Context;
4357 QualType OldType = E->getType();
4358 unsigned HasBits = C.getTypeSize(OldType);
4359 if (HasBits >= Bits)
4360 return ExprResult(E);
4361 // OK to convert to signed, because new type has more bits than old.
4362 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4363 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4364 true);
4365}
4366
4367/// \brief Check if the given expression \a E is a constant integer that fits
4368/// into \a Bits bits.
4369static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4370 if (E == nullptr)
4371 return false;
4372 llvm::APSInt Result;
4373 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4374 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4375 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004376}
4377
Alexey Bataev5a3af132016-03-29 08:58:54 +00004378/// Build preinits statement for the given declarations.
4379static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004380 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004381 if (!PreInits.empty()) {
4382 return new (Context) DeclStmt(
4383 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4384 SourceLocation(), SourceLocation());
4385 }
4386 return nullptr;
4387}
4388
4389/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004390static Stmt *
4391buildPreInits(ASTContext &Context,
4392 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004393 if (!Captures.empty()) {
4394 SmallVector<Decl *, 16> PreInits;
4395 for (auto &Pair : Captures)
4396 PreInits.push_back(Pair.second->getDecl());
4397 return buildPreInits(Context, PreInits);
4398 }
4399 return nullptr;
4400}
4401
4402/// Build postupdate expression for the given list of postupdates expressions.
4403static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4404 Expr *PostUpdate = nullptr;
4405 if (!PostUpdates.empty()) {
4406 for (auto *E : PostUpdates) {
4407 Expr *ConvE = S.BuildCStyleCastExpr(
4408 E->getExprLoc(),
4409 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4410 E->getExprLoc(), E)
4411 .get();
4412 PostUpdate = PostUpdate
4413 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4414 PostUpdate, ConvE)
4415 .get()
4416 : ConvE;
4417 }
4418 }
4419 return PostUpdate;
4420}
4421
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004422/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004423/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4424/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004425static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004426CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4427 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4428 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004429 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004430 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004431 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004432 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004433 // Found 'collapse' clause - calculate collapse number.
4434 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004435 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004436 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004437 }
4438 if (OrderedLoopCountExpr) {
4439 // Found 'ordered' clause - calculate collapse number.
4440 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004441 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4442 if (Result.getLimitedValue() < NestedLoopCount) {
4443 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4444 diag::err_omp_wrong_ordered_loop_count)
4445 << OrderedLoopCountExpr->getSourceRange();
4446 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4447 diag::note_collapse_loop_count)
4448 << CollapseLoopCountExpr->getSourceRange();
4449 }
4450 NestedLoopCount = Result.getLimitedValue();
4451 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004452 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004453 // This is helper routine for loop directives (e.g., 'for', 'simd',
4454 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004455 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004456 SmallVector<LoopIterationSpace, 4> IterSpaces;
4457 IterSpaces.resize(NestedLoopCount);
4458 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004459 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004460 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004461 NestedLoopCount, CollapseLoopCountExpr,
4462 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004463 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004464 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004465 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004466 // OpenMP [2.8.1, simd construct, Restrictions]
4467 // All loops associated with the construct must be perfectly nested; that
4468 // is, there must be no intervening code nor any OpenMP directive between
4469 // any two loops.
4470 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004471 }
4472
Alexander Musmana5f070a2014-10-01 06:03:56 +00004473 Built.clear(/* size */ NestedLoopCount);
4474
4475 if (SemaRef.CurContext->isDependentContext())
4476 return NestedLoopCount;
4477
4478 // An example of what is generated for the following code:
4479 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004480 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004481 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004482 // for (k = 0; k < NK; ++k)
4483 // for (j = J0; j < NJ; j+=2) {
4484 // <loop body>
4485 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004486 //
4487 // We generate the code below.
4488 // Note: the loop body may be outlined in CodeGen.
4489 // Note: some counters may be C++ classes, operator- is used to find number of
4490 // iterations and operator+= to calculate counter value.
4491 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4492 // or i64 is currently supported).
4493 //
4494 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4495 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4496 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4497 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4498 // // similar updates for vars in clauses (e.g. 'linear')
4499 // <loop body (using local i and j)>
4500 // }
4501 // i = NI; // assign final values of counters
4502 // j = NJ;
4503 //
4504
4505 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4506 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004507 // Precondition tests if there is at least one iteration (all conditions are
4508 // true).
4509 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004510 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004511 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004512 32 /* Bits */, SemaRef
4513 .PerformImplicitConversion(
4514 N0->IgnoreImpCasts(), N0->getType(),
4515 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004516 .get(),
4517 SemaRef);
4518 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004519 64 /* Bits */, SemaRef
4520 .PerformImplicitConversion(
4521 N0->IgnoreImpCasts(), N0->getType(),
4522 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004523 .get(),
4524 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004525
4526 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4527 return NestedLoopCount;
4528
4529 auto &C = SemaRef.Context;
4530 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4531
4532 Scope *CurScope = DSA.getCurScope();
4533 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004534 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004535 PreCond =
4536 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4537 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004538 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004539 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004540 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004541 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4542 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004543 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004544 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004545 SemaRef
4546 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4547 Sema::AA_Converting,
4548 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004549 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004550 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004551 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004552 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004553 SemaRef
4554 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4555 Sema::AA_Converting,
4556 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004557 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004558 }
4559
4560 // Choose either the 32-bit or 64-bit version.
4561 ExprResult LastIteration = LastIteration64;
4562 if (LastIteration32.isUsable() &&
4563 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4564 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4565 FitsInto(
4566 32 /* Bits */,
4567 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4568 LastIteration64.get(), SemaRef)))
4569 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004570 QualType VType = LastIteration.get()->getType();
4571 QualType RealVType = VType;
4572 QualType StrideVType = VType;
4573 if (isOpenMPTaskLoopDirective(DKind)) {
4574 VType =
4575 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4576 StrideVType =
4577 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4578 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004579
4580 if (!LastIteration.isUsable())
4581 return 0;
4582
4583 // Save the number of iterations.
4584 ExprResult NumIterations = LastIteration;
4585 {
4586 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004587 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4588 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004589 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4590 if (!LastIteration.isUsable())
4591 return 0;
4592 }
4593
4594 // Calculate the last iteration number beforehand instead of doing this on
4595 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4596 llvm::APSInt Result;
4597 bool IsConstant =
4598 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4599 ExprResult CalcLastIteration;
4600 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004601 ExprResult SaveRef =
4602 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004603 LastIteration = SaveRef;
4604
4605 // Prepare SaveRef + 1.
4606 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004607 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004608 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4609 if (!NumIterations.isUsable())
4610 return 0;
4611 }
4612
4613 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4614
David Majnemer9d168222016-08-05 17:44:54 +00004615 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004616 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004617 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4618 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004619 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004620 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4621 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004622 SemaRef.AddInitializerToDecl(LBDecl,
4623 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4624 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004625
4626 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004627 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4628 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004629 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004630 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004631
4632 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4633 // This will be used to implement clause 'lastprivate'.
4634 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004635 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4636 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004637 SemaRef.AddInitializerToDecl(ILDecl,
4638 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4639 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004640
4641 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004642 VarDecl *STDecl =
4643 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4644 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004645 SemaRef.AddInitializerToDecl(STDecl,
4646 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4647 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004648
4649 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004650 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004651 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4652 UB.get(), LastIteration.get());
4653 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4654 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4655 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4656 CondOp.get());
4657 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004658
4659 // If we have a combined directive that combines 'distribute', 'for' or
4660 // 'simd' we need to be able to access the bounds of the schedule of the
4661 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4662 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4663 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004664
Carlo Bertolliffafe102017-04-20 00:39:39 +00004665 // Lower bound variable, initialized with zero.
4666 VarDecl *CombLBDecl =
4667 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4668 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4669 SemaRef.AddInitializerToDecl(
4670 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4671 /*DirectInit*/ false);
4672
4673 // Upper bound variable, initialized with last iteration number.
4674 VarDecl *CombUBDecl =
4675 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4676 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4677 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4678 /*DirectInit*/ false);
4679
4680 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4681 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4682 ExprResult CombCondOp =
4683 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4684 LastIteration.get(), CombUB.get());
4685 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4686 CombCondOp.get());
4687 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4688
4689 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004690 // We expect to have at least 2 more parameters than the 'parallel'
4691 // directive does - the lower and upper bounds of the previous schedule.
4692 assert(CD->getNumParams() >= 4 &&
4693 "Unexpected number of parameters in loop combined directive");
4694
4695 // Set the proper type for the bounds given what we learned from the
4696 // enclosed loops.
4697 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4698 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4699
4700 // Previous lower and upper bounds are obtained from the region
4701 // parameters.
4702 PrevLB =
4703 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4704 PrevUB =
4705 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4706 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004707 }
4708
4709 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004710 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004711 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004712 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004713 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4714 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004715 Expr *RHS =
4716 (isOpenMPWorksharingDirective(DKind) ||
4717 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4718 ? LB.get()
4719 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004720 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4721 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004722
4723 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4724 Expr *CombRHS =
4725 (isOpenMPWorksharingDirective(DKind) ||
4726 isOpenMPTaskLoopDirective(DKind) ||
4727 isOpenMPDistributeDirective(DKind))
4728 ? CombLB.get()
4729 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4730 CombInit =
4731 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4732 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4733 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004734 }
4735
Alexander Musmanc6388682014-12-15 07:07:06 +00004736 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004737 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004738 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004739 (isOpenMPWorksharingDirective(DKind) ||
4740 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004741 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4742 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4743 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004744 ExprResult CombCond;
4745 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4746 CombCond =
4747 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4748 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004749 // Loop increment (IV = IV + 1)
4750 SourceLocation IncLoc;
4751 ExprResult Inc =
4752 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4753 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4754 if (!Inc.isUsable())
4755 return 0;
4756 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004757 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4758 if (!Inc.isUsable())
4759 return 0;
4760
4761 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4762 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004763 // In combined construct, add combined version that use CombLB and CombUB
4764 // base variables for the update
4765 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004766 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4767 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004768 // LB + ST
4769 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4770 if (!NextLB.isUsable())
4771 return 0;
4772 // LB = LB + ST
4773 NextLB =
4774 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4775 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4776 if (!NextLB.isUsable())
4777 return 0;
4778 // UB + ST
4779 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4780 if (!NextUB.isUsable())
4781 return 0;
4782 // UB = UB + ST
4783 NextUB =
4784 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4785 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4786 if (!NextUB.isUsable())
4787 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004788 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4789 CombNextLB =
4790 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4791 if (!NextLB.isUsable())
4792 return 0;
4793 // LB = LB + ST
4794 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4795 CombNextLB.get());
4796 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4797 if (!CombNextLB.isUsable())
4798 return 0;
4799 // UB + ST
4800 CombNextUB =
4801 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4802 if (!CombNextUB.isUsable())
4803 return 0;
4804 // UB = UB + ST
4805 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4806 CombNextUB.get());
4807 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4808 if (!CombNextUB.isUsable())
4809 return 0;
4810 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004811 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004812
Carlo Bertolliffafe102017-04-20 00:39:39 +00004813 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004814 // directive with for as IV = IV + ST; ensure upper bound expression based
4815 // on PrevUB instead of NumIterations - used to implement 'for' when found
4816 // in combination with 'distribute', like in 'distribute parallel for'
4817 SourceLocation DistIncLoc;
4818 ExprResult DistCond, DistInc, PrevEUB;
4819 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4820 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4821 assert(DistCond.isUsable() && "distribute cond expr was not built");
4822
4823 DistInc =
4824 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4825 assert(DistInc.isUsable() && "distribute inc expr was not built");
4826 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4827 DistInc.get());
4828 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4829 assert(DistInc.isUsable() && "distribute inc expr was not built");
4830
4831 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4832 // construct
4833 SourceLocation DistEUBLoc;
4834 ExprResult IsUBGreater =
4835 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4836 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4837 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4838 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4839 CondOp.get());
4840 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4841 }
4842
Alexander Musmana5f070a2014-10-01 06:03:56 +00004843 // Build updates and final values of the loop counters.
4844 bool HasErrors = false;
4845 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004846 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004847 Built.Updates.resize(NestedLoopCount);
4848 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004849 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004850 {
4851 ExprResult Div;
4852 // Go from inner nested loop to outer.
4853 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4854 LoopIterationSpace &IS = IterSpaces[Cnt];
4855 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4856 // Build: Iter = (IV / Div) % IS.NumIters
4857 // where Div is product of previous iterations' IS.NumIters.
4858 ExprResult Iter;
4859 if (Div.isUsable()) {
4860 Iter =
4861 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4862 } else {
4863 Iter = IV;
4864 assert((Cnt == (int)NestedLoopCount - 1) &&
4865 "unusable div expected on first iteration only");
4866 }
4867
4868 if (Cnt != 0 && Iter.isUsable())
4869 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4870 IS.NumIterations);
4871 if (!Iter.isUsable()) {
4872 HasErrors = true;
4873 break;
4874 }
4875
Alexey Bataev39f915b82015-05-08 10:41:21 +00004876 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004877 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4878 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4879 IS.CounterVar->getExprLoc(),
4880 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004881 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004882 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004883 if (!Init.isUsable()) {
4884 HasErrors = true;
4885 break;
4886 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004887 ExprResult Update = BuildCounterUpdate(
4888 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4889 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004890 if (!Update.isUsable()) {
4891 HasErrors = true;
4892 break;
4893 }
4894
4895 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4896 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004897 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004898 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004899 if (!Final.isUsable()) {
4900 HasErrors = true;
4901 break;
4902 }
4903
4904 // Build Div for the next iteration: Div <- Div * IS.NumIters
4905 if (Cnt != 0) {
4906 if (Div.isUnset())
4907 Div = IS.NumIterations;
4908 else
4909 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4910 IS.NumIterations);
4911
4912 // Add parentheses (for debugging purposes only).
4913 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004914 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004915 if (!Div.isUsable()) {
4916 HasErrors = true;
4917 break;
4918 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004919 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004920 }
4921 if (!Update.isUsable() || !Final.isUsable()) {
4922 HasErrors = true;
4923 break;
4924 }
4925 // Save results
4926 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004927 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004928 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004929 Built.Updates[Cnt] = Update.get();
4930 Built.Finals[Cnt] = Final.get();
4931 }
4932 }
4933
4934 if (HasErrors)
4935 return 0;
4936
4937 // Save results
4938 Built.IterationVarRef = IV.get();
4939 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004940 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004941 Built.CalcLastIteration =
4942 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004943 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004944 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004945 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004946 Built.Init = Init.get();
4947 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004948 Built.LB = LB.get();
4949 Built.UB = UB.get();
4950 Built.IL = IL.get();
4951 Built.ST = ST.get();
4952 Built.EUB = EUB.get();
4953 Built.NLB = NextLB.get();
4954 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004955 Built.PrevLB = PrevLB.get();
4956 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004957 Built.DistInc = DistInc.get();
4958 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004959 Built.DistCombinedFields.LB = CombLB.get();
4960 Built.DistCombinedFields.UB = CombUB.get();
4961 Built.DistCombinedFields.EUB = CombEUB.get();
4962 Built.DistCombinedFields.Init = CombInit.get();
4963 Built.DistCombinedFields.Cond = CombCond.get();
4964 Built.DistCombinedFields.NLB = CombNextLB.get();
4965 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004966
Alexey Bataev8b427062016-05-25 12:36:08 +00004967 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4968 // Fill data for doacross depend clauses.
4969 for (auto Pair : DSA.getDoacrossDependClauses()) {
4970 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4971 Pair.first->setCounterValue(CounterVal);
4972 else {
4973 if (NestedLoopCount != Pair.second.size() ||
4974 NestedLoopCount != LoopMultipliers.size() + 1) {
4975 // Erroneous case - clause has some problems.
4976 Pair.first->setCounterValue(CounterVal);
4977 continue;
4978 }
4979 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4980 auto I = Pair.second.rbegin();
4981 auto IS = IterSpaces.rbegin();
4982 auto ILM = LoopMultipliers.rbegin();
4983 Expr *UpCounterVal = CounterVal;
4984 Expr *Multiplier = nullptr;
4985 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4986 if (I->first) {
4987 assert(IS->CounterStep);
4988 Expr *NormalizedOffset =
4989 SemaRef
4990 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4991 I->first, IS->CounterStep)
4992 .get();
4993 if (Multiplier) {
4994 NormalizedOffset =
4995 SemaRef
4996 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4997 NormalizedOffset, Multiplier)
4998 .get();
4999 }
5000 assert(I->second == OO_Plus || I->second == OO_Minus);
5001 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005002 UpCounterVal = SemaRef
5003 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5004 UpCounterVal, NormalizedOffset)
5005 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005006 }
5007 Multiplier = *ILM;
5008 ++I;
5009 ++IS;
5010 ++ILM;
5011 }
5012 Pair.first->setCounterValue(UpCounterVal);
5013 }
5014 }
5015
Alexey Bataevabfc0692014-06-25 06:52:00 +00005016 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005017}
5018
Alexey Bataev10e775f2015-07-30 11:36:16 +00005019static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005020 auto CollapseClauses =
5021 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5022 if (CollapseClauses.begin() != CollapseClauses.end())
5023 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005024 return nullptr;
5025}
5026
Alexey Bataev10e775f2015-07-30 11:36:16 +00005027static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005028 auto OrderedClauses =
5029 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5030 if (OrderedClauses.begin() != OrderedClauses.end())
5031 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005032 return nullptr;
5033}
5034
Kelvin Lic5609492016-07-15 04:39:07 +00005035static bool checkSimdlenSafelenSpecified(Sema &S,
5036 const ArrayRef<OMPClause *> Clauses) {
5037 OMPSafelenClause *Safelen = nullptr;
5038 OMPSimdlenClause *Simdlen = nullptr;
5039
5040 for (auto *Clause : Clauses) {
5041 if (Clause->getClauseKind() == OMPC_safelen)
5042 Safelen = cast<OMPSafelenClause>(Clause);
5043 else if (Clause->getClauseKind() == OMPC_simdlen)
5044 Simdlen = cast<OMPSimdlenClause>(Clause);
5045 if (Safelen && Simdlen)
5046 break;
5047 }
5048
5049 if (Simdlen && Safelen) {
5050 llvm::APSInt SimdlenRes, SafelenRes;
5051 auto SimdlenLength = Simdlen->getSimdlen();
5052 auto SafelenLength = Safelen->getSafelen();
5053 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5054 SimdlenLength->isInstantiationDependent() ||
5055 SimdlenLength->containsUnexpandedParameterPack())
5056 return false;
5057 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5058 SafelenLength->isInstantiationDependent() ||
5059 SafelenLength->containsUnexpandedParameterPack())
5060 return false;
5061 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5062 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5063 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5064 // If both simdlen and safelen clauses are specified, the value of the
5065 // simdlen parameter must be less than or equal to the value of the safelen
5066 // parameter.
5067 if (SimdlenRes > SafelenRes) {
5068 S.Diag(SimdlenLength->getExprLoc(),
5069 diag::err_omp_wrong_simdlen_safelen_values)
5070 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5071 return true;
5072 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005073 }
5074 return false;
5075}
5076
Alexey Bataev4acb8592014-07-07 13:01:15 +00005077StmtResult Sema::ActOnOpenMPSimdDirective(
5078 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5079 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005080 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005081 if (!AStmt)
5082 return StmtError();
5083
5084 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005085 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005086 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5087 // define the nested loops number.
5088 unsigned NestedLoopCount = CheckOpenMPLoop(
5089 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5090 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005091 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005092 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005093
Alexander Musmana5f070a2014-10-01 06:03:56 +00005094 assert((CurContext->isDependentContext() || B.builtAll()) &&
5095 "omp simd loop exprs were not built");
5096
Alexander Musman3276a272015-03-21 10:12:56 +00005097 if (!CurContext->isDependentContext()) {
5098 // Finalize the clauses that need pre-built expressions for CodeGen.
5099 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005100 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005101 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005102 B.NumIterations, *this, CurScope,
5103 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005104 return StmtError();
5105 }
5106 }
5107
Kelvin Lic5609492016-07-15 04:39:07 +00005108 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005109 return StmtError();
5110
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005111 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005112 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5113 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005114}
5115
Alexey Bataev4acb8592014-07-07 13:01:15 +00005116StmtResult Sema::ActOnOpenMPForDirective(
5117 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5118 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005119 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005120 if (!AStmt)
5121 return StmtError();
5122
5123 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005124 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005125 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5126 // define the nested loops number.
5127 unsigned NestedLoopCount = CheckOpenMPLoop(
5128 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5129 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005130 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005131 return StmtError();
5132
Alexander Musmana5f070a2014-10-01 06:03:56 +00005133 assert((CurContext->isDependentContext() || B.builtAll()) &&
5134 "omp for loop exprs were not built");
5135
Alexey Bataev54acd402015-08-04 11:18:19 +00005136 if (!CurContext->isDependentContext()) {
5137 // Finalize the clauses that need pre-built expressions for CodeGen.
5138 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005139 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005140 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005141 B.NumIterations, *this, CurScope,
5142 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005143 return StmtError();
5144 }
5145 }
5146
Alexey Bataevf29276e2014-06-18 04:14:57 +00005147 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005148 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005149 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005150}
5151
Alexander Musmanf82886e2014-09-18 05:12:34 +00005152StmtResult Sema::ActOnOpenMPForSimdDirective(
5153 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5154 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005155 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005156 if (!AStmt)
5157 return StmtError();
5158
5159 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005160 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005161 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5162 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005163 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005164 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5165 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5166 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005167 if (NestedLoopCount == 0)
5168 return StmtError();
5169
Alexander Musmanc6388682014-12-15 07:07:06 +00005170 assert((CurContext->isDependentContext() || B.builtAll()) &&
5171 "omp for simd loop exprs were not built");
5172
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005173 if (!CurContext->isDependentContext()) {
5174 // Finalize the clauses that need pre-built expressions for CodeGen.
5175 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005176 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005177 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005178 B.NumIterations, *this, CurScope,
5179 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005180 return StmtError();
5181 }
5182 }
5183
Kelvin Lic5609492016-07-15 04:39:07 +00005184 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005185 return StmtError();
5186
Alexander Musmanf82886e2014-09-18 05:12:34 +00005187 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005188 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5189 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005190}
5191
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005192StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5193 Stmt *AStmt,
5194 SourceLocation StartLoc,
5195 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005196 if (!AStmt)
5197 return StmtError();
5198
5199 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005200 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005201 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005202 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005203 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005204 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005205 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005206 return StmtError();
5207 // All associated statements must be '#pragma omp section' except for
5208 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005209 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005210 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5211 if (SectionStmt)
5212 Diag(SectionStmt->getLocStart(),
5213 diag::err_omp_sections_substmt_not_section);
5214 return StmtError();
5215 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005216 cast<OMPSectionDirective>(SectionStmt)
5217 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005218 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005219 } else {
5220 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5221 return StmtError();
5222 }
5223
5224 getCurFunction()->setHasBranchProtectedScope();
5225
Alexey Bataev25e5b442015-09-15 12:52:43 +00005226 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5227 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005228}
5229
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005230StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5231 SourceLocation StartLoc,
5232 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005233 if (!AStmt)
5234 return StmtError();
5235
5236 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005237
5238 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005239 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005240
Alexey Bataev25e5b442015-09-15 12:52:43 +00005241 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5242 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005243}
5244
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005245StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5246 Stmt *AStmt,
5247 SourceLocation StartLoc,
5248 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005249 if (!AStmt)
5250 return StmtError();
5251
5252 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005253
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005254 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005255
Alexey Bataev3255bf32015-01-19 05:20:46 +00005256 // OpenMP [2.7.3, single Construct, Restrictions]
5257 // The copyprivate clause must not be used with the nowait clause.
5258 OMPClause *Nowait = nullptr;
5259 OMPClause *Copyprivate = nullptr;
5260 for (auto *Clause : Clauses) {
5261 if (Clause->getClauseKind() == OMPC_nowait)
5262 Nowait = Clause;
5263 else if (Clause->getClauseKind() == OMPC_copyprivate)
5264 Copyprivate = Clause;
5265 if (Copyprivate && Nowait) {
5266 Diag(Copyprivate->getLocStart(),
5267 diag::err_omp_single_copyprivate_with_nowait);
5268 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5269 return StmtError();
5270 }
5271 }
5272
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005273 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5274}
5275
Alexander Musman80c22892014-07-17 08:54:58 +00005276StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5277 SourceLocation StartLoc,
5278 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005279 if (!AStmt)
5280 return StmtError();
5281
5282 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005283
5284 getCurFunction()->setHasBranchProtectedScope();
5285
5286 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5287}
5288
Alexey Bataev28c75412015-12-15 08:19:24 +00005289StmtResult Sema::ActOnOpenMPCriticalDirective(
5290 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5291 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005292 if (!AStmt)
5293 return StmtError();
5294
5295 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005296
Alexey Bataev28c75412015-12-15 08:19:24 +00005297 bool ErrorFound = false;
5298 llvm::APSInt Hint;
5299 SourceLocation HintLoc;
5300 bool DependentHint = false;
5301 for (auto *C : Clauses) {
5302 if (C->getClauseKind() == OMPC_hint) {
5303 if (!DirName.getName()) {
5304 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5305 ErrorFound = true;
5306 }
5307 Expr *E = cast<OMPHintClause>(C)->getHint();
5308 if (E->isTypeDependent() || E->isValueDependent() ||
5309 E->isInstantiationDependent())
5310 DependentHint = true;
5311 else {
5312 Hint = E->EvaluateKnownConstInt(Context);
5313 HintLoc = C->getLocStart();
5314 }
5315 }
5316 }
5317 if (ErrorFound)
5318 return StmtError();
5319 auto Pair = DSAStack->getCriticalWithHint(DirName);
5320 if (Pair.first && DirName.getName() && !DependentHint) {
5321 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5322 Diag(StartLoc, diag::err_omp_critical_with_hint);
5323 if (HintLoc.isValid()) {
5324 Diag(HintLoc, diag::note_omp_critical_hint_here)
5325 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5326 } else
5327 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5328 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5329 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5330 << 1
5331 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5332 /*Radix=*/10, /*Signed=*/false);
5333 } else
5334 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5335 }
5336 }
5337
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005338 getCurFunction()->setHasBranchProtectedScope();
5339
Alexey Bataev28c75412015-12-15 08:19:24 +00005340 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5341 Clauses, AStmt);
5342 if (!Pair.first && DirName.getName() && !DependentHint)
5343 DSAStack->addCriticalWithHint(Dir, Hint);
5344 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005345}
5346
Alexey Bataev4acb8592014-07-07 13:01:15 +00005347StmtResult Sema::ActOnOpenMPParallelForDirective(
5348 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5349 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005350 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005351 if (!AStmt)
5352 return StmtError();
5353
Alexey Bataev4acb8592014-07-07 13:01:15 +00005354 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5355 // 1.2.2 OpenMP Language Terminology
5356 // Structured block - An executable statement with a single entry at the
5357 // top and a single exit at the bottom.
5358 // The point of exit cannot be a branch out of the structured block.
5359 // longjmp() and throw() must not violate the entry/exit criteria.
5360 CS->getCapturedDecl()->setNothrow();
5361
Alexander Musmanc6388682014-12-15 07:07:06 +00005362 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005363 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5364 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005365 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005366 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5367 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5368 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005369 if (NestedLoopCount == 0)
5370 return StmtError();
5371
Alexander Musmana5f070a2014-10-01 06:03:56 +00005372 assert((CurContext->isDependentContext() || B.builtAll()) &&
5373 "omp parallel for loop exprs were not built");
5374
Alexey Bataev54acd402015-08-04 11:18:19 +00005375 if (!CurContext->isDependentContext()) {
5376 // Finalize the clauses that need pre-built expressions for CodeGen.
5377 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005378 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005379 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005380 B.NumIterations, *this, CurScope,
5381 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005382 return StmtError();
5383 }
5384 }
5385
Alexey Bataev4acb8592014-07-07 13:01:15 +00005386 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005387 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005388 NestedLoopCount, Clauses, AStmt, B,
5389 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005390}
5391
Alexander Musmane4e893b2014-09-23 09:33:00 +00005392StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5393 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5394 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005395 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005396 if (!AStmt)
5397 return StmtError();
5398
Alexander Musmane4e893b2014-09-23 09:33:00 +00005399 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5400 // 1.2.2 OpenMP Language Terminology
5401 // Structured block - An executable statement with a single entry at the
5402 // top and a single exit at the bottom.
5403 // The point of exit cannot be a branch out of the structured block.
5404 // longjmp() and throw() must not violate the entry/exit criteria.
5405 CS->getCapturedDecl()->setNothrow();
5406
Alexander Musmanc6388682014-12-15 07:07:06 +00005407 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005408 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5409 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005410 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005411 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5412 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5413 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005414 if (NestedLoopCount == 0)
5415 return StmtError();
5416
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005417 if (!CurContext->isDependentContext()) {
5418 // Finalize the clauses that need pre-built expressions for CodeGen.
5419 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005420 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005421 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005422 B.NumIterations, *this, CurScope,
5423 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005424 return StmtError();
5425 }
5426 }
5427
Kelvin Lic5609492016-07-15 04:39:07 +00005428 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005429 return StmtError();
5430
Alexander Musmane4e893b2014-09-23 09:33:00 +00005431 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005432 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005433 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005434}
5435
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005436StmtResult
5437Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5438 Stmt *AStmt, SourceLocation StartLoc,
5439 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005440 if (!AStmt)
5441 return StmtError();
5442
5443 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005444 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005445 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005446 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005447 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005448 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005449 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005450 return StmtError();
5451 // All associated statements must be '#pragma omp section' except for
5452 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005453 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005454 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5455 if (SectionStmt)
5456 Diag(SectionStmt->getLocStart(),
5457 diag::err_omp_parallel_sections_substmt_not_section);
5458 return StmtError();
5459 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005460 cast<OMPSectionDirective>(SectionStmt)
5461 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005462 }
5463 } else {
5464 Diag(AStmt->getLocStart(),
5465 diag::err_omp_parallel_sections_not_compound_stmt);
5466 return StmtError();
5467 }
5468
5469 getCurFunction()->setHasBranchProtectedScope();
5470
Alexey Bataev25e5b442015-09-15 12:52:43 +00005471 return OMPParallelSectionsDirective::Create(
5472 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005473}
5474
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005475StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5476 Stmt *AStmt, SourceLocation StartLoc,
5477 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005478 if (!AStmt)
5479 return StmtError();
5480
David Majnemer9d168222016-08-05 17:44:54 +00005481 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005482 // 1.2.2 OpenMP Language Terminology
5483 // Structured block - An executable statement with a single entry at the
5484 // top and a single exit at the bottom.
5485 // The point of exit cannot be a branch out of the structured block.
5486 // longjmp() and throw() must not violate the entry/exit criteria.
5487 CS->getCapturedDecl()->setNothrow();
5488
5489 getCurFunction()->setHasBranchProtectedScope();
5490
Alexey Bataev25e5b442015-09-15 12:52:43 +00005491 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5492 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005493}
5494
Alexey Bataev68446b72014-07-18 07:47:19 +00005495StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5496 SourceLocation EndLoc) {
5497 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5498}
5499
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005500StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5501 SourceLocation EndLoc) {
5502 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5503}
5504
Alexey Bataev2df347a2014-07-18 10:17:07 +00005505StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5506 SourceLocation EndLoc) {
5507 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5508}
5509
Alexey Bataev169d96a2017-07-18 20:17:46 +00005510StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5511 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005512 SourceLocation StartLoc,
5513 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005514 if (!AStmt)
5515 return StmtError();
5516
5517 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005518
5519 getCurFunction()->setHasBranchProtectedScope();
5520
Alexey Bataev169d96a2017-07-18 20:17:46 +00005521 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005522 AStmt,
5523 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005524}
5525
Alexey Bataev6125da92014-07-21 11:26:11 +00005526StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5527 SourceLocation StartLoc,
5528 SourceLocation EndLoc) {
5529 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5530 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5531}
5532
Alexey Bataev346265e2015-09-25 10:37:12 +00005533StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5534 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005535 SourceLocation StartLoc,
5536 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005537 OMPClause *DependFound = nullptr;
5538 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005539 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005540 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005541 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005542 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005543 for (auto *C : Clauses) {
5544 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5545 DependFound = C;
5546 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5547 if (DependSourceClause) {
5548 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5549 << getOpenMPDirectiveName(OMPD_ordered)
5550 << getOpenMPClauseName(OMPC_depend) << 2;
5551 ErrorFound = true;
5552 } else
5553 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005554 if (DependSinkClause) {
5555 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5556 << 0;
5557 ErrorFound = true;
5558 }
5559 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5560 if (DependSourceClause) {
5561 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5562 << 1;
5563 ErrorFound = true;
5564 }
5565 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005566 }
5567 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005568 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005569 else if (C->getClauseKind() == OMPC_simd)
5570 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005571 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005572 if (!ErrorFound && !SC &&
5573 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005574 // OpenMP [2.8.1,simd Construct, Restrictions]
5575 // An ordered construct with the simd clause is the only OpenMP construct
5576 // that can appear in the simd region.
5577 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005578 ErrorFound = true;
5579 } else if (DependFound && (TC || SC)) {
5580 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5581 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5582 ErrorFound = true;
5583 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5584 Diag(DependFound->getLocStart(),
5585 diag::err_omp_ordered_directive_without_param);
5586 ErrorFound = true;
5587 } else if (TC || Clauses.empty()) {
5588 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5589 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5590 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5591 << (TC != nullptr);
5592 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5593 ErrorFound = true;
5594 }
5595 }
5596 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005597 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005598
5599 if (AStmt) {
5600 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5601
5602 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005603 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005604
5605 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005606}
5607
Alexey Bataev1d160b12015-03-13 12:27:31 +00005608namespace {
5609/// \brief Helper class for checking expression in 'omp atomic [update]'
5610/// construct.
5611class OpenMPAtomicUpdateChecker {
5612 /// \brief Error results for atomic update expressions.
5613 enum ExprAnalysisErrorCode {
5614 /// \brief A statement is not an expression statement.
5615 NotAnExpression,
5616 /// \brief Expression is not builtin binary or unary operation.
5617 NotABinaryOrUnaryExpression,
5618 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5619 NotAnUnaryIncDecExpression,
5620 /// \brief An expression is not of scalar type.
5621 NotAScalarType,
5622 /// \brief A binary operation is not an assignment operation.
5623 NotAnAssignmentOp,
5624 /// \brief RHS part of the binary operation is not a binary expression.
5625 NotABinaryExpression,
5626 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5627 /// expression.
5628 NotABinaryOperator,
5629 /// \brief RHS binary operation does not have reference to the updated LHS
5630 /// part.
5631 NotAnUpdateExpression,
5632 /// \brief No errors is found.
5633 NoError
5634 };
5635 /// \brief Reference to Sema.
5636 Sema &SemaRef;
5637 /// \brief A location for note diagnostics (when error is found).
5638 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005639 /// \brief 'x' lvalue part of the source atomic expression.
5640 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005641 /// \brief 'expr' rvalue part of the source atomic expression.
5642 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005643 /// \brief Helper expression of the form
5644 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5645 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5646 Expr *UpdateExpr;
5647 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5648 /// important for non-associative operations.
5649 bool IsXLHSInRHSPart;
5650 BinaryOperatorKind Op;
5651 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005652 /// \brief true if the source expression is a postfix unary operation, false
5653 /// if it is a prefix unary operation.
5654 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005655
5656public:
5657 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005658 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005659 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005660 /// \brief Check specified statement that it is suitable for 'atomic update'
5661 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005662 /// expression. If DiagId and NoteId == 0, then only check is performed
5663 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005664 /// \param DiagId Diagnostic which should be emitted if error is found.
5665 /// \param NoteId Diagnostic note for the main error message.
5666 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005667 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005668 /// \brief Return the 'x' lvalue part of the source atomic expression.
5669 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005670 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5671 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005672 /// \brief Return the update expression used in calculation of the updated
5673 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5674 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5675 Expr *getUpdateExpr() const { return UpdateExpr; }
5676 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5677 /// false otherwise.
5678 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5679
Alexey Bataevb78ca832015-04-01 03:33:17 +00005680 /// \brief true if the source expression is a postfix unary operation, false
5681 /// if it is a prefix unary operation.
5682 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5683
Alexey Bataev1d160b12015-03-13 12:27:31 +00005684private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005685 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5686 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005687};
5688} // namespace
5689
5690bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5691 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5692 ExprAnalysisErrorCode ErrorFound = NoError;
5693 SourceLocation ErrorLoc, NoteLoc;
5694 SourceRange ErrorRange, NoteRange;
5695 // Allowed constructs are:
5696 // x = x binop expr;
5697 // x = expr binop x;
5698 if (AtomicBinOp->getOpcode() == BO_Assign) {
5699 X = AtomicBinOp->getLHS();
5700 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5701 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5702 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5703 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5704 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005705 Op = AtomicInnerBinOp->getOpcode();
5706 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005707 auto *LHS = AtomicInnerBinOp->getLHS();
5708 auto *RHS = AtomicInnerBinOp->getRHS();
5709 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5710 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5711 /*Canonical=*/true);
5712 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5713 /*Canonical=*/true);
5714 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5715 /*Canonical=*/true);
5716 if (XId == LHSId) {
5717 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005718 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005719 } else if (XId == RHSId) {
5720 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005721 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005722 } else {
5723 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5724 ErrorRange = AtomicInnerBinOp->getSourceRange();
5725 NoteLoc = X->getExprLoc();
5726 NoteRange = X->getSourceRange();
5727 ErrorFound = NotAnUpdateExpression;
5728 }
5729 } else {
5730 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5731 ErrorRange = AtomicInnerBinOp->getSourceRange();
5732 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5733 NoteRange = SourceRange(NoteLoc, NoteLoc);
5734 ErrorFound = NotABinaryOperator;
5735 }
5736 } else {
5737 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5738 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5739 ErrorFound = NotABinaryExpression;
5740 }
5741 } else {
5742 ErrorLoc = AtomicBinOp->getExprLoc();
5743 ErrorRange = AtomicBinOp->getSourceRange();
5744 NoteLoc = AtomicBinOp->getOperatorLoc();
5745 NoteRange = SourceRange(NoteLoc, NoteLoc);
5746 ErrorFound = NotAnAssignmentOp;
5747 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005748 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005749 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5750 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5751 return true;
5752 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005753 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005754 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005755}
5756
5757bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5758 unsigned NoteId) {
5759 ExprAnalysisErrorCode ErrorFound = NoError;
5760 SourceLocation ErrorLoc, NoteLoc;
5761 SourceRange ErrorRange, NoteRange;
5762 // Allowed constructs are:
5763 // x++;
5764 // x--;
5765 // ++x;
5766 // --x;
5767 // x binop= expr;
5768 // x = x binop expr;
5769 // x = expr binop x;
5770 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5771 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5772 if (AtomicBody->getType()->isScalarType() ||
5773 AtomicBody->isInstantiationDependent()) {
5774 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5775 AtomicBody->IgnoreParenImpCasts())) {
5776 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005777 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005778 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005779 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005780 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005781 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005782 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005783 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5784 AtomicBody->IgnoreParenImpCasts())) {
5785 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005786 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005787 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005788 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5789 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005790 // Check for Unary Operation
5791 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005792 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005793 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5794 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005795 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005796 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5797 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005798 } else {
5799 ErrorFound = NotAnUnaryIncDecExpression;
5800 ErrorLoc = AtomicUnaryOp->getExprLoc();
5801 ErrorRange = AtomicUnaryOp->getSourceRange();
5802 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5803 NoteRange = SourceRange(NoteLoc, NoteLoc);
5804 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005805 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005806 ErrorFound = NotABinaryOrUnaryExpression;
5807 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5808 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5809 }
5810 } else {
5811 ErrorFound = NotAScalarType;
5812 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5813 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5814 }
5815 } else {
5816 ErrorFound = NotAnExpression;
5817 NoteLoc = ErrorLoc = S->getLocStart();
5818 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5819 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005820 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005821 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5822 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5823 return true;
5824 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005825 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005826 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005827 // Build an update expression of form 'OpaqueValueExpr(x) binop
5828 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5829 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5830 auto *OVEX = new (SemaRef.getASTContext())
5831 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5832 auto *OVEExpr = new (SemaRef.getASTContext())
5833 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5834 auto Update =
5835 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5836 IsXLHSInRHSPart ? OVEExpr : OVEX);
5837 if (Update.isInvalid())
5838 return true;
5839 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5840 Sema::AA_Casting);
5841 if (Update.isInvalid())
5842 return true;
5843 UpdateExpr = Update.get();
5844 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005845 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005846}
5847
Alexey Bataev0162e452014-07-22 10:10:35 +00005848StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5849 Stmt *AStmt,
5850 SourceLocation StartLoc,
5851 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005852 if (!AStmt)
5853 return StmtError();
5854
David Majnemer9d168222016-08-05 17:44:54 +00005855 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005856 // 1.2.2 OpenMP Language Terminology
5857 // Structured block - An executable statement with a single entry at the
5858 // top and a single exit at the bottom.
5859 // The point of exit cannot be a branch out of the structured block.
5860 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005861 OpenMPClauseKind AtomicKind = OMPC_unknown;
5862 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005863 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005864 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005865 C->getClauseKind() == OMPC_update ||
5866 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005867 if (AtomicKind != OMPC_unknown) {
5868 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5869 << SourceRange(C->getLocStart(), C->getLocEnd());
5870 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5871 << getOpenMPClauseName(AtomicKind);
5872 } else {
5873 AtomicKind = C->getClauseKind();
5874 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005875 }
5876 }
5877 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005878
Alexey Bataev459dec02014-07-24 06:46:57 +00005879 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005880 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5881 Body = EWC->getSubExpr();
5882
Alexey Bataev62cec442014-11-18 10:14:22 +00005883 Expr *X = nullptr;
5884 Expr *V = nullptr;
5885 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005886 Expr *UE = nullptr;
5887 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005888 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005889 // OpenMP [2.12.6, atomic Construct]
5890 // In the next expressions:
5891 // * x and v (as applicable) are both l-value expressions with scalar type.
5892 // * During the execution of an atomic region, multiple syntactic
5893 // occurrences of x must designate the same storage location.
5894 // * Neither of v and expr (as applicable) may access the storage location
5895 // designated by x.
5896 // * Neither of x and expr (as applicable) may access the storage location
5897 // designated by v.
5898 // * expr is an expression with scalar type.
5899 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5900 // * binop, binop=, ++, and -- are not overloaded operators.
5901 // * The expression x binop expr must be numerically equivalent to x binop
5902 // (expr). This requirement is satisfied if the operators in expr have
5903 // precedence greater than binop, or by using parentheses around expr or
5904 // subexpressions of expr.
5905 // * The expression expr binop x must be numerically equivalent to (expr)
5906 // binop x. This requirement is satisfied if the operators in expr have
5907 // precedence equal to or greater than binop, or by using parentheses around
5908 // expr or subexpressions of expr.
5909 // * For forms that allow multiple occurrences of x, the number of times
5910 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005911 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005912 enum {
5913 NotAnExpression,
5914 NotAnAssignmentOp,
5915 NotAScalarType,
5916 NotAnLValue,
5917 NoError
5918 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005919 SourceLocation ErrorLoc, NoteLoc;
5920 SourceRange ErrorRange, NoteRange;
5921 // If clause is read:
5922 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005923 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5924 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005925 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5926 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5927 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5928 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5929 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5930 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5931 if (!X->isLValue() || !V->isLValue()) {
5932 auto NotLValueExpr = X->isLValue() ? V : X;
5933 ErrorFound = NotAnLValue;
5934 ErrorLoc = AtomicBinOp->getExprLoc();
5935 ErrorRange = AtomicBinOp->getSourceRange();
5936 NoteLoc = NotLValueExpr->getExprLoc();
5937 NoteRange = NotLValueExpr->getSourceRange();
5938 }
5939 } else if (!X->isInstantiationDependent() ||
5940 !V->isInstantiationDependent()) {
5941 auto NotScalarExpr =
5942 (X->isInstantiationDependent() || X->getType()->isScalarType())
5943 ? V
5944 : X;
5945 ErrorFound = NotAScalarType;
5946 ErrorLoc = AtomicBinOp->getExprLoc();
5947 ErrorRange = AtomicBinOp->getSourceRange();
5948 NoteLoc = NotScalarExpr->getExprLoc();
5949 NoteRange = NotScalarExpr->getSourceRange();
5950 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005951 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005952 ErrorFound = NotAnAssignmentOp;
5953 ErrorLoc = AtomicBody->getExprLoc();
5954 ErrorRange = AtomicBody->getSourceRange();
5955 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5956 : AtomicBody->getExprLoc();
5957 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5958 : AtomicBody->getSourceRange();
5959 }
5960 } else {
5961 ErrorFound = NotAnExpression;
5962 NoteLoc = ErrorLoc = Body->getLocStart();
5963 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005964 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005965 if (ErrorFound != NoError) {
5966 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5967 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005968 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5969 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005970 return StmtError();
5971 } else if (CurContext->isDependentContext())
5972 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005973 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005974 enum {
5975 NotAnExpression,
5976 NotAnAssignmentOp,
5977 NotAScalarType,
5978 NotAnLValue,
5979 NoError
5980 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005981 SourceLocation ErrorLoc, NoteLoc;
5982 SourceRange ErrorRange, NoteRange;
5983 // If clause is write:
5984 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005985 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5986 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005987 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5988 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005989 X = AtomicBinOp->getLHS();
5990 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005991 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5992 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5993 if (!X->isLValue()) {
5994 ErrorFound = NotAnLValue;
5995 ErrorLoc = AtomicBinOp->getExprLoc();
5996 ErrorRange = AtomicBinOp->getSourceRange();
5997 NoteLoc = X->getExprLoc();
5998 NoteRange = X->getSourceRange();
5999 }
6000 } else if (!X->isInstantiationDependent() ||
6001 !E->isInstantiationDependent()) {
6002 auto NotScalarExpr =
6003 (X->isInstantiationDependent() || X->getType()->isScalarType())
6004 ? E
6005 : X;
6006 ErrorFound = NotAScalarType;
6007 ErrorLoc = AtomicBinOp->getExprLoc();
6008 ErrorRange = AtomicBinOp->getSourceRange();
6009 NoteLoc = NotScalarExpr->getExprLoc();
6010 NoteRange = NotScalarExpr->getSourceRange();
6011 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006012 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006013 ErrorFound = NotAnAssignmentOp;
6014 ErrorLoc = AtomicBody->getExprLoc();
6015 ErrorRange = AtomicBody->getSourceRange();
6016 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6017 : AtomicBody->getExprLoc();
6018 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6019 : AtomicBody->getSourceRange();
6020 }
6021 } else {
6022 ErrorFound = NotAnExpression;
6023 NoteLoc = ErrorLoc = Body->getLocStart();
6024 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006025 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006026 if (ErrorFound != NoError) {
6027 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6028 << ErrorRange;
6029 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6030 << NoteRange;
6031 return StmtError();
6032 } else if (CurContext->isDependentContext())
6033 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006034 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006035 // If clause is update:
6036 // x++;
6037 // x--;
6038 // ++x;
6039 // --x;
6040 // x binop= expr;
6041 // x = x binop expr;
6042 // x = expr binop x;
6043 OpenMPAtomicUpdateChecker Checker(*this);
6044 if (Checker.checkStatement(
6045 Body, (AtomicKind == OMPC_update)
6046 ? diag::err_omp_atomic_update_not_expression_statement
6047 : diag::err_omp_atomic_not_expression_statement,
6048 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006049 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006050 if (!CurContext->isDependentContext()) {
6051 E = Checker.getExpr();
6052 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006053 UE = Checker.getUpdateExpr();
6054 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006055 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006056 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006057 enum {
6058 NotAnAssignmentOp,
6059 NotACompoundStatement,
6060 NotTwoSubstatements,
6061 NotASpecificExpression,
6062 NoError
6063 } ErrorFound = NoError;
6064 SourceLocation ErrorLoc, NoteLoc;
6065 SourceRange ErrorRange, NoteRange;
6066 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6067 // If clause is a capture:
6068 // v = x++;
6069 // v = x--;
6070 // v = ++x;
6071 // v = --x;
6072 // v = x binop= expr;
6073 // v = x = x binop expr;
6074 // v = x = expr binop x;
6075 auto *AtomicBinOp =
6076 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6077 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6078 V = AtomicBinOp->getLHS();
6079 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6080 OpenMPAtomicUpdateChecker Checker(*this);
6081 if (Checker.checkStatement(
6082 Body, diag::err_omp_atomic_capture_not_expression_statement,
6083 diag::note_omp_atomic_update))
6084 return StmtError();
6085 E = Checker.getExpr();
6086 X = Checker.getX();
6087 UE = Checker.getUpdateExpr();
6088 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6089 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006090 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006091 ErrorLoc = AtomicBody->getExprLoc();
6092 ErrorRange = AtomicBody->getSourceRange();
6093 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6094 : AtomicBody->getExprLoc();
6095 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6096 : AtomicBody->getSourceRange();
6097 ErrorFound = NotAnAssignmentOp;
6098 }
6099 if (ErrorFound != NoError) {
6100 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6101 << ErrorRange;
6102 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6103 return StmtError();
6104 } else if (CurContext->isDependentContext()) {
6105 UE = V = E = X = nullptr;
6106 }
6107 } else {
6108 // If clause is a capture:
6109 // { v = x; x = expr; }
6110 // { v = x; x++; }
6111 // { v = x; x--; }
6112 // { v = x; ++x; }
6113 // { v = x; --x; }
6114 // { v = x; x binop= expr; }
6115 // { v = x; x = x binop expr; }
6116 // { v = x; x = expr binop x; }
6117 // { x++; v = x; }
6118 // { x--; v = x; }
6119 // { ++x; v = x; }
6120 // { --x; v = x; }
6121 // { x binop= expr; v = x; }
6122 // { x = x binop expr; v = x; }
6123 // { x = expr binop x; v = x; }
6124 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6125 // Check that this is { expr1; expr2; }
6126 if (CS->size() == 2) {
6127 auto *First = CS->body_front();
6128 auto *Second = CS->body_back();
6129 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6130 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6131 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6132 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6133 // Need to find what subexpression is 'v' and what is 'x'.
6134 OpenMPAtomicUpdateChecker Checker(*this);
6135 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6136 BinaryOperator *BinOp = nullptr;
6137 if (IsUpdateExprFound) {
6138 BinOp = dyn_cast<BinaryOperator>(First);
6139 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6140 }
6141 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6142 // { v = x; x++; }
6143 // { v = x; x--; }
6144 // { v = x; ++x; }
6145 // { v = x; --x; }
6146 // { v = x; x binop= expr; }
6147 // { v = x; x = x binop expr; }
6148 // { v = x; x = expr binop x; }
6149 // Check that the first expression has form v = x.
6150 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6151 llvm::FoldingSetNodeID XId, PossibleXId;
6152 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6153 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6154 IsUpdateExprFound = XId == PossibleXId;
6155 if (IsUpdateExprFound) {
6156 V = BinOp->getLHS();
6157 X = Checker.getX();
6158 E = Checker.getExpr();
6159 UE = Checker.getUpdateExpr();
6160 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006161 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006162 }
6163 }
6164 if (!IsUpdateExprFound) {
6165 IsUpdateExprFound = !Checker.checkStatement(First);
6166 BinOp = nullptr;
6167 if (IsUpdateExprFound) {
6168 BinOp = dyn_cast<BinaryOperator>(Second);
6169 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6170 }
6171 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6172 // { x++; v = x; }
6173 // { x--; v = x; }
6174 // { ++x; v = x; }
6175 // { --x; v = x; }
6176 // { x binop= expr; v = x; }
6177 // { x = x binop expr; v = x; }
6178 // { x = expr binop x; v = x; }
6179 // Check that the second expression has form v = x.
6180 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6181 llvm::FoldingSetNodeID XId, PossibleXId;
6182 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6183 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6184 IsUpdateExprFound = XId == PossibleXId;
6185 if (IsUpdateExprFound) {
6186 V = BinOp->getLHS();
6187 X = Checker.getX();
6188 E = Checker.getExpr();
6189 UE = Checker.getUpdateExpr();
6190 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006191 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006192 }
6193 }
6194 }
6195 if (!IsUpdateExprFound) {
6196 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006197 auto *FirstExpr = dyn_cast<Expr>(First);
6198 auto *SecondExpr = dyn_cast<Expr>(Second);
6199 if (!FirstExpr || !SecondExpr ||
6200 !(FirstExpr->isInstantiationDependent() ||
6201 SecondExpr->isInstantiationDependent())) {
6202 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6203 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006204 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006205 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6206 : First->getLocStart();
6207 NoteRange = ErrorRange = FirstBinOp
6208 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006209 : SourceRange(ErrorLoc, ErrorLoc);
6210 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006211 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6212 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6213 ErrorFound = NotAnAssignmentOp;
6214 NoteLoc = ErrorLoc = SecondBinOp
6215 ? SecondBinOp->getOperatorLoc()
6216 : Second->getLocStart();
6217 NoteRange = ErrorRange =
6218 SecondBinOp ? SecondBinOp->getSourceRange()
6219 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006220 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006221 auto *PossibleXRHSInFirst =
6222 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6223 auto *PossibleXLHSInSecond =
6224 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6225 llvm::FoldingSetNodeID X1Id, X2Id;
6226 PossibleXRHSInFirst->Profile(X1Id, Context,
6227 /*Canonical=*/true);
6228 PossibleXLHSInSecond->Profile(X2Id, Context,
6229 /*Canonical=*/true);
6230 IsUpdateExprFound = X1Id == X2Id;
6231 if (IsUpdateExprFound) {
6232 V = FirstBinOp->getLHS();
6233 X = SecondBinOp->getLHS();
6234 E = SecondBinOp->getRHS();
6235 UE = nullptr;
6236 IsXLHSInRHSPart = false;
6237 IsPostfixUpdate = true;
6238 } else {
6239 ErrorFound = NotASpecificExpression;
6240 ErrorLoc = FirstBinOp->getExprLoc();
6241 ErrorRange = FirstBinOp->getSourceRange();
6242 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6243 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6244 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006245 }
6246 }
6247 }
6248 }
6249 } else {
6250 NoteLoc = ErrorLoc = Body->getLocStart();
6251 NoteRange = ErrorRange =
6252 SourceRange(Body->getLocStart(), Body->getLocStart());
6253 ErrorFound = NotTwoSubstatements;
6254 }
6255 } else {
6256 NoteLoc = ErrorLoc = Body->getLocStart();
6257 NoteRange = ErrorRange =
6258 SourceRange(Body->getLocStart(), Body->getLocStart());
6259 ErrorFound = NotACompoundStatement;
6260 }
6261 if (ErrorFound != NoError) {
6262 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6263 << ErrorRange;
6264 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6265 return StmtError();
6266 } else if (CurContext->isDependentContext()) {
6267 UE = V = E = X = nullptr;
6268 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006269 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006270 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006271
6272 getCurFunction()->setHasBranchProtectedScope();
6273
Alexey Bataev62cec442014-11-18 10:14:22 +00006274 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006275 X, V, E, UE, IsXLHSInRHSPart,
6276 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006277}
6278
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006279StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6280 Stmt *AStmt,
6281 SourceLocation StartLoc,
6282 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006283 if (!AStmt)
6284 return StmtError();
6285
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006286 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6287 // 1.2.2 OpenMP Language Terminology
6288 // Structured block - An executable statement with a single entry at the
6289 // top and a single exit at the bottom.
6290 // The point of exit cannot be a branch out of the structured block.
6291 // longjmp() and throw() must not violate the entry/exit criteria.
6292 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006293
Alexey Bataev13314bf2014-10-09 04:18:56 +00006294 // OpenMP [2.16, Nesting of Regions]
6295 // If specified, a teams construct must be contained within a target
6296 // construct. That target construct must contain no statements or directives
6297 // outside of the teams construct.
6298 if (DSAStack->hasInnerTeamsRegion()) {
6299 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6300 bool OMPTeamsFound = true;
6301 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6302 auto I = CS->body_begin();
6303 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006304 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006305 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6306 OMPTeamsFound = false;
6307 break;
6308 }
6309 ++I;
6310 }
6311 assert(I != CS->body_end() && "Not found statement");
6312 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006313 } else {
6314 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6315 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006316 }
6317 if (!OMPTeamsFound) {
6318 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6319 Diag(DSAStack->getInnerTeamsRegionLoc(),
6320 diag::note_omp_nested_teams_construct_here);
6321 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6322 << isa<OMPExecutableDirective>(S);
6323 return StmtError();
6324 }
6325 }
6326
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006327 getCurFunction()->setHasBranchProtectedScope();
6328
6329 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6330}
6331
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006332StmtResult
6333Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6334 Stmt *AStmt, SourceLocation StartLoc,
6335 SourceLocation EndLoc) {
6336 if (!AStmt)
6337 return StmtError();
6338
6339 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6340 // 1.2.2 OpenMP Language Terminology
6341 // Structured block - An executable statement with a single entry at the
6342 // top and a single exit at the bottom.
6343 // The point of exit cannot be a branch out of the structured block.
6344 // longjmp() and throw() must not violate the entry/exit criteria.
6345 CS->getCapturedDecl()->setNothrow();
6346
6347 getCurFunction()->setHasBranchProtectedScope();
6348
6349 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6350 AStmt);
6351}
6352
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006353StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6354 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6355 SourceLocation EndLoc,
6356 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6357 if (!AStmt)
6358 return StmtError();
6359
6360 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6361 // 1.2.2 OpenMP Language Terminology
6362 // Structured block - An executable statement with a single entry at the
6363 // top and a single exit at the bottom.
6364 // The point of exit cannot be a branch out of the structured block.
6365 // longjmp() and throw() must not violate the entry/exit criteria.
6366 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006367 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6368 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6369 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6370 // 1.2.2 OpenMP Language Terminology
6371 // Structured block - An executable statement with a single entry at the
6372 // top and a single exit at the bottom.
6373 // The point of exit cannot be a branch out of the structured block.
6374 // longjmp() and throw() must not violate the entry/exit criteria.
6375 CS->getCapturedDecl()->setNothrow();
6376 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006377
6378 OMPLoopDirective::HelperExprs B;
6379 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6380 // define the nested loops number.
6381 unsigned NestedLoopCount =
6382 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006383 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006384 VarsWithImplicitDSA, B);
6385 if (NestedLoopCount == 0)
6386 return StmtError();
6387
6388 assert((CurContext->isDependentContext() || B.builtAll()) &&
6389 "omp target parallel for loop exprs were not built");
6390
6391 if (!CurContext->isDependentContext()) {
6392 // Finalize the clauses that need pre-built expressions for CodeGen.
6393 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006394 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006395 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006396 B.NumIterations, *this, CurScope,
6397 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006398 return StmtError();
6399 }
6400 }
6401
6402 getCurFunction()->setHasBranchProtectedScope();
6403 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6404 NestedLoopCount, Clauses, AStmt,
6405 B, DSAStack->isCancelRegion());
6406}
6407
Alexey Bataev95b64a92017-05-30 16:00:04 +00006408/// Check for existence of a map clause in the list of clauses.
6409static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6410 const OpenMPClauseKind K) {
6411 return llvm::any_of(
6412 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6413}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006414
Alexey Bataev95b64a92017-05-30 16:00:04 +00006415template <typename... Params>
6416static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6417 const Params... ClauseTypes) {
6418 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006419}
6420
Michael Wong65f367f2015-07-21 13:44:28 +00006421StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6422 Stmt *AStmt,
6423 SourceLocation StartLoc,
6424 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006425 if (!AStmt)
6426 return StmtError();
6427
6428 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6429
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006430 // OpenMP [2.10.1, Restrictions, p. 97]
6431 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006432 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6433 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6434 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006435 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006436 return StmtError();
6437 }
6438
Michael Wong65f367f2015-07-21 13:44:28 +00006439 getCurFunction()->setHasBranchProtectedScope();
6440
6441 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6442 AStmt);
6443}
6444
Samuel Antaodf67fc42016-01-19 19:15:56 +00006445StmtResult
6446Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6447 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006448 SourceLocation EndLoc, Stmt *AStmt) {
6449 if (!AStmt)
6450 return StmtError();
6451
6452 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6453 // 1.2.2 OpenMP Language Terminology
6454 // Structured block - An executable statement with a single entry at the
6455 // top and a single exit at the bottom.
6456 // The point of exit cannot be a branch out of the structured block.
6457 // longjmp() and throw() must not violate the entry/exit criteria.
6458 CS->getCapturedDecl()->setNothrow();
6459 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6460 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6461 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6462 // 1.2.2 OpenMP Language Terminology
6463 // Structured block - An executable statement with a single entry at the
6464 // top and a single exit at the bottom.
6465 // The point of exit cannot be a branch out of the structured block.
6466 // longjmp() and throw() must not violate the entry/exit criteria.
6467 CS->getCapturedDecl()->setNothrow();
6468 }
6469
Samuel Antaodf67fc42016-01-19 19:15:56 +00006470 // OpenMP [2.10.2, Restrictions, p. 99]
6471 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006472 if (!hasClauses(Clauses, OMPC_map)) {
6473 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6474 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006475 return StmtError();
6476 }
6477
Alexey Bataev7828b252017-11-21 17:08:48 +00006478 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6479 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006480}
6481
Samuel Antao72590762016-01-19 20:04:50 +00006482StmtResult
6483Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6484 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006485 SourceLocation EndLoc, Stmt *AStmt) {
6486 if (!AStmt)
6487 return StmtError();
6488
6489 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6490 // 1.2.2 OpenMP Language Terminology
6491 // Structured block - An executable statement with a single entry at the
6492 // top and a single exit at the bottom.
6493 // The point of exit cannot be a branch out of the structured block.
6494 // longjmp() and throw() must not violate the entry/exit criteria.
6495 CS->getCapturedDecl()->setNothrow();
6496 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6497 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6498 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6499 // 1.2.2 OpenMP Language Terminology
6500 // Structured block - An executable statement with a single entry at the
6501 // top and a single exit at the bottom.
6502 // The point of exit cannot be a branch out of the structured block.
6503 // longjmp() and throw() must not violate the entry/exit criteria.
6504 CS->getCapturedDecl()->setNothrow();
6505 }
6506
Samuel Antao72590762016-01-19 20:04:50 +00006507 // OpenMP [2.10.3, Restrictions, p. 102]
6508 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006509 if (!hasClauses(Clauses, OMPC_map)) {
6510 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6511 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006512 return StmtError();
6513 }
6514
Alexey Bataev7828b252017-11-21 17:08:48 +00006515 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6516 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006517}
6518
Samuel Antao686c70c2016-05-26 17:30:50 +00006519StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6520 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006521 SourceLocation EndLoc,
6522 Stmt *AStmt) {
6523 if (!AStmt)
6524 return StmtError();
6525
6526 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6527 // 1.2.2 OpenMP Language Terminology
6528 // Structured block - An executable statement with a single entry at the
6529 // top and a single exit at the bottom.
6530 // The point of exit cannot be a branch out of the structured block.
6531 // longjmp() and throw() must not violate the entry/exit criteria.
6532 CS->getCapturedDecl()->setNothrow();
6533 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6534 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6535 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6536 // 1.2.2 OpenMP Language Terminology
6537 // Structured block - An executable statement with a single entry at the
6538 // top and a single exit at the bottom.
6539 // The point of exit cannot be a branch out of the structured block.
6540 // longjmp() and throw() must not violate the entry/exit criteria.
6541 CS->getCapturedDecl()->setNothrow();
6542 }
6543
Alexey Bataev95b64a92017-05-30 16:00:04 +00006544 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006545 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6546 return StmtError();
6547 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006548 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6549 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006550}
6551
Alexey Bataev13314bf2014-10-09 04:18:56 +00006552StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6553 Stmt *AStmt, SourceLocation StartLoc,
6554 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006555 if (!AStmt)
6556 return StmtError();
6557
Alexey Bataev13314bf2014-10-09 04:18:56 +00006558 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6559 // 1.2.2 OpenMP Language Terminology
6560 // Structured block - An executable statement with a single entry at the
6561 // top and a single exit at the bottom.
6562 // The point of exit cannot be a branch out of the structured block.
6563 // longjmp() and throw() must not violate the entry/exit criteria.
6564 CS->getCapturedDecl()->setNothrow();
6565
6566 getCurFunction()->setHasBranchProtectedScope();
6567
6568 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6569}
6570
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006571StmtResult
6572Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6573 SourceLocation EndLoc,
6574 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006575 if (DSAStack->isParentNowaitRegion()) {
6576 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6577 return StmtError();
6578 }
6579 if (DSAStack->isParentOrderedRegion()) {
6580 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6581 return StmtError();
6582 }
6583 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6584 CancelRegion);
6585}
6586
Alexey Bataev87933c72015-09-18 08:07:34 +00006587StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6588 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006589 SourceLocation EndLoc,
6590 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006591 if (DSAStack->isParentNowaitRegion()) {
6592 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6593 return StmtError();
6594 }
6595 if (DSAStack->isParentOrderedRegion()) {
6596 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6597 return StmtError();
6598 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006599 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006600 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6601 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006602}
6603
Alexey Bataev382967a2015-12-08 12:06:20 +00006604static bool checkGrainsizeNumTasksClauses(Sema &S,
6605 ArrayRef<OMPClause *> Clauses) {
6606 OMPClause *PrevClause = nullptr;
6607 bool ErrorFound = false;
6608 for (auto *C : Clauses) {
6609 if (C->getClauseKind() == OMPC_grainsize ||
6610 C->getClauseKind() == OMPC_num_tasks) {
6611 if (!PrevClause)
6612 PrevClause = C;
6613 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6614 S.Diag(C->getLocStart(),
6615 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6616 << getOpenMPClauseName(C->getClauseKind())
6617 << getOpenMPClauseName(PrevClause->getClauseKind());
6618 S.Diag(PrevClause->getLocStart(),
6619 diag::note_omp_previous_grainsize_num_tasks)
6620 << getOpenMPClauseName(PrevClause->getClauseKind());
6621 ErrorFound = true;
6622 }
6623 }
6624 }
6625 return ErrorFound;
6626}
6627
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006628static bool checkReductionClauseWithNogroup(Sema &S,
6629 ArrayRef<OMPClause *> Clauses) {
6630 OMPClause *ReductionClause = nullptr;
6631 OMPClause *NogroupClause = nullptr;
6632 for (auto *C : Clauses) {
6633 if (C->getClauseKind() == OMPC_reduction) {
6634 ReductionClause = C;
6635 if (NogroupClause)
6636 break;
6637 continue;
6638 }
6639 if (C->getClauseKind() == OMPC_nogroup) {
6640 NogroupClause = C;
6641 if (ReductionClause)
6642 break;
6643 continue;
6644 }
6645 }
6646 if (ReductionClause && NogroupClause) {
6647 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6648 << SourceRange(NogroupClause->getLocStart(),
6649 NogroupClause->getLocEnd());
6650 return true;
6651 }
6652 return false;
6653}
6654
Alexey Bataev49f6e782015-12-01 04:18:41 +00006655StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6656 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6657 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006658 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006659 if (!AStmt)
6660 return StmtError();
6661
6662 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6663 OMPLoopDirective::HelperExprs B;
6664 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6665 // define the nested loops number.
6666 unsigned NestedLoopCount =
6667 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006668 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006669 VarsWithImplicitDSA, B);
6670 if (NestedLoopCount == 0)
6671 return StmtError();
6672
6673 assert((CurContext->isDependentContext() || B.builtAll()) &&
6674 "omp for loop exprs were not built");
6675
Alexey Bataev382967a2015-12-08 12:06:20 +00006676 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6677 // The grainsize clause and num_tasks clause are mutually exclusive and may
6678 // not appear on the same taskloop directive.
6679 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6680 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006681 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6682 // If a reduction clause is present on the taskloop directive, the nogroup
6683 // clause must not be specified.
6684 if (checkReductionClauseWithNogroup(*this, Clauses))
6685 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006686
Alexey Bataev49f6e782015-12-01 04:18:41 +00006687 getCurFunction()->setHasBranchProtectedScope();
6688 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6689 NestedLoopCount, Clauses, AStmt, B);
6690}
6691
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006692StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6693 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6694 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006695 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006696 if (!AStmt)
6697 return StmtError();
6698
6699 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6700 OMPLoopDirective::HelperExprs B;
6701 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6702 // define the nested loops number.
6703 unsigned NestedLoopCount =
6704 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6705 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6706 VarsWithImplicitDSA, B);
6707 if (NestedLoopCount == 0)
6708 return StmtError();
6709
6710 assert((CurContext->isDependentContext() || B.builtAll()) &&
6711 "omp for loop exprs were not built");
6712
Alexey Bataev5a3af132016-03-29 08:58:54 +00006713 if (!CurContext->isDependentContext()) {
6714 // Finalize the clauses that need pre-built expressions for CodeGen.
6715 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006716 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006717 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006718 B.NumIterations, *this, CurScope,
6719 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006720 return StmtError();
6721 }
6722 }
6723
Alexey Bataev382967a2015-12-08 12:06:20 +00006724 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6725 // The grainsize clause and num_tasks clause are mutually exclusive and may
6726 // not appear on the same taskloop directive.
6727 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6728 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006729 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6730 // If a reduction clause is present on the taskloop directive, the nogroup
6731 // clause must not be specified.
6732 if (checkReductionClauseWithNogroup(*this, Clauses))
6733 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006734
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006735 getCurFunction()->setHasBranchProtectedScope();
6736 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6737 NestedLoopCount, Clauses, AStmt, B);
6738}
6739
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006740StmtResult Sema::ActOnOpenMPDistributeDirective(
6741 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6742 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006743 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006744 if (!AStmt)
6745 return StmtError();
6746
6747 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6748 OMPLoopDirective::HelperExprs B;
6749 // In presence of clause 'collapse' with number of loops, it will
6750 // define the nested loops number.
6751 unsigned NestedLoopCount =
6752 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6753 nullptr /*ordered not a clause on distribute*/, AStmt,
6754 *this, *DSAStack, VarsWithImplicitDSA, B);
6755 if (NestedLoopCount == 0)
6756 return StmtError();
6757
6758 assert((CurContext->isDependentContext() || B.builtAll()) &&
6759 "omp for loop exprs were not built");
6760
6761 getCurFunction()->setHasBranchProtectedScope();
6762 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6763 NestedLoopCount, Clauses, AStmt, B);
6764}
6765
Carlo Bertolli9925f152016-06-27 14:55:37 +00006766StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6767 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6768 SourceLocation EndLoc,
6769 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6770 if (!AStmt)
6771 return StmtError();
6772
6773 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6774 // 1.2.2 OpenMP Language Terminology
6775 // Structured block - An executable statement with a single entry at the
6776 // top and a single exit at the bottom.
6777 // The point of exit cannot be a branch out of the structured block.
6778 // longjmp() and throw() must not violate the entry/exit criteria.
6779 CS->getCapturedDecl()->setNothrow();
6780
6781 OMPLoopDirective::HelperExprs B;
6782 // In presence of clause 'collapse' with number of loops, it will
6783 // define the nested loops number.
6784 unsigned NestedLoopCount = CheckOpenMPLoop(
6785 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6786 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6787 VarsWithImplicitDSA, B);
6788 if (NestedLoopCount == 0)
6789 return StmtError();
6790
6791 assert((CurContext->isDependentContext() || B.builtAll()) &&
6792 "omp for loop exprs were not built");
6793
6794 getCurFunction()->setHasBranchProtectedScope();
6795 return OMPDistributeParallelForDirective::Create(
6796 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6797}
6798
Kelvin Li4a39add2016-07-05 05:00:15 +00006799StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6800 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6801 SourceLocation EndLoc,
6802 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6803 if (!AStmt)
6804 return StmtError();
6805
6806 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6807 // 1.2.2 OpenMP Language Terminology
6808 // Structured block - An executable statement with a single entry at the
6809 // top and a single exit at the bottom.
6810 // The point of exit cannot be a branch out of the structured block.
6811 // longjmp() and throw() must not violate the entry/exit criteria.
6812 CS->getCapturedDecl()->setNothrow();
6813
6814 OMPLoopDirective::HelperExprs B;
6815 // In presence of clause 'collapse' with number of loops, it will
6816 // define the nested loops number.
6817 unsigned NestedLoopCount = CheckOpenMPLoop(
6818 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6819 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6820 VarsWithImplicitDSA, B);
6821 if (NestedLoopCount == 0)
6822 return StmtError();
6823
6824 assert((CurContext->isDependentContext() || B.builtAll()) &&
6825 "omp for loop exprs were not built");
6826
Kelvin Lic5609492016-07-15 04:39:07 +00006827 if (checkSimdlenSafelenSpecified(*this, Clauses))
6828 return StmtError();
6829
Kelvin Li4a39add2016-07-05 05:00:15 +00006830 getCurFunction()->setHasBranchProtectedScope();
6831 return OMPDistributeParallelForSimdDirective::Create(
6832 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6833}
6834
Kelvin Li787f3fc2016-07-06 04:45:38 +00006835StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6836 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6837 SourceLocation EndLoc,
6838 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6839 if (!AStmt)
6840 return StmtError();
6841
6842 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6843 // 1.2.2 OpenMP Language Terminology
6844 // Structured block - An executable statement with a single entry at the
6845 // top and a single exit at the bottom.
6846 // The point of exit cannot be a branch out of the structured block.
6847 // longjmp() and throw() must not violate the entry/exit criteria.
6848 CS->getCapturedDecl()->setNothrow();
6849
6850 OMPLoopDirective::HelperExprs B;
6851 // In presence of clause 'collapse' with number of loops, it will
6852 // define the nested loops number.
6853 unsigned NestedLoopCount =
6854 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6855 nullptr /*ordered not a clause on distribute*/, AStmt,
6856 *this, *DSAStack, VarsWithImplicitDSA, B);
6857 if (NestedLoopCount == 0)
6858 return StmtError();
6859
6860 assert((CurContext->isDependentContext() || B.builtAll()) &&
6861 "omp for loop exprs were not built");
6862
Kelvin Lic5609492016-07-15 04:39:07 +00006863 if (checkSimdlenSafelenSpecified(*this, Clauses))
6864 return StmtError();
6865
Kelvin Li787f3fc2016-07-06 04:45:38 +00006866 getCurFunction()->setHasBranchProtectedScope();
6867 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6868 NestedLoopCount, Clauses, AStmt, B);
6869}
6870
Kelvin Lia579b912016-07-14 02:54:56 +00006871StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6872 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6873 SourceLocation EndLoc,
6874 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6875 if (!AStmt)
6876 return StmtError();
6877
6878 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6879 // 1.2.2 OpenMP Language Terminology
6880 // Structured block - An executable statement with a single entry at the
6881 // top and a single exit at the bottom.
6882 // The point of exit cannot be a branch out of the structured block.
6883 // longjmp() and throw() must not violate the entry/exit criteria.
6884 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006885 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6886 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6887 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6888 // 1.2.2 OpenMP Language Terminology
6889 // Structured block - An executable statement with a single entry at the
6890 // top and a single exit at the bottom.
6891 // The point of exit cannot be a branch out of the structured block.
6892 // longjmp() and throw() must not violate the entry/exit criteria.
6893 CS->getCapturedDecl()->setNothrow();
6894 }
Kelvin Lia579b912016-07-14 02:54:56 +00006895
6896 OMPLoopDirective::HelperExprs B;
6897 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6898 // define the nested loops number.
6899 unsigned NestedLoopCount = CheckOpenMPLoop(
6900 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00006901 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00006902 VarsWithImplicitDSA, B);
6903 if (NestedLoopCount == 0)
6904 return StmtError();
6905
6906 assert((CurContext->isDependentContext() || B.builtAll()) &&
6907 "omp target parallel for simd loop exprs were not built");
6908
6909 if (!CurContext->isDependentContext()) {
6910 // Finalize the clauses that need pre-built expressions for CodeGen.
6911 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006912 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006913 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6914 B.NumIterations, *this, CurScope,
6915 DSAStack))
6916 return StmtError();
6917 }
6918 }
Kelvin Lic5609492016-07-15 04:39:07 +00006919 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006920 return StmtError();
6921
6922 getCurFunction()->setHasBranchProtectedScope();
6923 return OMPTargetParallelForSimdDirective::Create(
6924 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6925}
6926
Kelvin Li986330c2016-07-20 22:57:10 +00006927StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6928 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6929 SourceLocation EndLoc,
6930 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6931 if (!AStmt)
6932 return StmtError();
6933
6934 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6935 // 1.2.2 OpenMP Language Terminology
6936 // Structured block - An executable statement with a single entry at the
6937 // top and a single exit at the bottom.
6938 // The point of exit cannot be a branch out of the structured block.
6939 // longjmp() and throw() must not violate the entry/exit criteria.
6940 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00006941 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
6942 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6943 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6944 // 1.2.2 OpenMP Language Terminology
6945 // Structured block - An executable statement with a single entry at the
6946 // top and a single exit at the bottom.
6947 // The point of exit cannot be a branch out of the structured block.
6948 // longjmp() and throw() must not violate the entry/exit criteria.
6949 CS->getCapturedDecl()->setNothrow();
6950 }
6951
Kelvin Li986330c2016-07-20 22:57:10 +00006952 OMPLoopDirective::HelperExprs B;
6953 // In presence of clause 'collapse' with number of loops, it will define the
6954 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006955 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006956 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00006957 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00006958 VarsWithImplicitDSA, B);
6959 if (NestedLoopCount == 0)
6960 return StmtError();
6961
6962 assert((CurContext->isDependentContext() || B.builtAll()) &&
6963 "omp target simd loop exprs were not built");
6964
6965 if (!CurContext->isDependentContext()) {
6966 // Finalize the clauses that need pre-built expressions for CodeGen.
6967 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006968 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006969 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6970 B.NumIterations, *this, CurScope,
6971 DSAStack))
6972 return StmtError();
6973 }
6974 }
6975
6976 if (checkSimdlenSafelenSpecified(*this, Clauses))
6977 return StmtError();
6978
6979 getCurFunction()->setHasBranchProtectedScope();
6980 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6981 NestedLoopCount, Clauses, AStmt, B);
6982}
6983
Kelvin Li02532872016-08-05 14:37:37 +00006984StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6985 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6986 SourceLocation EndLoc,
6987 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6988 if (!AStmt)
6989 return StmtError();
6990
6991 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6992 // 1.2.2 OpenMP Language Terminology
6993 // Structured block - An executable statement with a single entry at the
6994 // top and a single exit at the bottom.
6995 // The point of exit cannot be a branch out of the structured block.
6996 // longjmp() and throw() must not violate the entry/exit criteria.
6997 CS->getCapturedDecl()->setNothrow();
6998
6999 OMPLoopDirective::HelperExprs B;
7000 // In presence of clause 'collapse' with number of loops, it will
7001 // define the nested loops number.
7002 unsigned NestedLoopCount =
7003 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7004 nullptr /*ordered not a clause on distribute*/, AStmt,
7005 *this, *DSAStack, VarsWithImplicitDSA, B);
7006 if (NestedLoopCount == 0)
7007 return StmtError();
7008
7009 assert((CurContext->isDependentContext() || B.builtAll()) &&
7010 "omp teams distribute loop exprs were not built");
7011
7012 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00007013 return OMPTeamsDistributeDirective::Create(
7014 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007015}
7016
Kelvin Li4e325f72016-10-25 12:50:55 +00007017StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7018 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7019 SourceLocation EndLoc,
7020 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7021 if (!AStmt)
7022 return StmtError();
7023
7024 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7025 // 1.2.2 OpenMP Language Terminology
7026 // Structured block - An executable statement with a single entry at the
7027 // top and a single exit at the bottom.
7028 // The point of exit cannot be a branch out of the structured block.
7029 // longjmp() and throw() must not violate the entry/exit criteria.
7030 CS->getCapturedDecl()->setNothrow();
7031
7032 OMPLoopDirective::HelperExprs B;
7033 // In presence of clause 'collapse' with number of loops, it will
7034 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007035 unsigned NestedLoopCount = CheckOpenMPLoop(
7036 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7037 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7038 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007039
7040 if (NestedLoopCount == 0)
7041 return StmtError();
7042
7043 assert((CurContext->isDependentContext() || B.builtAll()) &&
7044 "omp teams distribute simd loop exprs were not built");
7045
7046 if (!CurContext->isDependentContext()) {
7047 // Finalize the clauses that need pre-built expressions for CodeGen.
7048 for (auto C : Clauses) {
7049 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7050 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7051 B.NumIterations, *this, CurScope,
7052 DSAStack))
7053 return StmtError();
7054 }
7055 }
7056
7057 if (checkSimdlenSafelenSpecified(*this, Clauses))
7058 return StmtError();
7059
7060 getCurFunction()->setHasBranchProtectedScope();
7061 return OMPTeamsDistributeSimdDirective::Create(
7062 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7063}
7064
Kelvin Li579e41c2016-11-30 23:51:03 +00007065StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7066 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7067 SourceLocation EndLoc,
7068 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7069 if (!AStmt)
7070 return StmtError();
7071
7072 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7073 // 1.2.2 OpenMP Language Terminology
7074 // Structured block - An executable statement with a single entry at the
7075 // top and a single exit at the bottom.
7076 // The point of exit cannot be a branch out of the structured block.
7077 // longjmp() and throw() must not violate the entry/exit criteria.
7078 CS->getCapturedDecl()->setNothrow();
7079
7080 OMPLoopDirective::HelperExprs B;
7081 // In presence of clause 'collapse' with number of loops, it will
7082 // define the nested loops number.
7083 auto NestedLoopCount = CheckOpenMPLoop(
7084 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7085 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7086 VarsWithImplicitDSA, B);
7087
7088 if (NestedLoopCount == 0)
7089 return StmtError();
7090
7091 assert((CurContext->isDependentContext() || B.builtAll()) &&
7092 "omp for loop exprs were not built");
7093
7094 if (!CurContext->isDependentContext()) {
7095 // Finalize the clauses that need pre-built expressions for CodeGen.
7096 for (auto C : Clauses) {
7097 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7098 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7099 B.NumIterations, *this, CurScope,
7100 DSAStack))
7101 return StmtError();
7102 }
7103 }
7104
7105 if (checkSimdlenSafelenSpecified(*this, Clauses))
7106 return StmtError();
7107
7108 getCurFunction()->setHasBranchProtectedScope();
7109 return OMPTeamsDistributeParallelForSimdDirective::Create(
7110 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7111}
7112
Kelvin Li7ade93f2016-12-09 03:24:30 +00007113StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7114 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7115 SourceLocation EndLoc,
7116 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7117 if (!AStmt)
7118 return StmtError();
7119
7120 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7121 // 1.2.2 OpenMP Language Terminology
7122 // Structured block - An executable statement with a single entry at the
7123 // top and a single exit at the bottom.
7124 // The point of exit cannot be a branch out of the structured block.
7125 // longjmp() and throw() must not violate the entry/exit criteria.
7126 CS->getCapturedDecl()->setNothrow();
7127
Carlo Bertolli62fae152017-11-20 20:46:39 +00007128 for (int ThisCaptureLevel =
7129 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7130 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7131 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7132 // 1.2.2 OpenMP Language Terminology
7133 // Structured block - An executable statement with a single entry at the
7134 // top and a single exit at the bottom.
7135 // The point of exit cannot be a branch out of the structured block.
7136 // longjmp() and throw() must not violate the entry/exit criteria.
7137 CS->getCapturedDecl()->setNothrow();
7138 }
7139
Kelvin Li7ade93f2016-12-09 03:24:30 +00007140 OMPLoopDirective::HelperExprs B;
7141 // In presence of clause 'collapse' with number of loops, it will
7142 // define the nested loops number.
7143 unsigned NestedLoopCount = CheckOpenMPLoop(
7144 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007145 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007146 VarsWithImplicitDSA, B);
7147
7148 if (NestedLoopCount == 0)
7149 return StmtError();
7150
7151 assert((CurContext->isDependentContext() || B.builtAll()) &&
7152 "omp for loop exprs were not built");
7153
7154 if (!CurContext->isDependentContext()) {
7155 // Finalize the clauses that need pre-built expressions for CodeGen.
7156 for (auto C : Clauses) {
7157 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7158 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7159 B.NumIterations, *this, CurScope,
7160 DSAStack))
7161 return StmtError();
7162 }
7163 }
7164
7165 getCurFunction()->setHasBranchProtectedScope();
7166 return OMPTeamsDistributeParallelForDirective::Create(
7167 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7168}
7169
Kelvin Libf594a52016-12-17 05:48:59 +00007170StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7171 Stmt *AStmt,
7172 SourceLocation StartLoc,
7173 SourceLocation EndLoc) {
7174 if (!AStmt)
7175 return StmtError();
7176
7177 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7178 // 1.2.2 OpenMP Language Terminology
7179 // Structured block - An executable statement with a single entry at the
7180 // top and a single exit at the bottom.
7181 // The point of exit cannot be a branch out of the structured block.
7182 // longjmp() and throw() must not violate the entry/exit criteria.
7183 CS->getCapturedDecl()->setNothrow();
7184
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007185 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7186 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7187 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7188 // 1.2.2 OpenMP Language Terminology
7189 // Structured block - An executable statement with a single entry at the
7190 // top and a single exit at the bottom.
7191 // The point of exit cannot be a branch out of the structured block.
7192 // longjmp() and throw() must not violate the entry/exit criteria.
7193 CS->getCapturedDecl()->setNothrow();
7194 }
Kelvin Libf594a52016-12-17 05:48:59 +00007195 getCurFunction()->setHasBranchProtectedScope();
7196
7197 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7198 AStmt);
7199}
7200
Kelvin Li83c451e2016-12-25 04:52:54 +00007201StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7202 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7203 SourceLocation EndLoc,
7204 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7205 if (!AStmt)
7206 return StmtError();
7207
7208 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7209 // 1.2.2 OpenMP Language Terminology
7210 // Structured block - An executable statement with a single entry at the
7211 // top and a single exit at the bottom.
7212 // The point of exit cannot be a branch out of the structured block.
7213 // longjmp() and throw() must not violate the entry/exit criteria.
7214 CS->getCapturedDecl()->setNothrow();
7215
7216 OMPLoopDirective::HelperExprs B;
7217 // In presence of clause 'collapse' with number of loops, it will
7218 // define the nested loops number.
7219 auto NestedLoopCount = CheckOpenMPLoop(
7220 OMPD_target_teams_distribute,
7221 getCollapseNumberExpr(Clauses),
7222 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7223 VarsWithImplicitDSA, B);
7224 if (NestedLoopCount == 0)
7225 return StmtError();
7226
7227 assert((CurContext->isDependentContext() || B.builtAll()) &&
7228 "omp target teams distribute loop exprs were not built");
7229
7230 getCurFunction()->setHasBranchProtectedScope();
7231 return OMPTargetTeamsDistributeDirective::Create(
7232 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7233}
7234
Kelvin Li80e8f562016-12-29 22:16:30 +00007235StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7236 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7237 SourceLocation EndLoc,
7238 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7239 if (!AStmt)
7240 return StmtError();
7241
7242 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7243 // 1.2.2 OpenMP Language Terminology
7244 // Structured block - An executable statement with a single entry at the
7245 // top and a single exit at the bottom.
7246 // The point of exit cannot be a branch out of the structured block.
7247 // longjmp() and throw() must not violate the entry/exit criteria.
7248 CS->getCapturedDecl()->setNothrow();
7249
7250 OMPLoopDirective::HelperExprs B;
7251 // In presence of clause 'collapse' with number of loops, it will
7252 // define the nested loops number.
7253 auto NestedLoopCount = CheckOpenMPLoop(
7254 OMPD_target_teams_distribute_parallel_for,
7255 getCollapseNumberExpr(Clauses),
7256 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7257 VarsWithImplicitDSA, B);
7258 if (NestedLoopCount == 0)
7259 return StmtError();
7260
7261 assert((CurContext->isDependentContext() || B.builtAll()) &&
7262 "omp target teams distribute parallel for loop exprs were not built");
7263
7264 if (!CurContext->isDependentContext()) {
7265 // Finalize the clauses that need pre-built expressions for CodeGen.
7266 for (auto C : Clauses) {
7267 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7268 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7269 B.NumIterations, *this, CurScope,
7270 DSAStack))
7271 return StmtError();
7272 }
7273 }
7274
7275 getCurFunction()->setHasBranchProtectedScope();
7276 return OMPTargetTeamsDistributeParallelForDirective::Create(
7277 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7278}
7279
Kelvin Li1851df52017-01-03 05:23:48 +00007280StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7281 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7282 SourceLocation EndLoc,
7283 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7284 if (!AStmt)
7285 return StmtError();
7286
7287 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7288 // 1.2.2 OpenMP Language Terminology
7289 // Structured block - An executable statement with a single entry at the
7290 // top and a single exit at the bottom.
7291 // The point of exit cannot be a branch out of the structured block.
7292 // longjmp() and throw() must not violate the entry/exit criteria.
7293 CS->getCapturedDecl()->setNothrow();
7294
7295 OMPLoopDirective::HelperExprs B;
7296 // In presence of clause 'collapse' with number of loops, it will
7297 // define the nested loops number.
7298 auto NestedLoopCount = CheckOpenMPLoop(
7299 OMPD_target_teams_distribute_parallel_for_simd,
7300 getCollapseNumberExpr(Clauses),
7301 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7302 VarsWithImplicitDSA, B);
7303 if (NestedLoopCount == 0)
7304 return StmtError();
7305
7306 assert((CurContext->isDependentContext() || B.builtAll()) &&
7307 "omp target teams distribute parallel for simd loop exprs were not "
7308 "built");
7309
7310 if (!CurContext->isDependentContext()) {
7311 // Finalize the clauses that need pre-built expressions for CodeGen.
7312 for (auto C : Clauses) {
7313 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7314 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7315 B.NumIterations, *this, CurScope,
7316 DSAStack))
7317 return StmtError();
7318 }
7319 }
7320
7321 getCurFunction()->setHasBranchProtectedScope();
7322 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7323 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7324}
7325
Kelvin Lida681182017-01-10 18:08:18 +00007326StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7327 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7328 SourceLocation EndLoc,
7329 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7330 if (!AStmt)
7331 return StmtError();
7332
7333 auto *CS = cast<CapturedStmt>(AStmt);
7334 // 1.2.2 OpenMP Language Terminology
7335 // Structured block - An executable statement with a single entry at the
7336 // top and a single exit at the bottom.
7337 // The point of exit cannot be a branch out of the structured block.
7338 // longjmp() and throw() must not violate the entry/exit criteria.
7339 CS->getCapturedDecl()->setNothrow();
7340
7341 OMPLoopDirective::HelperExprs B;
7342 // In presence of clause 'collapse' with number of loops, it will
7343 // define the nested loops number.
7344 auto NestedLoopCount = CheckOpenMPLoop(
7345 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7346 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7347 VarsWithImplicitDSA, B);
7348 if (NestedLoopCount == 0)
7349 return StmtError();
7350
7351 assert((CurContext->isDependentContext() || B.builtAll()) &&
7352 "omp target teams distribute simd loop exprs were not built");
7353
7354 getCurFunction()->setHasBranchProtectedScope();
7355 return OMPTargetTeamsDistributeSimdDirective::Create(
7356 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7357}
7358
Alexey Bataeved09d242014-05-28 05:53:51 +00007359OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007360 SourceLocation StartLoc,
7361 SourceLocation LParenLoc,
7362 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007363 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007364 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007365 case OMPC_final:
7366 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7367 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007368 case OMPC_num_threads:
7369 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7370 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007371 case OMPC_safelen:
7372 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7373 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007374 case OMPC_simdlen:
7375 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7376 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007377 case OMPC_collapse:
7378 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7379 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007380 case OMPC_ordered:
7381 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7382 break;
Michael Wonge710d542015-08-07 16:16:36 +00007383 case OMPC_device:
7384 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7385 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007386 case OMPC_num_teams:
7387 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7388 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007389 case OMPC_thread_limit:
7390 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7391 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007392 case OMPC_priority:
7393 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7394 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007395 case OMPC_grainsize:
7396 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7397 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007398 case OMPC_num_tasks:
7399 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7400 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007401 case OMPC_hint:
7402 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7403 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007404 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007405 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007406 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007407 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007408 case OMPC_private:
7409 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007410 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007411 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007412 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007413 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007414 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007415 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007416 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007417 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007418 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007419 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007420 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007421 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007422 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007423 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007424 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007425 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007426 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007427 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007428 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007429 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007430 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007431 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007432 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007433 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007434 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007435 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007436 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007437 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007438 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007439 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007440 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007441 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007442 llvm_unreachable("Clause is not allowed.");
7443 }
7444 return Res;
7445}
7446
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007447// An OpenMP directive such as 'target parallel' has two captured regions:
7448// for the 'target' and 'parallel' respectively. This function returns
7449// the region in which to capture expressions associated with a clause.
7450// A return value of OMPD_unknown signifies that the expression should not
7451// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007452static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7453 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7454 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007455 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7456
7457 switch (CKind) {
7458 case OMPC_if:
7459 switch (DKind) {
7460 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007461 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007462 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007463 // If this clause applies to the nested 'parallel' region, capture within
7464 // the 'target' region, otherwise do not capture.
7465 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7466 CaptureRegion = OMPD_target;
7467 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007468 case OMPD_teams_distribute_parallel_for:
7469 CaptureRegion = OMPD_teams;
7470 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007471 case OMPD_cancel:
7472 case OMPD_parallel:
7473 case OMPD_parallel_sections:
7474 case OMPD_parallel_for:
7475 case OMPD_parallel_for_simd:
7476 case OMPD_target:
7477 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007478 case OMPD_target_teams:
7479 case OMPD_target_teams_distribute:
7480 case OMPD_target_teams_distribute_simd:
7481 case OMPD_target_teams_distribute_parallel_for:
7482 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007483 case OMPD_teams_distribute_parallel_for_simd:
7484 case OMPD_distribute_parallel_for:
7485 case OMPD_distribute_parallel_for_simd:
7486 case OMPD_task:
7487 case OMPD_taskloop:
7488 case OMPD_taskloop_simd:
7489 case OMPD_target_data:
7490 case OMPD_target_enter_data:
7491 case OMPD_target_exit_data:
7492 case OMPD_target_update:
7493 // Do not capture if-clause expressions.
7494 break;
7495 case OMPD_threadprivate:
7496 case OMPD_taskyield:
7497 case OMPD_barrier:
7498 case OMPD_taskwait:
7499 case OMPD_cancellation_point:
7500 case OMPD_flush:
7501 case OMPD_declare_reduction:
7502 case OMPD_declare_simd:
7503 case OMPD_declare_target:
7504 case OMPD_end_declare_target:
7505 case OMPD_teams:
7506 case OMPD_simd:
7507 case OMPD_for:
7508 case OMPD_for_simd:
7509 case OMPD_sections:
7510 case OMPD_section:
7511 case OMPD_single:
7512 case OMPD_master:
7513 case OMPD_critical:
7514 case OMPD_taskgroup:
7515 case OMPD_distribute:
7516 case OMPD_ordered:
7517 case OMPD_atomic:
7518 case OMPD_distribute_simd:
7519 case OMPD_teams_distribute:
7520 case OMPD_teams_distribute_simd:
7521 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7522 case OMPD_unknown:
7523 llvm_unreachable("Unknown OpenMP directive");
7524 }
7525 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007526 case OMPC_num_threads:
7527 switch (DKind) {
7528 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007529 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007530 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007531 CaptureRegion = OMPD_target;
7532 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007533 case OMPD_teams_distribute_parallel_for:
7534 CaptureRegion = OMPD_teams;
7535 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007536 case OMPD_cancel:
7537 case OMPD_parallel:
7538 case OMPD_parallel_sections:
7539 case OMPD_parallel_for:
7540 case OMPD_parallel_for_simd:
7541 case OMPD_target:
7542 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007543 case OMPD_target_teams:
7544 case OMPD_target_teams_distribute:
7545 case OMPD_target_teams_distribute_simd:
7546 case OMPD_target_teams_distribute_parallel_for:
7547 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007548 case OMPD_teams_distribute_parallel_for_simd:
7549 case OMPD_distribute_parallel_for:
7550 case OMPD_distribute_parallel_for_simd:
7551 case OMPD_task:
7552 case OMPD_taskloop:
7553 case OMPD_taskloop_simd:
7554 case OMPD_target_data:
7555 case OMPD_target_enter_data:
7556 case OMPD_target_exit_data:
7557 case OMPD_target_update:
7558 // Do not capture num_threads-clause expressions.
7559 break;
7560 case OMPD_threadprivate:
7561 case OMPD_taskyield:
7562 case OMPD_barrier:
7563 case OMPD_taskwait:
7564 case OMPD_cancellation_point:
7565 case OMPD_flush:
7566 case OMPD_declare_reduction:
7567 case OMPD_declare_simd:
7568 case OMPD_declare_target:
7569 case OMPD_end_declare_target:
7570 case OMPD_teams:
7571 case OMPD_simd:
7572 case OMPD_for:
7573 case OMPD_for_simd:
7574 case OMPD_sections:
7575 case OMPD_section:
7576 case OMPD_single:
7577 case OMPD_master:
7578 case OMPD_critical:
7579 case OMPD_taskgroup:
7580 case OMPD_distribute:
7581 case OMPD_ordered:
7582 case OMPD_atomic:
7583 case OMPD_distribute_simd:
7584 case OMPD_teams_distribute:
7585 case OMPD_teams_distribute_simd:
7586 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7587 case OMPD_unknown:
7588 llvm_unreachable("Unknown OpenMP directive");
7589 }
7590 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007591 case OMPC_num_teams:
7592 switch (DKind) {
7593 case OMPD_target_teams:
7594 CaptureRegion = OMPD_target;
7595 break;
7596 case OMPD_cancel:
7597 case OMPD_parallel:
7598 case OMPD_parallel_sections:
7599 case OMPD_parallel_for:
7600 case OMPD_parallel_for_simd:
7601 case OMPD_target:
7602 case OMPD_target_simd:
7603 case OMPD_target_parallel:
7604 case OMPD_target_parallel_for:
7605 case OMPD_target_parallel_for_simd:
7606 case OMPD_target_teams_distribute:
7607 case OMPD_target_teams_distribute_simd:
7608 case OMPD_target_teams_distribute_parallel_for:
7609 case OMPD_target_teams_distribute_parallel_for_simd:
7610 case OMPD_teams_distribute_parallel_for:
7611 case OMPD_teams_distribute_parallel_for_simd:
7612 case OMPD_distribute_parallel_for:
7613 case OMPD_distribute_parallel_for_simd:
7614 case OMPD_task:
7615 case OMPD_taskloop:
7616 case OMPD_taskloop_simd:
7617 case OMPD_target_data:
7618 case OMPD_target_enter_data:
7619 case OMPD_target_exit_data:
7620 case OMPD_target_update:
7621 case OMPD_teams:
7622 case OMPD_teams_distribute:
7623 case OMPD_teams_distribute_simd:
7624 // Do not capture num_teams-clause expressions.
7625 break;
7626 case OMPD_threadprivate:
7627 case OMPD_taskyield:
7628 case OMPD_barrier:
7629 case OMPD_taskwait:
7630 case OMPD_cancellation_point:
7631 case OMPD_flush:
7632 case OMPD_declare_reduction:
7633 case OMPD_declare_simd:
7634 case OMPD_declare_target:
7635 case OMPD_end_declare_target:
7636 case OMPD_simd:
7637 case OMPD_for:
7638 case OMPD_for_simd:
7639 case OMPD_sections:
7640 case OMPD_section:
7641 case OMPD_single:
7642 case OMPD_master:
7643 case OMPD_critical:
7644 case OMPD_taskgroup:
7645 case OMPD_distribute:
7646 case OMPD_ordered:
7647 case OMPD_atomic:
7648 case OMPD_distribute_simd:
7649 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7650 case OMPD_unknown:
7651 llvm_unreachable("Unknown OpenMP directive");
7652 }
7653 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007654 case OMPC_thread_limit:
7655 switch (DKind) {
7656 case OMPD_target_teams:
7657 CaptureRegion = OMPD_target;
7658 break;
7659 case OMPD_cancel:
7660 case OMPD_parallel:
7661 case OMPD_parallel_sections:
7662 case OMPD_parallel_for:
7663 case OMPD_parallel_for_simd:
7664 case OMPD_target:
7665 case OMPD_target_simd:
7666 case OMPD_target_parallel:
7667 case OMPD_target_parallel_for:
7668 case OMPD_target_parallel_for_simd:
7669 case OMPD_target_teams_distribute:
7670 case OMPD_target_teams_distribute_simd:
7671 case OMPD_target_teams_distribute_parallel_for:
7672 case OMPD_target_teams_distribute_parallel_for_simd:
7673 case OMPD_teams_distribute_parallel_for:
7674 case OMPD_teams_distribute_parallel_for_simd:
7675 case OMPD_distribute_parallel_for:
7676 case OMPD_distribute_parallel_for_simd:
7677 case OMPD_task:
7678 case OMPD_taskloop:
7679 case OMPD_taskloop_simd:
7680 case OMPD_target_data:
7681 case OMPD_target_enter_data:
7682 case OMPD_target_exit_data:
7683 case OMPD_target_update:
7684 case OMPD_teams:
7685 case OMPD_teams_distribute:
7686 case OMPD_teams_distribute_simd:
7687 // Do not capture thread_limit-clause expressions.
7688 break;
7689 case OMPD_threadprivate:
7690 case OMPD_taskyield:
7691 case OMPD_barrier:
7692 case OMPD_taskwait:
7693 case OMPD_cancellation_point:
7694 case OMPD_flush:
7695 case OMPD_declare_reduction:
7696 case OMPD_declare_simd:
7697 case OMPD_declare_target:
7698 case OMPD_end_declare_target:
7699 case OMPD_simd:
7700 case OMPD_for:
7701 case OMPD_for_simd:
7702 case OMPD_sections:
7703 case OMPD_section:
7704 case OMPD_single:
7705 case OMPD_master:
7706 case OMPD_critical:
7707 case OMPD_taskgroup:
7708 case OMPD_distribute:
7709 case OMPD_ordered:
7710 case OMPD_atomic:
7711 case OMPD_distribute_simd:
7712 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7713 case OMPD_unknown:
7714 llvm_unreachable("Unknown OpenMP directive");
7715 }
7716 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007717 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007718 switch (DKind) {
7719 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007720 case OMPD_target_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007721 CaptureRegion = OMPD_target;
7722 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007723 case OMPD_teams_distribute_parallel_for:
7724 CaptureRegion = OMPD_teams;
7725 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007726 case OMPD_parallel_for:
7727 case OMPD_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007728 case OMPD_target_teams_distribute_parallel_for:
7729 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007730 case OMPD_teams_distribute_parallel_for_simd:
7731 case OMPD_distribute_parallel_for:
7732 case OMPD_distribute_parallel_for_simd:
7733 // Do not capture thread_limit-clause expressions.
7734 break;
7735 case OMPD_task:
7736 case OMPD_taskloop:
7737 case OMPD_taskloop_simd:
7738 case OMPD_target_data:
7739 case OMPD_target_enter_data:
7740 case OMPD_target_exit_data:
7741 case OMPD_target_update:
7742 case OMPD_teams:
7743 case OMPD_teams_distribute:
7744 case OMPD_teams_distribute_simd:
7745 case OMPD_target_teams_distribute:
7746 case OMPD_target_teams_distribute_simd:
7747 case OMPD_target:
7748 case OMPD_target_simd:
7749 case OMPD_target_parallel:
7750 case OMPD_cancel:
7751 case OMPD_parallel:
7752 case OMPD_parallel_sections:
7753 case OMPD_threadprivate:
7754 case OMPD_taskyield:
7755 case OMPD_barrier:
7756 case OMPD_taskwait:
7757 case OMPD_cancellation_point:
7758 case OMPD_flush:
7759 case OMPD_declare_reduction:
7760 case OMPD_declare_simd:
7761 case OMPD_declare_target:
7762 case OMPD_end_declare_target:
7763 case OMPD_simd:
7764 case OMPD_for:
7765 case OMPD_for_simd:
7766 case OMPD_sections:
7767 case OMPD_section:
7768 case OMPD_single:
7769 case OMPD_master:
7770 case OMPD_critical:
7771 case OMPD_taskgroup:
7772 case OMPD_distribute:
7773 case OMPD_ordered:
7774 case OMPD_atomic:
7775 case OMPD_distribute_simd:
7776 case OMPD_target_teams:
7777 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7778 case OMPD_unknown:
7779 llvm_unreachable("Unknown OpenMP directive");
7780 }
7781 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007782 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007783 switch (DKind) {
7784 case OMPD_teams_distribute_parallel_for:
7785 CaptureRegion = OMPD_teams;
7786 break;
7787 case OMPD_target_teams_distribute_parallel_for:
7788 case OMPD_target_teams_distribute_parallel_for_simd:
7789 case OMPD_teams_distribute_parallel_for_simd:
7790 case OMPD_distribute_parallel_for:
7791 case OMPD_distribute_parallel_for_simd:
7792 case OMPD_teams_distribute:
7793 case OMPD_teams_distribute_simd:
7794 case OMPD_target_teams_distribute:
7795 case OMPD_target_teams_distribute_simd:
7796 case OMPD_distribute_simd:
7797 // Do not capture thread_limit-clause expressions.
7798 break;
7799 case OMPD_parallel_for:
7800 case OMPD_parallel_for_simd:
7801 case OMPD_target_parallel_for_simd:
7802 case OMPD_target_parallel_for:
7803 case OMPD_task:
7804 case OMPD_taskloop:
7805 case OMPD_taskloop_simd:
7806 case OMPD_target_data:
7807 case OMPD_target_enter_data:
7808 case OMPD_target_exit_data:
7809 case OMPD_target_update:
7810 case OMPD_teams:
7811 case OMPD_target:
7812 case OMPD_target_simd:
7813 case OMPD_target_parallel:
7814 case OMPD_cancel:
7815 case OMPD_parallel:
7816 case OMPD_parallel_sections:
7817 case OMPD_threadprivate:
7818 case OMPD_taskyield:
7819 case OMPD_barrier:
7820 case OMPD_taskwait:
7821 case OMPD_cancellation_point:
7822 case OMPD_flush:
7823 case OMPD_declare_reduction:
7824 case OMPD_declare_simd:
7825 case OMPD_declare_target:
7826 case OMPD_end_declare_target:
7827 case OMPD_simd:
7828 case OMPD_for:
7829 case OMPD_for_simd:
7830 case OMPD_sections:
7831 case OMPD_section:
7832 case OMPD_single:
7833 case OMPD_master:
7834 case OMPD_critical:
7835 case OMPD_taskgroup:
7836 case OMPD_distribute:
7837 case OMPD_ordered:
7838 case OMPD_atomic:
7839 case OMPD_target_teams:
7840 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7841 case OMPD_unknown:
7842 llvm_unreachable("Unknown OpenMP directive");
7843 }
7844 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007845 case OMPC_firstprivate:
7846 case OMPC_lastprivate:
7847 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007848 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007849 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007850 case OMPC_linear:
7851 case OMPC_default:
7852 case OMPC_proc_bind:
7853 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007854 case OMPC_safelen:
7855 case OMPC_simdlen:
7856 case OMPC_collapse:
7857 case OMPC_private:
7858 case OMPC_shared:
7859 case OMPC_aligned:
7860 case OMPC_copyin:
7861 case OMPC_copyprivate:
7862 case OMPC_ordered:
7863 case OMPC_nowait:
7864 case OMPC_untied:
7865 case OMPC_mergeable:
7866 case OMPC_threadprivate:
7867 case OMPC_flush:
7868 case OMPC_read:
7869 case OMPC_write:
7870 case OMPC_update:
7871 case OMPC_capture:
7872 case OMPC_seq_cst:
7873 case OMPC_depend:
7874 case OMPC_device:
7875 case OMPC_threads:
7876 case OMPC_simd:
7877 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007878 case OMPC_priority:
7879 case OMPC_grainsize:
7880 case OMPC_nogroup:
7881 case OMPC_num_tasks:
7882 case OMPC_hint:
7883 case OMPC_defaultmap:
7884 case OMPC_unknown:
7885 case OMPC_uniform:
7886 case OMPC_to:
7887 case OMPC_from:
7888 case OMPC_use_device_ptr:
7889 case OMPC_is_device_ptr:
7890 llvm_unreachable("Unexpected OpenMP clause.");
7891 }
7892 return CaptureRegion;
7893}
7894
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007895OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7896 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007897 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007898 SourceLocation NameModifierLoc,
7899 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007900 SourceLocation EndLoc) {
7901 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007902 Stmt *HelperValStmt = nullptr;
7903 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007904 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7905 !Condition->isInstantiationDependent() &&
7906 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007907 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007908 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007909 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007910
Richard Smith03a4aa32016-06-23 19:02:52 +00007911 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007912
7913 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7914 CaptureRegion =
7915 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7916 if (CaptureRegion != OMPD_unknown) {
7917 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7918 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7919 HelperValStmt = buildPreInits(Context, Captures);
7920 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007921 }
7922
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007923 return new (Context)
7924 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7925 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007926}
7927
Alexey Bataev3778b602014-07-17 07:32:53 +00007928OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7929 SourceLocation StartLoc,
7930 SourceLocation LParenLoc,
7931 SourceLocation EndLoc) {
7932 Expr *ValExpr = Condition;
7933 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7934 !Condition->isInstantiationDependent() &&
7935 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007936 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007937 if (Val.isInvalid())
7938 return nullptr;
7939
Richard Smith03a4aa32016-06-23 19:02:52 +00007940 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007941 }
7942
7943 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7944}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007945ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7946 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007947 if (!Op)
7948 return ExprError();
7949
7950 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7951 public:
7952 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007953 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007954 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7955 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007956 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7957 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007958 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7959 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007960 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7961 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007962 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7963 QualType T,
7964 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007965 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7966 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007967 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7968 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007969 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007970 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007971 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007972 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7973 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007974 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7975 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007976 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7977 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007978 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007979 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007980 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007981 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7982 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007983 llvm_unreachable("conversion functions are permitted");
7984 }
7985 } ConvertDiagnoser;
7986 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7987}
7988
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007989static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007990 OpenMPClauseKind CKind,
7991 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007992 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7993 !ValExpr->isInstantiationDependent()) {
7994 SourceLocation Loc = ValExpr->getExprLoc();
7995 ExprResult Value =
7996 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7997 if (Value.isInvalid())
7998 return false;
7999
8000 ValExpr = Value.get();
8001 // The expression must evaluate to a non-negative integer value.
8002 llvm::APSInt Result;
8003 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008004 Result.isSigned() &&
8005 !((!StrictlyPositive && Result.isNonNegative()) ||
8006 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008007 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008008 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8009 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008010 return false;
8011 }
8012 }
8013 return true;
8014}
8015
Alexey Bataev568a8332014-03-06 06:15:19 +00008016OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8017 SourceLocation StartLoc,
8018 SourceLocation LParenLoc,
8019 SourceLocation EndLoc) {
8020 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008021 Stmt *HelperValStmt = nullptr;
8022 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00008023
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008024 // OpenMP [2.5, Restrictions]
8025 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008026 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8027 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008028 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008029
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008030 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8031 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8032 if (CaptureRegion != OMPD_unknown) {
8033 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8034 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8035 HelperValStmt = buildPreInits(Context, Captures);
8036 }
8037
8038 return new (Context) OMPNumThreadsClause(
8039 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008040}
8041
Alexey Bataev62c87d22014-03-21 04:51:18 +00008042ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008043 OpenMPClauseKind CKind,
8044 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008045 if (!E)
8046 return ExprError();
8047 if (E->isValueDependent() || E->isTypeDependent() ||
8048 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008049 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008050 llvm::APSInt Result;
8051 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8052 if (ICE.isInvalid())
8053 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008054 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8055 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008056 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008057 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8058 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008059 return ExprError();
8060 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008061 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8062 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8063 << E->getSourceRange();
8064 return ExprError();
8065 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008066 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8067 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008068 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008069 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008070 return ICE;
8071}
8072
8073OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8074 SourceLocation LParenLoc,
8075 SourceLocation EndLoc) {
8076 // OpenMP [2.8.1, simd construct, Description]
8077 // The parameter of the safelen clause must be a constant
8078 // positive integer expression.
8079 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8080 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008081 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008082 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008083 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008084}
8085
Alexey Bataev66b15b52015-08-21 11:14:16 +00008086OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8087 SourceLocation LParenLoc,
8088 SourceLocation EndLoc) {
8089 // OpenMP [2.8.1, simd construct, Description]
8090 // The parameter of the simdlen clause must be a constant
8091 // positive integer expression.
8092 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8093 if (Simdlen.isInvalid())
8094 return nullptr;
8095 return new (Context)
8096 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8097}
8098
Alexander Musman64d33f12014-06-04 07:53:32 +00008099OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8100 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008101 SourceLocation LParenLoc,
8102 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008103 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008104 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008105 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008106 // The parameter of the collapse clause must be a constant
8107 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008108 ExprResult NumForLoopsResult =
8109 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8110 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008111 return nullptr;
8112 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008113 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008114}
8115
Alexey Bataev10e775f2015-07-30 11:36:16 +00008116OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8117 SourceLocation EndLoc,
8118 SourceLocation LParenLoc,
8119 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008120 // OpenMP [2.7.1, loop construct, Description]
8121 // OpenMP [2.8.1, simd construct, Description]
8122 // OpenMP [2.9.6, distribute construct, Description]
8123 // The parameter of the ordered clause must be a constant
8124 // positive integer expression if any.
8125 if (NumForLoops && LParenLoc.isValid()) {
8126 ExprResult NumForLoopsResult =
8127 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8128 if (NumForLoopsResult.isInvalid())
8129 return nullptr;
8130 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008131 } else
8132 NumForLoops = nullptr;
8133 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008134 return new (Context)
8135 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8136}
8137
Alexey Bataeved09d242014-05-28 05:53:51 +00008138OMPClause *Sema::ActOnOpenMPSimpleClause(
8139 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8140 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008141 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008142 switch (Kind) {
8143 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008144 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008145 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8146 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008147 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008148 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008149 Res = ActOnOpenMPProcBindClause(
8150 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8151 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008152 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008153 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008154 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008155 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008156 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008157 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008158 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008159 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008160 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008161 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008162 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008163 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008164 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008165 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008166 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008167 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008168 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008169 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008170 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008171 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008172 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008173 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008174 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008175 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008176 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008177 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008178 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008179 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008180 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008181 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008182 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008183 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008184 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008185 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008186 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008187 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008188 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008189 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008190 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008191 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008192 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008193 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008194 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008195 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008196 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008197 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008198 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008199 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008200 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008201 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008202 llvm_unreachable("Clause is not allowed.");
8203 }
8204 return Res;
8205}
8206
Alexey Bataev6402bca2015-12-28 07:25:51 +00008207static std::string
8208getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8209 ArrayRef<unsigned> Exclude = llvm::None) {
8210 std::string Values;
8211 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8212 unsigned Skipped = Exclude.size();
8213 auto S = Exclude.begin(), E = Exclude.end();
8214 for (unsigned i = First; i < Last; ++i) {
8215 if (std::find(S, E, i) != E) {
8216 --Skipped;
8217 continue;
8218 }
8219 Values += "'";
8220 Values += getOpenMPSimpleClauseTypeName(K, i);
8221 Values += "'";
8222 if (i == Bound - Skipped)
8223 Values += " or ";
8224 else if (i != Bound + 1 - Skipped)
8225 Values += ", ";
8226 }
8227 return Values;
8228}
8229
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008230OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8231 SourceLocation KindKwLoc,
8232 SourceLocation StartLoc,
8233 SourceLocation LParenLoc,
8234 SourceLocation EndLoc) {
8235 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008236 static_assert(OMPC_DEFAULT_unknown > 0,
8237 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008238 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008239 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8240 /*Last=*/OMPC_DEFAULT_unknown)
8241 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008242 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008243 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008244 switch (Kind) {
8245 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008246 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008247 break;
8248 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008249 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008250 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008251 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008252 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008253 break;
8254 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008255 return new (Context)
8256 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008257}
8258
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008259OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8260 SourceLocation KindKwLoc,
8261 SourceLocation StartLoc,
8262 SourceLocation LParenLoc,
8263 SourceLocation EndLoc) {
8264 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008265 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008266 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8267 /*Last=*/OMPC_PROC_BIND_unknown)
8268 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008269 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008270 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008271 return new (Context)
8272 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008273}
8274
Alexey Bataev56dafe82014-06-20 07:16:17 +00008275OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008276 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008277 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008278 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008279 SourceLocation EndLoc) {
8280 OMPClause *Res = nullptr;
8281 switch (Kind) {
8282 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008283 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8284 assert(Argument.size() == NumberOfElements &&
8285 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008286 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008287 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8288 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8289 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8290 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8291 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008292 break;
8293 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008294 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8295 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8296 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8297 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008298 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008299 case OMPC_dist_schedule:
8300 Res = ActOnOpenMPDistScheduleClause(
8301 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8302 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8303 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008304 case OMPC_defaultmap:
8305 enum { Modifier, DefaultmapKind };
8306 Res = ActOnOpenMPDefaultmapClause(
8307 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8308 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008309 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8310 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008311 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008312 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008313 case OMPC_num_threads:
8314 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008315 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008316 case OMPC_collapse:
8317 case OMPC_default:
8318 case OMPC_proc_bind:
8319 case OMPC_private:
8320 case OMPC_firstprivate:
8321 case OMPC_lastprivate:
8322 case OMPC_shared:
8323 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008324 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008325 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008326 case OMPC_linear:
8327 case OMPC_aligned:
8328 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008329 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008330 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008331 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008332 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008333 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008334 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008335 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008336 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008337 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008338 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008339 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008340 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008341 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008342 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008343 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008344 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008345 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008346 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008347 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008348 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008349 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008350 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008351 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008352 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008353 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008354 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008355 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008356 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008357 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008358 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008359 llvm_unreachable("Clause is not allowed.");
8360 }
8361 return Res;
8362}
8363
Alexey Bataev6402bca2015-12-28 07:25:51 +00008364static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8365 OpenMPScheduleClauseModifier M2,
8366 SourceLocation M1Loc, SourceLocation M2Loc) {
8367 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8368 SmallVector<unsigned, 2> Excluded;
8369 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8370 Excluded.push_back(M2);
8371 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8372 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8373 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8374 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8375 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8376 << getListOfPossibleValues(OMPC_schedule,
8377 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8378 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8379 Excluded)
8380 << getOpenMPClauseName(OMPC_schedule);
8381 return true;
8382 }
8383 return false;
8384}
8385
Alexey Bataev56dafe82014-06-20 07:16:17 +00008386OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008387 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008388 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008389 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8390 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8391 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8392 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8393 return nullptr;
8394 // OpenMP, 2.7.1, Loop Construct, Restrictions
8395 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8396 // but not both.
8397 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8398 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8399 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8400 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8401 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8402 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8403 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8404 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8405 return nullptr;
8406 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008407 if (Kind == OMPC_SCHEDULE_unknown) {
8408 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008409 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8410 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8411 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8412 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8413 Exclude);
8414 } else {
8415 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8416 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008417 }
8418 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8419 << Values << getOpenMPClauseName(OMPC_schedule);
8420 return nullptr;
8421 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008422 // OpenMP, 2.7.1, Loop Construct, Restrictions
8423 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8424 // schedule(guided).
8425 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8426 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8427 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8428 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8429 diag::err_omp_schedule_nonmonotonic_static);
8430 return nullptr;
8431 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008432 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008433 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008434 if (ChunkSize) {
8435 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8436 !ChunkSize->isInstantiationDependent() &&
8437 !ChunkSize->containsUnexpandedParameterPack()) {
8438 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8439 ExprResult Val =
8440 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8441 if (Val.isInvalid())
8442 return nullptr;
8443
8444 ValExpr = Val.get();
8445
8446 // OpenMP [2.7.1, Restrictions]
8447 // chunk_size must be a loop invariant integer expression with a positive
8448 // value.
8449 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008450 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8451 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8452 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008453 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008454 return nullptr;
8455 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008456 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
8457 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008458 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8459 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8460 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008461 }
8462 }
8463 }
8464
Alexey Bataev6402bca2015-12-28 07:25:51 +00008465 return new (Context)
8466 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008467 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008468}
8469
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008470OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8471 SourceLocation StartLoc,
8472 SourceLocation EndLoc) {
8473 OMPClause *Res = nullptr;
8474 switch (Kind) {
8475 case OMPC_ordered:
8476 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8477 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008478 case OMPC_nowait:
8479 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8480 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008481 case OMPC_untied:
8482 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8483 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008484 case OMPC_mergeable:
8485 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8486 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008487 case OMPC_read:
8488 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8489 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008490 case OMPC_write:
8491 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8492 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008493 case OMPC_update:
8494 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8495 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008496 case OMPC_capture:
8497 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8498 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008499 case OMPC_seq_cst:
8500 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8501 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008502 case OMPC_threads:
8503 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8504 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008505 case OMPC_simd:
8506 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8507 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008508 case OMPC_nogroup:
8509 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8510 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008511 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008512 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008513 case OMPC_num_threads:
8514 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008515 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008516 case OMPC_collapse:
8517 case OMPC_schedule:
8518 case OMPC_private:
8519 case OMPC_firstprivate:
8520 case OMPC_lastprivate:
8521 case OMPC_shared:
8522 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008523 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008524 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008525 case OMPC_linear:
8526 case OMPC_aligned:
8527 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008528 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008529 case OMPC_default:
8530 case OMPC_proc_bind:
8531 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008532 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008533 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008534 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008535 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008536 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008537 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008538 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008539 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008540 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008541 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008542 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008543 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008544 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008545 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008546 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008547 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008548 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008549 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008550 llvm_unreachable("Clause is not allowed.");
8551 }
8552 return Res;
8553}
8554
Alexey Bataev236070f2014-06-20 11:19:47 +00008555OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8556 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008557 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008558 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8559}
8560
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008561OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8562 SourceLocation EndLoc) {
8563 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8564}
8565
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008566OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8567 SourceLocation EndLoc) {
8568 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8569}
8570
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008571OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8572 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008573 return new (Context) OMPReadClause(StartLoc, EndLoc);
8574}
8575
Alexey Bataevdea47612014-07-23 07:46:59 +00008576OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8577 SourceLocation EndLoc) {
8578 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8579}
8580
Alexey Bataev67a4f222014-07-23 10:25:33 +00008581OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8582 SourceLocation EndLoc) {
8583 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8584}
8585
Alexey Bataev459dec02014-07-24 06:46:57 +00008586OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8587 SourceLocation EndLoc) {
8588 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8589}
8590
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008591OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8592 SourceLocation EndLoc) {
8593 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8594}
8595
Alexey Bataev346265e2015-09-25 10:37:12 +00008596OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8597 SourceLocation EndLoc) {
8598 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8599}
8600
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008601OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8602 SourceLocation EndLoc) {
8603 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8604}
8605
Alexey Bataevb825de12015-12-07 10:51:44 +00008606OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8607 SourceLocation EndLoc) {
8608 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8609}
8610
Alexey Bataevc5e02582014-06-16 07:08:35 +00008611OMPClause *Sema::ActOnOpenMPVarListClause(
8612 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8613 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8614 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008615 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008616 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8617 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8618 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008619 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008620 switch (Kind) {
8621 case OMPC_private:
8622 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8623 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008624 case OMPC_firstprivate:
8625 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8626 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008627 case OMPC_lastprivate:
8628 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8629 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008630 case OMPC_shared:
8631 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8632 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008633 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008634 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8635 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008636 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008637 case OMPC_task_reduction:
8638 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8639 EndLoc, ReductionIdScopeSpec,
8640 ReductionId);
8641 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008642 case OMPC_in_reduction:
8643 Res =
8644 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8645 EndLoc, ReductionIdScopeSpec, ReductionId);
8646 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008647 case OMPC_linear:
8648 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008649 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008650 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008651 case OMPC_aligned:
8652 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8653 ColonLoc, EndLoc);
8654 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008655 case OMPC_copyin:
8656 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8657 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008658 case OMPC_copyprivate:
8659 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8660 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008661 case OMPC_flush:
8662 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8663 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008664 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008665 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008666 StartLoc, LParenLoc, EndLoc);
8667 break;
8668 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008669 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8670 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8671 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008672 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008673 case OMPC_to:
8674 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8675 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008676 case OMPC_from:
8677 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8678 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008679 case OMPC_use_device_ptr:
8680 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8681 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008682 case OMPC_is_device_ptr:
8683 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8684 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008685 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008686 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008687 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008688 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008689 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008690 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008691 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008692 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008693 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008694 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008695 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008696 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008697 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008698 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008699 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008700 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008701 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008702 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008703 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008704 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008705 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008706 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008707 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008708 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008709 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008710 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008711 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008712 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008713 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008714 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008715 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008716 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008717 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008718 llvm_unreachable("Clause is not allowed.");
8719 }
8720 return Res;
8721}
8722
Alexey Bataev90c228f2016-02-08 09:29:13 +00008723ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008724 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008725 ExprResult Res = BuildDeclRefExpr(
8726 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8727 if (!Res.isUsable())
8728 return ExprError();
8729 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8730 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8731 if (!Res.isUsable())
8732 return ExprError();
8733 }
8734 if (VK != VK_LValue && Res.get()->isGLValue()) {
8735 Res = DefaultLvalueConversion(Res.get());
8736 if (!Res.isUsable())
8737 return ExprError();
8738 }
8739 return Res;
8740}
8741
Alexey Bataev60da77e2016-02-29 05:54:20 +00008742static std::pair<ValueDecl *, bool>
8743getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8744 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008745 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8746 RefExpr->containsUnexpandedParameterPack())
8747 return std::make_pair(nullptr, true);
8748
Alexey Bataevd985eda2016-02-10 11:29:16 +00008749 // OpenMP [3.1, C/C++]
8750 // A list item is a variable name.
8751 // OpenMP [2.9.3.3, Restrictions, p.1]
8752 // A variable that is part of another variable (as an array or
8753 // structure element) cannot appear in a private clause.
8754 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008755 enum {
8756 NoArrayExpr = -1,
8757 ArraySubscript = 0,
8758 OMPArraySection = 1
8759 } IsArrayExpr = NoArrayExpr;
8760 if (AllowArraySection) {
8761 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8762 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8763 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8764 Base = TempASE->getBase()->IgnoreParenImpCasts();
8765 RefExpr = Base;
8766 IsArrayExpr = ArraySubscript;
8767 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8768 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8769 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8770 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8771 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8772 Base = TempASE->getBase()->IgnoreParenImpCasts();
8773 RefExpr = Base;
8774 IsArrayExpr = OMPArraySection;
8775 }
8776 }
8777 ELoc = RefExpr->getExprLoc();
8778 ERange = RefExpr->getSourceRange();
8779 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008780 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8781 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8782 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8783 (S.getCurrentThisType().isNull() || !ME ||
8784 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8785 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008786 if (IsArrayExpr != NoArrayExpr)
8787 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8788 << ERange;
8789 else {
8790 S.Diag(ELoc,
8791 AllowArraySection
8792 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8793 : diag::err_omp_expected_var_name_member_expr)
8794 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8795 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008796 return std::make_pair(nullptr, false);
8797 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008798 return std::make_pair(
8799 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008800}
8801
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008802OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8803 SourceLocation StartLoc,
8804 SourceLocation LParenLoc,
8805 SourceLocation EndLoc) {
8806 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008807 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008808 for (auto &RefExpr : VarList) {
8809 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008810 SourceLocation ELoc;
8811 SourceRange ERange;
8812 Expr *SimpleRefExpr = RefExpr;
8813 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008814 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008815 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008816 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008817 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008818 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008819 ValueDecl *D = Res.first;
8820 if (!D)
8821 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008822
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008823 QualType Type = D->getType();
8824 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008825
8826 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8827 // A variable that appears in a private clause must not have an incomplete
8828 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008829 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008830 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008831 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008832
Alexey Bataev758e55e2013-09-06 18:03:48 +00008833 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8834 // in a Construct]
8835 // Variables with the predetermined data-sharing attributes may not be
8836 // listed in data-sharing attributes clauses, except for the cases
8837 // listed below. For these exceptions only, listing a predetermined
8838 // variable in a data-sharing attribute clause is allowed and overrides
8839 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008840 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008841 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008842 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8843 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008844 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008845 continue;
8846 }
8847
Kelvin Libf594a52016-12-17 05:48:59 +00008848 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008849 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008850 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008851 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008852 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8853 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008854 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008855 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008856 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008857 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008858 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008859 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008860 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008861 continue;
8862 }
8863
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008864 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8865 // A list item cannot appear in both a map clause and a data-sharing
8866 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008867 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008868 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008869 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008870 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008871 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008872 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008873 CurrDir == OMPD_target_parallel_for_simd ||
8874 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008875 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008876 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008877 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008878 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8879 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8880 ConflictKind = WhereFoundClauseKind;
8881 return true;
8882 })) {
8883 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008884 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008885 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008886 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008887 ReportOriginalDSA(*this, DSAStack, D, DVar);
8888 continue;
8889 }
8890 }
8891
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008892 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8893 // A variable of class type (or array thereof) that appears in a private
8894 // clause requires an accessible, unambiguous default constructor for the
8895 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008896 // Generate helper private variable and initialize it with the default
8897 // value. The address of the original variable is replaced by the address of
8898 // the new private variable in CodeGen. This new variable is not added to
8899 // IdResolver, so the code in the OpenMP region uses original variable for
8900 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008901 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008902 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8903 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008904 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008905 if (VDPrivate->isInvalidDecl())
8906 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008907 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008908 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008909
Alexey Bataev90c228f2016-02-08 09:29:13 +00008910 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008911 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008912 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008913 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008914 Vars.push_back((VD || CurContext->isDependentContext())
8915 ? RefExpr->IgnoreParens()
8916 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008917 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008918 }
8919
Alexey Bataeved09d242014-05-28 05:53:51 +00008920 if (Vars.empty())
8921 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008922
Alexey Bataev03b340a2014-10-21 03:16:40 +00008923 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8924 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008925}
8926
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008927namespace {
8928class DiagsUninitializedSeveretyRAII {
8929private:
8930 DiagnosticsEngine &Diags;
8931 SourceLocation SavedLoc;
8932 bool IsIgnored;
8933
8934public:
8935 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8936 bool IsIgnored)
8937 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8938 if (!IsIgnored) {
8939 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8940 /*Map*/ diag::Severity::Ignored, Loc);
8941 }
8942 }
8943 ~DiagsUninitializedSeveretyRAII() {
8944 if (!IsIgnored)
8945 Diags.popMappings(SavedLoc);
8946 }
8947};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008948}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008949
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008950OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8951 SourceLocation StartLoc,
8952 SourceLocation LParenLoc,
8953 SourceLocation EndLoc) {
8954 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008955 SmallVector<Expr *, 8> PrivateCopies;
8956 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008957 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008958 bool IsImplicitClause =
8959 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8960 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8961
Alexey Bataeved09d242014-05-28 05:53:51 +00008962 for (auto &RefExpr : VarList) {
8963 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008964 SourceLocation ELoc;
8965 SourceRange ERange;
8966 Expr *SimpleRefExpr = RefExpr;
8967 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008968 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008969 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008970 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008971 PrivateCopies.push_back(nullptr);
8972 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008973 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008974 ValueDecl *D = Res.first;
8975 if (!D)
8976 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008977
Alexey Bataev60da77e2016-02-29 05:54:20 +00008978 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008979 QualType Type = D->getType();
8980 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008981
8982 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8983 // A variable that appears in a private clause must not have an incomplete
8984 // type or a reference type.
8985 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008986 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008987 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008988 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008989
8990 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8991 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008992 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008993 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008994 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008995
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008996 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008997 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008998 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008999 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009000 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009001 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009002 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009003 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9004 // A list item that specifies a given variable may not appear in more
9005 // than one clause on the same directive, except that a variable may be
9006 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009007 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9008 // A list item may appear in a firstprivate or lastprivate clause but not
9009 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009010 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009011 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
9012 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009013 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009014 << getOpenMPClauseName(DVar.CKind)
9015 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009016 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009017 continue;
9018 }
9019
9020 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9021 // in a Construct]
9022 // Variables with the predetermined data-sharing attributes may not be
9023 // listed in data-sharing attributes clauses, except for the cases
9024 // listed below. For these exceptions only, listing a predetermined
9025 // variable in a data-sharing attribute clause is allowed and overrides
9026 // the variable's predetermined data-sharing attributes.
9027 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9028 // in a Construct, C/C++, p.2]
9029 // Variables with const-qualified type having no mutable member may be
9030 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009031 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009032 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9033 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009034 << getOpenMPClauseName(DVar.CKind)
9035 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009036 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009037 continue;
9038 }
9039
9040 // OpenMP [2.9.3.4, Restrictions, p.2]
9041 // A list item that is private within a parallel region must not appear
9042 // in a firstprivate clause on a worksharing construct if any of the
9043 // worksharing regions arising from the worksharing construct ever bind
9044 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009045 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9046 // A list item that is private within a teams region must not appear in a
9047 // firstprivate clause on a distribute construct if any of the distribute
9048 // regions arising from the distribute construct ever bind to any of the
9049 // teams regions arising from the teams construct.
9050 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9051 // A list item that appears in a reduction clause of a teams construct
9052 // must not appear in a firstprivate clause on a distribute construct if
9053 // any of the distribute regions arising from the distribute construct
9054 // ever bind to any of the teams regions arising from the teams construct.
9055 if ((isOpenMPWorksharingDirective(CurrDir) ||
9056 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009057 !isOpenMPParallelDirective(CurrDir) &&
9058 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009059 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009060 if (DVar.CKind != OMPC_shared &&
9061 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009062 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009063 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009064 Diag(ELoc, diag::err_omp_required_access)
9065 << getOpenMPClauseName(OMPC_firstprivate)
9066 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009067 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009068 continue;
9069 }
9070 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009071 // OpenMP [2.9.3.4, Restrictions, p.3]
9072 // A list item that appears in a reduction clause of a parallel construct
9073 // must not appear in a firstprivate clause on a worksharing or task
9074 // construct if any of the worksharing or task regions arising from the
9075 // worksharing or task construct ever bind to any of the parallel regions
9076 // arising from the parallel construct.
9077 // OpenMP [2.9.3.4, Restrictions, p.4]
9078 // A list item that appears in a reduction clause in worksharing
9079 // construct must not appear in a firstprivate clause in a task construct
9080 // encountered during execution of any of the worksharing regions arising
9081 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009082 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009083 DVar = DSAStack->hasInnermostDSA(
9084 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9085 [](OpenMPDirectiveKind K) -> bool {
9086 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009087 isOpenMPWorksharingDirective(K) ||
9088 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009089 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009090 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009091 if (DVar.CKind == OMPC_reduction &&
9092 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009093 isOpenMPWorksharingDirective(DVar.DKind) ||
9094 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009095 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9096 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009097 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009098 continue;
9099 }
9100 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009101
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009102 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9103 // A list item cannot appear in both a map clause and a data-sharing
9104 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009105 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00009106 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009107 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009108 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009109 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009110 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009111 CurrDir == OMPD_target_parallel_for_simd ||
9112 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009113 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009114 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009115 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009116 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9117 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9118 ConflictKind = WhereFoundClauseKind;
9119 return true;
9120 })) {
9121 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009122 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009123 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009124 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9125 ReportOriginalDSA(*this, DSAStack, D, DVar);
9126 continue;
9127 }
9128 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009129 }
9130
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009131 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009132 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009133 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009134 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9135 << getOpenMPClauseName(OMPC_firstprivate) << Type
9136 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9137 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009138 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009139 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009140 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009141 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009142 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009143 continue;
9144 }
9145
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009146 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009147 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9148 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009149 // Generate helper private variable and initialize it with the value of the
9150 // original variable. The address of the original variable is replaced by
9151 // the address of the new private variable in the CodeGen. This new variable
9152 // is not added to IdResolver, so the code in the OpenMP region uses
9153 // original variable for proper diagnostics and variable capturing.
9154 Expr *VDInitRefExpr = nullptr;
9155 // For arrays generate initializer for single element and replace it by the
9156 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009157 if (Type->isArrayType()) {
9158 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009159 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009160 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009161 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009162 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009163 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009164 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009165 InitializedEntity Entity =
9166 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009167 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9168
9169 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9170 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9171 if (Result.isInvalid())
9172 VDPrivate->setInvalidDecl();
9173 else
9174 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009175 // Remove temp variable declaration.
9176 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009177 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009178 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9179 ".firstprivate.temp");
9180 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9181 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009182 AddInitializerToDecl(VDPrivate,
9183 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009184 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009185 }
9186 if (VDPrivate->isInvalidDecl()) {
9187 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009188 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009189 diag::note_omp_task_predetermined_firstprivate_here);
9190 }
9191 continue;
9192 }
9193 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009194 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009195 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9196 RefExpr->getExprLoc());
9197 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009198 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009199 if (TopDVar.CKind == OMPC_lastprivate)
9200 Ref = TopDVar.PrivateCopy;
9201 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009202 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009203 if (!IsOpenMPCapturedDecl(D))
9204 ExprCaptures.push_back(Ref->getDecl());
9205 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009206 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009207 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009208 Vars.push_back((VD || CurContext->isDependentContext())
9209 ? RefExpr->IgnoreParens()
9210 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009211 PrivateCopies.push_back(VDPrivateRefExpr);
9212 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009213 }
9214
Alexey Bataeved09d242014-05-28 05:53:51 +00009215 if (Vars.empty())
9216 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009217
9218 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009219 Vars, PrivateCopies, Inits,
9220 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009221}
9222
Alexander Musman1bb328c2014-06-04 13:06:39 +00009223OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9224 SourceLocation StartLoc,
9225 SourceLocation LParenLoc,
9226 SourceLocation EndLoc) {
9227 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009228 SmallVector<Expr *, 8> SrcExprs;
9229 SmallVector<Expr *, 8> DstExprs;
9230 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009231 SmallVector<Decl *, 4> ExprCaptures;
9232 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009233 for (auto &RefExpr : VarList) {
9234 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009235 SourceLocation ELoc;
9236 SourceRange ERange;
9237 Expr *SimpleRefExpr = RefExpr;
9238 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009239 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009240 // It will be analyzed later.
9241 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009242 SrcExprs.push_back(nullptr);
9243 DstExprs.push_back(nullptr);
9244 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009245 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009246 ValueDecl *D = Res.first;
9247 if (!D)
9248 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009249
Alexey Bataev74caaf22016-02-20 04:09:36 +00009250 QualType Type = D->getType();
9251 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009252
9253 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9254 // A variable that appears in a lastprivate clause must not have an
9255 // incomplete type or a reference type.
9256 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009257 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009258 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009259 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009260
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009261 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009262 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9263 // in a Construct]
9264 // Variables with the predetermined data-sharing attributes may not be
9265 // listed in data-sharing attributes clauses, except for the cases
9266 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009267 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9268 // A list item may appear in a firstprivate or lastprivate clause but not
9269 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009270 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009271 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009272 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009273 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9274 Diag(ELoc, diag::err_omp_wrong_dsa)
9275 << getOpenMPClauseName(DVar.CKind)
9276 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009277 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009278 continue;
9279 }
9280
Alexey Bataevf29276e2014-06-18 04:14:57 +00009281 // OpenMP [2.14.3.5, Restrictions, p.2]
9282 // A list item that is private within a parallel region, or that appears in
9283 // the reduction clause of a parallel construct, must not appear in a
9284 // lastprivate clause on a worksharing construct if any of the corresponding
9285 // worksharing regions ever binds to any of the corresponding parallel
9286 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009287 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009288 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009289 !isOpenMPParallelDirective(CurrDir) &&
9290 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009291 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009292 if (DVar.CKind != OMPC_shared) {
9293 Diag(ELoc, diag::err_omp_required_access)
9294 << getOpenMPClauseName(OMPC_lastprivate)
9295 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009296 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009297 continue;
9298 }
9299 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009300
Alexander Musman1bb328c2014-06-04 13:06:39 +00009301 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009302 // A variable of class type (or array thereof) that appears in a
9303 // lastprivate clause requires an accessible, unambiguous default
9304 // constructor for the class type, unless the list item is also specified
9305 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009306 // A variable of class type (or array thereof) that appears in a
9307 // lastprivate clause requires an accessible, unambiguous copy assignment
9308 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009309 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009310 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009311 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009312 D->hasAttrs() ? &D->getAttrs() : nullptr);
9313 auto *PseudoSrcExpr =
9314 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009315 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009316 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009317 D->hasAttrs() ? &D->getAttrs() : nullptr);
9318 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009319 // For arrays generate assignment operation for single element and replace
9320 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009321 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009322 PseudoDstExpr, PseudoSrcExpr);
9323 if (AssignmentOp.isInvalid())
9324 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009325 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009326 /*DiscardedValue=*/true);
9327 if (AssignmentOp.isInvalid())
9328 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009329
Alexey Bataev74caaf22016-02-20 04:09:36 +00009330 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009331 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009332 if (TopDVar.CKind == OMPC_firstprivate)
9333 Ref = TopDVar.PrivateCopy;
9334 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009335 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009336 if (!IsOpenMPCapturedDecl(D))
9337 ExprCaptures.push_back(Ref->getDecl());
9338 }
9339 if (TopDVar.CKind == OMPC_firstprivate ||
9340 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009341 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009342 ExprResult RefRes = DefaultLvalueConversion(Ref);
9343 if (!RefRes.isUsable())
9344 continue;
9345 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009346 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9347 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009348 if (!PostUpdateRes.isUsable())
9349 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009350 ExprPostUpdates.push_back(
9351 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009352 }
9353 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009354 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009355 Vars.push_back((VD || CurContext->isDependentContext())
9356 ? RefExpr->IgnoreParens()
9357 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009358 SrcExprs.push_back(PseudoSrcExpr);
9359 DstExprs.push_back(PseudoDstExpr);
9360 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009361 }
9362
9363 if (Vars.empty())
9364 return nullptr;
9365
9366 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009367 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009368 buildPreInits(Context, ExprCaptures),
9369 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009370}
9371
Alexey Bataev758e55e2013-09-06 18:03:48 +00009372OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9373 SourceLocation StartLoc,
9374 SourceLocation LParenLoc,
9375 SourceLocation EndLoc) {
9376 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009377 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009378 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009379 SourceLocation ELoc;
9380 SourceRange ERange;
9381 Expr *SimpleRefExpr = RefExpr;
9382 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009383 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009384 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009385 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009386 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009387 ValueDecl *D = Res.first;
9388 if (!D)
9389 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009390
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009391 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009392 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9393 // in a Construct]
9394 // Variables with the predetermined data-sharing attributes may not be
9395 // listed in data-sharing attributes clauses, except for the cases
9396 // listed below. For these exceptions only, listing a predetermined
9397 // variable in a data-sharing attribute clause is allowed and overrides
9398 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009399 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009400 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9401 DVar.RefExpr) {
9402 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9403 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009404 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009405 continue;
9406 }
9407
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009408 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009409 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009410 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009411 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009412 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9413 ? RefExpr->IgnoreParens()
9414 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009415 }
9416
Alexey Bataeved09d242014-05-28 05:53:51 +00009417 if (Vars.empty())
9418 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009419
9420 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9421}
9422
Alexey Bataevc5e02582014-06-16 07:08:35 +00009423namespace {
9424class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9425 DSAStackTy *Stack;
9426
9427public:
9428 bool VisitDeclRefExpr(DeclRefExpr *E) {
9429 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009430 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009431 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9432 return false;
9433 if (DVar.CKind != OMPC_unknown)
9434 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009435 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9436 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009437 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009438 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009439 return true;
9440 return false;
9441 }
9442 return false;
9443 }
9444 bool VisitStmt(Stmt *S) {
9445 for (auto Child : S->children()) {
9446 if (Child && Visit(Child))
9447 return true;
9448 }
9449 return false;
9450 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009451 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009452};
Alexey Bataev23b69422014-06-18 07:08:49 +00009453} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009454
Alexey Bataev60da77e2016-02-29 05:54:20 +00009455namespace {
9456// Transform MemberExpression for specified FieldDecl of current class to
9457// DeclRefExpr to specified OMPCapturedExprDecl.
9458class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9459 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9460 ValueDecl *Field;
9461 DeclRefExpr *CapturedExpr;
9462
9463public:
9464 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9465 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9466
9467 ExprResult TransformMemberExpr(MemberExpr *E) {
9468 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9469 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009470 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009471 return CapturedExpr;
9472 }
9473 return BaseTransform::TransformMemberExpr(E);
9474 }
9475 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9476};
9477} // namespace
9478
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009479template <typename T>
9480static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9481 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9482 for (auto &Set : Lookups) {
9483 for (auto *D : Set) {
9484 if (auto Res = Gen(cast<ValueDecl>(D)))
9485 return Res;
9486 }
9487 }
9488 return T();
9489}
9490
9491static ExprResult
9492buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9493 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9494 const DeclarationNameInfo &ReductionId, QualType Ty,
9495 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9496 if (ReductionIdScopeSpec.isInvalid())
9497 return ExprError();
9498 SmallVector<UnresolvedSet<8>, 4> Lookups;
9499 if (S) {
9500 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9501 Lookup.suppressDiagnostics();
9502 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9503 auto *D = Lookup.getRepresentativeDecl();
9504 do {
9505 S = S->getParent();
9506 } while (S && !S->isDeclScope(D));
9507 if (S)
9508 S = S->getParent();
9509 Lookups.push_back(UnresolvedSet<8>());
9510 Lookups.back().append(Lookup.begin(), Lookup.end());
9511 Lookup.clear();
9512 }
9513 } else if (auto *ULE =
9514 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9515 Lookups.push_back(UnresolvedSet<8>());
9516 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009517 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009518 if (D == PrevD)
9519 Lookups.push_back(UnresolvedSet<8>());
9520 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9521 Lookups.back().addDecl(DRD);
9522 PrevD = D;
9523 }
9524 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009525 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9526 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009527 Ty->containsUnexpandedParameterPack() ||
9528 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9529 return !D->isInvalidDecl() &&
9530 (D->getType()->isDependentType() ||
9531 D->getType()->isInstantiationDependentType() ||
9532 D->getType()->containsUnexpandedParameterPack());
9533 })) {
9534 UnresolvedSet<8> ResSet;
9535 for (auto &Set : Lookups) {
9536 ResSet.append(Set.begin(), Set.end());
9537 // The last item marks the end of all declarations at the specified scope.
9538 ResSet.addDecl(Set[Set.size() - 1]);
9539 }
9540 return UnresolvedLookupExpr::Create(
9541 SemaRef.Context, /*NamingClass=*/nullptr,
9542 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9543 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9544 }
9545 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9546 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9547 if (!D->isInvalidDecl() &&
9548 SemaRef.Context.hasSameType(D->getType(), Ty))
9549 return D;
9550 return nullptr;
9551 }))
9552 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9553 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9554 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9555 if (!D->isInvalidDecl() &&
9556 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9557 !Ty.isMoreQualifiedThan(D->getType()))
9558 return D;
9559 return nullptr;
9560 })) {
9561 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9562 /*DetectVirtual=*/false);
9563 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9564 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9565 VD->getType().getUnqualifiedType()))) {
9566 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9567 /*DiagID=*/0) !=
9568 Sema::AR_inaccessible) {
9569 SemaRef.BuildBasePathArray(Paths, BasePath);
9570 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9571 }
9572 }
9573 }
9574 }
9575 if (ReductionIdScopeSpec.isSet()) {
9576 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9577 return ExprError();
9578 }
9579 return ExprEmpty();
9580}
9581
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009582namespace {
9583/// Data for the reduction-based clauses.
9584struct ReductionData {
9585 /// List of original reduction items.
9586 SmallVector<Expr *, 8> Vars;
9587 /// List of private copies of the reduction items.
9588 SmallVector<Expr *, 8> Privates;
9589 /// LHS expressions for the reduction_op expressions.
9590 SmallVector<Expr *, 8> LHSs;
9591 /// RHS expressions for the reduction_op expressions.
9592 SmallVector<Expr *, 8> RHSs;
9593 /// Reduction operation expression.
9594 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009595 /// Taskgroup descriptors for the corresponding reduction items in
9596 /// in_reduction clauses.
9597 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009598 /// List of captures for clause.
9599 SmallVector<Decl *, 4> ExprCaptures;
9600 /// List of postupdate expressions.
9601 SmallVector<Expr *, 4> ExprPostUpdates;
9602 ReductionData() = delete;
9603 /// Reserves required memory for the reduction data.
9604 ReductionData(unsigned Size) {
9605 Vars.reserve(Size);
9606 Privates.reserve(Size);
9607 LHSs.reserve(Size);
9608 RHSs.reserve(Size);
9609 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009610 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009611 ExprCaptures.reserve(Size);
9612 ExprPostUpdates.reserve(Size);
9613 }
9614 /// Stores reduction item and reduction operation only (required for dependent
9615 /// reduction item).
9616 void push(Expr *Item, Expr *ReductionOp) {
9617 Vars.emplace_back(Item);
9618 Privates.emplace_back(nullptr);
9619 LHSs.emplace_back(nullptr);
9620 RHSs.emplace_back(nullptr);
9621 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009622 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009623 }
9624 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009625 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9626 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009627 Vars.emplace_back(Item);
9628 Privates.emplace_back(Private);
9629 LHSs.emplace_back(LHS);
9630 RHSs.emplace_back(RHS);
9631 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009632 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009633 }
9634};
9635} // namespace
9636
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009637static bool CheckOMPArraySectionConstantForReduction(
9638 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9639 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9640 const Expr *Length = OASE->getLength();
9641 if (Length == nullptr) {
9642 // For array sections of the form [1:] or [:], we would need to analyze
9643 // the lower bound...
9644 if (OASE->getColonLoc().isValid())
9645 return false;
9646
9647 // This is an array subscript which has implicit length 1!
9648 SingleElement = true;
9649 ArraySizes.push_back(llvm::APSInt::get(1));
9650 } else {
9651 llvm::APSInt ConstantLengthValue;
9652 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9653 return false;
9654
9655 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9656 ArraySizes.push_back(ConstantLengthValue);
9657 }
9658
9659 // Get the base of this array section and walk up from there.
9660 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9661
9662 // We require length = 1 for all array sections except the right-most to
9663 // guarantee that the memory region is contiguous and has no holes in it.
9664 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9665 Length = TempOASE->getLength();
9666 if (Length == nullptr) {
9667 // For array sections of the form [1:] or [:], we would need to analyze
9668 // the lower bound...
9669 if (OASE->getColonLoc().isValid())
9670 return false;
9671
9672 // This is an array subscript which has implicit length 1!
9673 ArraySizes.push_back(llvm::APSInt::get(1));
9674 } else {
9675 llvm::APSInt ConstantLengthValue;
9676 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9677 ConstantLengthValue.getSExtValue() != 1)
9678 return false;
9679
9680 ArraySizes.push_back(ConstantLengthValue);
9681 }
9682 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9683 }
9684
9685 // If we have a single element, we don't need to add the implicit lengths.
9686 if (!SingleElement) {
9687 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9688 // Has implicit length 1!
9689 ArraySizes.push_back(llvm::APSInt::get(1));
9690 Base = TempASE->getBase()->IgnoreParenImpCasts();
9691 }
9692 }
9693
9694 // This array section can be privatized as a single value or as a constant
9695 // sized array.
9696 return true;
9697}
9698
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009699static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009700 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9701 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9702 SourceLocation ColonLoc, SourceLocation EndLoc,
9703 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009704 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009705 auto DN = ReductionId.getName();
9706 auto OOK = DN.getCXXOverloadedOperator();
9707 BinaryOperatorKind BOK = BO_Comma;
9708
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009709 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009710 // OpenMP [2.14.3.6, reduction clause]
9711 // C
9712 // reduction-identifier is either an identifier or one of the following
9713 // operators: +, -, *, &, |, ^, && and ||
9714 // C++
9715 // reduction-identifier is either an id-expression or one of the following
9716 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009717 switch (OOK) {
9718 case OO_Plus:
9719 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009720 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009721 break;
9722 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009723 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009724 break;
9725 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009726 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009727 break;
9728 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009729 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009730 break;
9731 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009732 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009733 break;
9734 case OO_AmpAmp:
9735 BOK = BO_LAnd;
9736 break;
9737 case OO_PipePipe:
9738 BOK = BO_LOr;
9739 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009740 case OO_New:
9741 case OO_Delete:
9742 case OO_Array_New:
9743 case OO_Array_Delete:
9744 case OO_Slash:
9745 case OO_Percent:
9746 case OO_Tilde:
9747 case OO_Exclaim:
9748 case OO_Equal:
9749 case OO_Less:
9750 case OO_Greater:
9751 case OO_LessEqual:
9752 case OO_GreaterEqual:
9753 case OO_PlusEqual:
9754 case OO_MinusEqual:
9755 case OO_StarEqual:
9756 case OO_SlashEqual:
9757 case OO_PercentEqual:
9758 case OO_CaretEqual:
9759 case OO_AmpEqual:
9760 case OO_PipeEqual:
9761 case OO_LessLess:
9762 case OO_GreaterGreater:
9763 case OO_LessLessEqual:
9764 case OO_GreaterGreaterEqual:
9765 case OO_EqualEqual:
9766 case OO_ExclaimEqual:
9767 case OO_PlusPlus:
9768 case OO_MinusMinus:
9769 case OO_Comma:
9770 case OO_ArrowStar:
9771 case OO_Arrow:
9772 case OO_Call:
9773 case OO_Subscript:
9774 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009775 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009776 case NUM_OVERLOADED_OPERATORS:
9777 llvm_unreachable("Unexpected reduction identifier");
9778 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009779 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009780 if (II->isStr("max"))
9781 BOK = BO_GT;
9782 else if (II->isStr("min"))
9783 BOK = BO_LT;
9784 }
9785 break;
9786 }
9787 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009788 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009789 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009790 else
9791 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009792 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009793
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009794 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9795 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009796 for (auto RefExpr : VarList) {
9797 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009798 // OpenMP [2.1, C/C++]
9799 // A list item is a variable or array section, subject to the restrictions
9800 // specified in Section 2.4 on page 42 and in each of the sections
9801 // describing clauses and directives for which a list appears.
9802 // OpenMP [2.14.3.3, Restrictions, p.1]
9803 // A variable that is part of another variable (as an array or
9804 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009805 if (!FirstIter && IR != ER)
9806 ++IR;
9807 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009808 SourceLocation ELoc;
9809 SourceRange ERange;
9810 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009811 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009812 /*AllowArraySection=*/true);
9813 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009814 // Try to find 'declare reduction' corresponding construct before using
9815 // builtin/overloaded operators.
9816 QualType Type = Context.DependentTy;
9817 CXXCastPath BasePath;
9818 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009819 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009820 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009821 Expr *ReductionOp = nullptr;
9822 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009823 (DeclareReductionRef.isUnset() ||
9824 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009825 ReductionOp = DeclareReductionRef.get();
9826 // It will be analyzed later.
9827 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009828 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009829 ValueDecl *D = Res.first;
9830 if (!D)
9831 continue;
9832
Alexey Bataev88202be2017-07-27 13:20:36 +00009833 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009834 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009835 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9836 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9837 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009838 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009839 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009840 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9841 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9842 Type = ATy->getElementType();
9843 else
9844 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009845 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009846 } else
9847 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9848 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009849
Alexey Bataevc5e02582014-06-16 07:08:35 +00009850 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9851 // A variable that appears in a private clause must not have an incomplete
9852 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009853 if (S.RequireCompleteType(ELoc, Type,
9854 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009855 continue;
9856 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009857 // A list item that appears in a reduction clause must not be
9858 // const-qualified.
9859 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009860 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009861 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009862 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9863 VarDecl::DeclarationOnly;
9864 S.Diag(D->getLocation(),
9865 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009866 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009867 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009868 continue;
9869 }
9870 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9871 // If a list-item is a reference type then it must bind to the same object
9872 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009873 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009874 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009875 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009876 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009877 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009878 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9879 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009880 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009881 continue;
9882 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009883 }
9884 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009885
Alexey Bataevc5e02582014-06-16 07:08:35 +00009886 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9887 // in a Construct]
9888 // Variables with the predetermined data-sharing attributes may not be
9889 // listed in data-sharing attributes clauses, except for the cases
9890 // listed below. For these exceptions only, listing a predetermined
9891 // variable in a data-sharing attribute clause is allowed and overrides
9892 // the variable's predetermined data-sharing attributes.
9893 // OpenMP [2.14.3.6, Restrictions, p.3]
9894 // Any number of reduction clauses can be specified on the directive,
9895 // but a list item can appear only once in the reduction clauses for that
9896 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009897 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009898 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009899 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009900 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009901 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009902 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009903 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009904 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009905 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009906 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009907 << getOpenMPClauseName(DVar.CKind)
9908 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009909 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009910 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009911 }
9912
9913 // OpenMP [2.14.3.6, Restrictions, p.1]
9914 // A list item that appears in a reduction clause of a worksharing
9915 // construct must be shared in the parallel regions to which any of the
9916 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009917 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009918 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009919 !isOpenMPParallelDirective(CurrDir) &&
9920 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009921 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009922 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009923 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009924 << getOpenMPClauseName(OMPC_reduction)
9925 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009926 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009927 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009928 }
9929 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009930
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009931 // Try to find 'declare reduction' corresponding construct before using
9932 // builtin/overloaded operators.
9933 CXXCastPath BasePath;
9934 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009935 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009936 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9937 if (DeclareReductionRef.isInvalid())
9938 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009939 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009940 (DeclareReductionRef.isUnset() ||
9941 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009942 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009943 continue;
9944 }
9945 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9946 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009947 S.Diag(ReductionId.getLocStart(),
9948 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009949 << Type << ReductionIdRange;
9950 continue;
9951 }
9952
9953 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9954 // The type of a list item that appears in a reduction clause must be valid
9955 // for the reduction-identifier. For a max or min reduction in C, the type
9956 // of the list item must be an allowed arithmetic data type: char, int,
9957 // float, double, or _Bool, possibly modified with long, short, signed, or
9958 // unsigned. For a max or min reduction in C++, the type of the list item
9959 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9960 // double, or bool, possibly modified with long, short, signed, or unsigned.
9961 if (DeclareReductionRef.isUnset()) {
9962 if ((BOK == BO_GT || BOK == BO_LT) &&
9963 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009964 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9965 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009966 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009967 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009968 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9969 VarDecl::DeclarationOnly;
9970 S.Diag(D->getLocation(),
9971 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009972 << D;
9973 }
9974 continue;
9975 }
9976 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009977 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009978 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9979 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009980 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009981 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9982 VarDecl::DeclarationOnly;
9983 S.Diag(D->getLocation(),
9984 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009985 << D;
9986 }
9987 continue;
9988 }
9989 }
9990
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009991 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009992 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009993 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009994 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009995 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009996 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009997
9998 // Try if we can determine constant lengths for all array sections and avoid
9999 // the VLA.
10000 bool ConstantLengthOASE = false;
10001 if (OASE) {
10002 bool SingleElement;
10003 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10004 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10005 Context, OASE, SingleElement, ArraySizes);
10006
10007 // If we don't have a single element, we must emit a constant array type.
10008 if (ConstantLengthOASE && !SingleElement) {
10009 for (auto &Size : ArraySizes) {
10010 PrivateTy = Context.getConstantArrayType(
10011 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10012 }
10013 }
10014 }
10015
10016 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010017 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010018 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010019 if (!Context.getTargetInfo().isVLASupported() &&
10020 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10021 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10022 S.Diag(ELoc, diag::note_vla_unsupported);
10023 continue;
10024 }
David Majnemer9d168222016-08-05 17:44:54 +000010025 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010026 // Create pseudo array type for private copy. The size for this array will
10027 // be generated during codegen.
10028 // For array subscripts or single variables Private Ty is the same as Type
10029 // (type of the variable or single array element).
10030 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010031 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010032 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010033 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010034 } else if (!ASE && !OASE &&
10035 Context.getAsArrayType(D->getType().getNonReferenceType()))
10036 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010037 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010038 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010039 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010040 // Add initializer for private variable.
10041 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010042 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10043 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010044 if (DeclareReductionRef.isUsable()) {
10045 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10046 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10047 if (DRD->getInitializer()) {
10048 Init = DRDRef;
10049 RHSVD->setInit(DRDRef);
10050 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010051 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010052 } else {
10053 switch (BOK) {
10054 case BO_Add:
10055 case BO_Xor:
10056 case BO_Or:
10057 case BO_LOr:
10058 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10059 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010060 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010061 break;
10062 case BO_Mul:
10063 case BO_LAnd:
10064 if (Type->isScalarType() || Type->isAnyComplexType()) {
10065 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010066 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010067 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010068 break;
10069 case BO_And: {
10070 // '&' reduction op - initializer is '~0'.
10071 QualType OrigType = Type;
10072 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10073 Type = ComplexTy->getElementType();
10074 if (Type->isRealFloatingType()) {
10075 llvm::APFloat InitValue =
10076 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10077 /*isIEEE=*/true);
10078 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10079 Type, ELoc);
10080 } else if (Type->isScalarType()) {
10081 auto Size = Context.getTypeSize(Type);
10082 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10083 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10084 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10085 }
10086 if (Init && OrigType->isAnyComplexType()) {
10087 // Init = 0xFFFF + 0xFFFFi;
10088 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010089 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010090 }
10091 Type = OrigType;
10092 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010093 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010094 case BO_LT:
10095 case BO_GT: {
10096 // 'min' reduction op - initializer is 'Largest representable number in
10097 // the reduction list item type'.
10098 // 'max' reduction op - initializer is 'Least representable number in
10099 // the reduction list item type'.
10100 if (Type->isIntegerType() || Type->isPointerType()) {
10101 bool IsSigned = Type->hasSignedIntegerRepresentation();
10102 auto Size = Context.getTypeSize(Type);
10103 QualType IntTy =
10104 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10105 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010106 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10107 : llvm::APInt::getMinValue(Size)
10108 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10109 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010110 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10111 if (Type->isPointerType()) {
10112 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010113 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010114 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010115 if (CastExpr.isInvalid())
10116 continue;
10117 Init = CastExpr.get();
10118 }
10119 } else if (Type->isRealFloatingType()) {
10120 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10121 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10122 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10123 Type, ELoc);
10124 }
10125 break;
10126 }
10127 case BO_PtrMemD:
10128 case BO_PtrMemI:
10129 case BO_MulAssign:
10130 case BO_Div:
10131 case BO_Rem:
10132 case BO_Sub:
10133 case BO_Shl:
10134 case BO_Shr:
10135 case BO_LE:
10136 case BO_GE:
10137 case BO_EQ:
10138 case BO_NE:
10139 case BO_AndAssign:
10140 case BO_XorAssign:
10141 case BO_OrAssign:
10142 case BO_Assign:
10143 case BO_AddAssign:
10144 case BO_SubAssign:
10145 case BO_DivAssign:
10146 case BO_RemAssign:
10147 case BO_ShlAssign:
10148 case BO_ShrAssign:
10149 case BO_Comma:
10150 llvm_unreachable("Unexpected reduction operation");
10151 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010152 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010153 if (Init && DeclareReductionRef.isUnset())
10154 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10155 else if (!Init)
10156 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010157 if (RHSVD->isInvalidDecl())
10158 continue;
10159 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010160 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10161 << Type << ReductionIdRange;
10162 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10163 VarDecl::DeclarationOnly;
10164 S.Diag(D->getLocation(),
10165 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010166 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010167 continue;
10168 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010169 // Store initializer for single element in private copy. Will be used during
10170 // codegen.
10171 PrivateVD->setInit(RHSVD->getInit());
10172 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010173 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010174 ExprResult ReductionOp;
10175 if (DeclareReductionRef.isUsable()) {
10176 QualType RedTy = DeclareReductionRef.get()->getType();
10177 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010178 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10179 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010180 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010181 LHS = S.DefaultLvalueConversion(LHS.get());
10182 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010183 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10184 CK_UncheckedDerivedToBase, LHS.get(),
10185 &BasePath, LHS.get()->getValueKind());
10186 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10187 CK_UncheckedDerivedToBase, RHS.get(),
10188 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010189 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010190 FunctionProtoType::ExtProtoInfo EPI;
10191 QualType Params[] = {PtrRedTy, PtrRedTy};
10192 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10193 auto *OVE = new (Context) OpaqueValueExpr(
10194 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010195 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010196 Expr *Args[] = {LHS.get(), RHS.get()};
10197 ReductionOp = new (Context)
10198 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10199 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010200 ReductionOp = S.BuildBinOp(
10201 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010202 if (ReductionOp.isUsable()) {
10203 if (BOK != BO_LT && BOK != BO_GT) {
10204 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010205 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10206 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010207 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010208 auto *ConditionalOp = new (Context)
10209 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10210 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010211 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010212 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10213 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010214 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010215 if (ReductionOp.isUsable())
10216 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010217 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010218 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010219 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010220 }
10221
Alexey Bataevfa312f32017-07-21 18:48:21 +000010222 // OpenMP [2.15.4.6, Restrictions, p.2]
10223 // A list item that appears in an in_reduction clause of a task construct
10224 // must appear in a task_reduction clause of a construct associated with a
10225 // taskgroup region that includes the participating task in its taskgroup
10226 // set. The construct associated with the innermost region that meets this
10227 // condition must specify the same reduction-identifier as the in_reduction
10228 // clause.
10229 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010230 SourceRange ParentSR;
10231 BinaryOperatorKind ParentBOK;
10232 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010233 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010234 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010235 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10236 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010237 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010238 Stack->getTopMostTaskgroupReductionData(
10239 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010240 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10241 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10242 if (!IsParentBOK && !IsParentReductionOp) {
10243 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10244 continue;
10245 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010246 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10247 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10248 IsParentReductionOp) {
10249 bool EmitError = true;
10250 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10251 llvm::FoldingSetNodeID RedId, ParentRedId;
10252 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10253 DeclareReductionRef.get()->Profile(RedId, Context,
10254 /*Canonical=*/true);
10255 EmitError = RedId != ParentRedId;
10256 }
10257 if (EmitError) {
10258 S.Diag(ReductionId.getLocStart(),
10259 diag::err_omp_reduction_identifier_mismatch)
10260 << ReductionIdRange << RefExpr->getSourceRange();
10261 S.Diag(ParentSR.getBegin(),
10262 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010263 << ParentSR
10264 << (IsParentBOK ? ParentBOKDSA.RefExpr
10265 : ParentReductionOpDSA.RefExpr)
10266 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010267 continue;
10268 }
10269 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010270 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10271 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010272 }
10273
Alexey Bataev60da77e2016-02-29 05:54:20 +000010274 DeclRefExpr *Ref = nullptr;
10275 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010276 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010277 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010278 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010279 VarsExpr =
10280 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10281 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010282 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010283 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010284 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010285 if (!S.IsOpenMPCapturedDecl(D)) {
10286 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010287 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010288 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010289 if (!RefRes.isUsable())
10290 continue;
10291 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010292 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10293 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010294 if (!PostUpdateRes.isUsable())
10295 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010296 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10297 Stack->getCurrentDirective() == OMPD_taskgroup) {
10298 S.Diag(RefExpr->getExprLoc(),
10299 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010300 << RefExpr->getSourceRange();
10301 continue;
10302 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010303 RD.ExprPostUpdates.emplace_back(
10304 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010305 }
10306 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010307 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010308 // All reduction items are still marked as reduction (to do not increase
10309 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010310 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010311 if (CurrDir == OMPD_taskgroup) {
10312 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010313 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10314 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010315 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010316 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010317 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010318 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10319 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010320 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010321 return RD.Vars.empty();
10322}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010323
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010324OMPClause *Sema::ActOnOpenMPReductionClause(
10325 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10326 SourceLocation ColonLoc, SourceLocation EndLoc,
10327 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10328 ArrayRef<Expr *> UnresolvedReductions) {
10329 ReductionData RD(VarList.size());
10330
Alexey Bataev169d96a2017-07-18 20:17:46 +000010331 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10332 StartLoc, LParenLoc, ColonLoc, EndLoc,
10333 ReductionIdScopeSpec, ReductionId,
10334 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010335 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010336
Alexey Bataevc5e02582014-06-16 07:08:35 +000010337 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010338 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10339 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10340 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10341 buildPreInits(Context, RD.ExprCaptures),
10342 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010343}
10344
Alexey Bataev169d96a2017-07-18 20:17:46 +000010345OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10346 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10347 SourceLocation ColonLoc, SourceLocation EndLoc,
10348 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10349 ArrayRef<Expr *> UnresolvedReductions) {
10350 ReductionData RD(VarList.size());
10351
10352 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10353 VarList, StartLoc, LParenLoc, ColonLoc,
10354 EndLoc, ReductionIdScopeSpec, ReductionId,
10355 UnresolvedReductions, RD))
10356 return nullptr;
10357
10358 return OMPTaskReductionClause::Create(
10359 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10360 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10361 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10362 buildPreInits(Context, RD.ExprCaptures),
10363 buildPostUpdate(*this, RD.ExprPostUpdates));
10364}
10365
Alexey Bataevfa312f32017-07-21 18:48:21 +000010366OMPClause *Sema::ActOnOpenMPInReductionClause(
10367 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10368 SourceLocation ColonLoc, SourceLocation EndLoc,
10369 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10370 ArrayRef<Expr *> UnresolvedReductions) {
10371 ReductionData RD(VarList.size());
10372
10373 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10374 StartLoc, LParenLoc, ColonLoc, EndLoc,
10375 ReductionIdScopeSpec, ReductionId,
10376 UnresolvedReductions, RD))
10377 return nullptr;
10378
10379 return OMPInReductionClause::Create(
10380 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10381 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010382 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010383 buildPreInits(Context, RD.ExprCaptures),
10384 buildPostUpdate(*this, RD.ExprPostUpdates));
10385}
10386
Alexey Bataevecba70f2016-04-12 11:02:11 +000010387bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10388 SourceLocation LinLoc) {
10389 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10390 LinKind == OMPC_LINEAR_unknown) {
10391 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10392 return true;
10393 }
10394 return false;
10395}
10396
10397bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10398 OpenMPLinearClauseKind LinKind,
10399 QualType Type) {
10400 auto *VD = dyn_cast_or_null<VarDecl>(D);
10401 // A variable must not have an incomplete type or a reference type.
10402 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10403 return true;
10404 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10405 !Type->isReferenceType()) {
10406 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10407 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10408 return true;
10409 }
10410 Type = Type.getNonReferenceType();
10411
10412 // A list item must not be const-qualified.
10413 if (Type.isConstant(Context)) {
10414 Diag(ELoc, diag::err_omp_const_variable)
10415 << getOpenMPClauseName(OMPC_linear);
10416 if (D) {
10417 bool IsDecl =
10418 !VD ||
10419 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10420 Diag(D->getLocation(),
10421 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10422 << D;
10423 }
10424 return true;
10425 }
10426
10427 // A list item must be of integral or pointer type.
10428 Type = Type.getUnqualifiedType().getCanonicalType();
10429 const auto *Ty = Type.getTypePtrOrNull();
10430 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10431 !Ty->isPointerType())) {
10432 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10433 if (D) {
10434 bool IsDecl =
10435 !VD ||
10436 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10437 Diag(D->getLocation(),
10438 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10439 << D;
10440 }
10441 return true;
10442 }
10443 return false;
10444}
10445
Alexey Bataev182227b2015-08-20 10:54:39 +000010446OMPClause *Sema::ActOnOpenMPLinearClause(
10447 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10448 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10449 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010450 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010451 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010452 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010453 SmallVector<Decl *, 4> ExprCaptures;
10454 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010455 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010456 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010457 for (auto &RefExpr : VarList) {
10458 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010459 SourceLocation ELoc;
10460 SourceRange ERange;
10461 Expr *SimpleRefExpr = RefExpr;
10462 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10463 /*AllowArraySection=*/false);
10464 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010465 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010466 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010467 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010468 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010469 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010470 ValueDecl *D = Res.first;
10471 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010472 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010473
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010474 QualType Type = D->getType();
10475 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010476
10477 // OpenMP [2.14.3.7, linear clause]
10478 // A list-item cannot appear in more than one linear clause.
10479 // A list-item that appears in a linear clause cannot appear in any
10480 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010481 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010482 if (DVar.RefExpr) {
10483 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10484 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010485 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010486 continue;
10487 }
10488
Alexey Bataevecba70f2016-04-12 11:02:11 +000010489 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010490 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010491 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010492
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010493 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010494 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10495 D->hasAttrs() ? &D->getAttrs() : nullptr);
10496 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010497 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010498 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010499 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010500 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010501 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010502 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10503 if (!IsOpenMPCapturedDecl(D)) {
10504 ExprCaptures.push_back(Ref->getDecl());
10505 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10506 ExprResult RefRes = DefaultLvalueConversion(Ref);
10507 if (!RefRes.isUsable())
10508 continue;
10509 ExprResult PostUpdateRes =
10510 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10511 SimpleRefExpr, RefRes.get());
10512 if (!PostUpdateRes.isUsable())
10513 continue;
10514 ExprPostUpdates.push_back(
10515 IgnoredValueConversions(PostUpdateRes.get()).get());
10516 }
10517 }
10518 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010519 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010520 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010521 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010522 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010523 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010524 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010525 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10526
10527 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010528 Vars.push_back((VD || CurContext->isDependentContext())
10529 ? RefExpr->IgnoreParens()
10530 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010531 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010532 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010533 }
10534
10535 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010536 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010537
10538 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010539 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010540 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10541 !Step->isInstantiationDependent() &&
10542 !Step->containsUnexpandedParameterPack()) {
10543 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010544 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010545 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010546 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010547 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010548
Alexander Musman3276a272015-03-21 10:12:56 +000010549 // Build var to save the step value.
10550 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010551 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010552 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010553 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010554 ExprResult CalcStep =
10555 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010556 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010557
Alexander Musman8dba6642014-04-22 13:09:42 +000010558 // Warn about zero linear step (it would be probably better specified as
10559 // making corresponding variables 'const').
10560 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010561 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10562 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010563 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10564 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010565 if (!IsConstant && CalcStep.isUsable()) {
10566 // Calculate the step beforehand instead of doing this on each iteration.
10567 // (This is not used if the number of iterations may be kfold-ed).
10568 CalcStepExpr = CalcStep.get();
10569 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010570 }
10571
Alexey Bataev182227b2015-08-20 10:54:39 +000010572 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10573 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010574 StepExpr, CalcStepExpr,
10575 buildPreInits(Context, ExprCaptures),
10576 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010577}
10578
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010579static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10580 Expr *NumIterations, Sema &SemaRef,
10581 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010582 // Walk the vars and build update/final expressions for the CodeGen.
10583 SmallVector<Expr *, 8> Updates;
10584 SmallVector<Expr *, 8> Finals;
10585 Expr *Step = Clause.getStep();
10586 Expr *CalcStep = Clause.getCalcStep();
10587 // OpenMP [2.14.3.7, linear clause]
10588 // If linear-step is not specified it is assumed to be 1.
10589 if (Step == nullptr)
10590 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010591 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010592 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010593 }
Alexander Musman3276a272015-03-21 10:12:56 +000010594 bool HasErrors = false;
10595 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010596 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010597 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010598 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010599 SourceLocation ELoc;
10600 SourceRange ERange;
10601 Expr *SimpleRefExpr = RefExpr;
10602 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10603 /*AllowArraySection=*/false);
10604 ValueDecl *D = Res.first;
10605 if (Res.second || !D) {
10606 Updates.push_back(nullptr);
10607 Finals.push_back(nullptr);
10608 HasErrors = true;
10609 continue;
10610 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010611 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010612 Expr *InitExpr = *CurInit;
10613
10614 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010615 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010616 Expr *CapturedRef;
10617 if (LinKind == OMPC_LINEAR_uval)
10618 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10619 else
10620 CapturedRef =
10621 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10622 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10623 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010624
10625 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010626 ExprResult Update;
10627 if (!Info.first) {
10628 Update =
10629 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10630 InitExpr, IV, Step, /* Subtract */ false);
10631 } else
10632 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010633 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10634 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010635
10636 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010637 ExprResult Final;
10638 if (!Info.first) {
10639 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10640 InitExpr, NumIterations, Step,
10641 /* Subtract */ false);
10642 } else
10643 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010644 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10645 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010646
Alexander Musman3276a272015-03-21 10:12:56 +000010647 if (!Update.isUsable() || !Final.isUsable()) {
10648 Updates.push_back(nullptr);
10649 Finals.push_back(nullptr);
10650 HasErrors = true;
10651 } else {
10652 Updates.push_back(Update.get());
10653 Finals.push_back(Final.get());
10654 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010655 ++CurInit;
10656 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010657 }
10658 Clause.setUpdates(Updates);
10659 Clause.setFinals(Finals);
10660 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010661}
10662
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010663OMPClause *Sema::ActOnOpenMPAlignedClause(
10664 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10665 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10666
10667 SmallVector<Expr *, 8> Vars;
10668 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010669 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10670 SourceLocation ELoc;
10671 SourceRange ERange;
10672 Expr *SimpleRefExpr = RefExpr;
10673 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10674 /*AllowArraySection=*/false);
10675 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010676 // It will be analyzed later.
10677 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010678 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010679 ValueDecl *D = Res.first;
10680 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010681 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010682
Alexey Bataev1efd1662016-03-29 10:59:56 +000010683 QualType QType = D->getType();
10684 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010685
10686 // OpenMP [2.8.1, simd construct, Restrictions]
10687 // The type of list items appearing in the aligned clause must be
10688 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010689 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010690 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010691 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010692 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010693 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010694 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010695 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010696 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010697 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010698 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010699 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010700 continue;
10701 }
10702
10703 // OpenMP [2.8.1, simd construct, Restrictions]
10704 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010705 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010706 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010707 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10708 << getOpenMPClauseName(OMPC_aligned);
10709 continue;
10710 }
10711
Alexey Bataev1efd1662016-03-29 10:59:56 +000010712 DeclRefExpr *Ref = nullptr;
10713 if (!VD && IsOpenMPCapturedDecl(D))
10714 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10715 Vars.push_back(DefaultFunctionArrayConversion(
10716 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10717 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010718 }
10719
10720 // OpenMP [2.8.1, simd construct, Description]
10721 // The parameter of the aligned clause, alignment, must be a constant
10722 // positive integer expression.
10723 // If no optional parameter is specified, implementation-defined default
10724 // alignments for SIMD instructions on the target platforms are assumed.
10725 if (Alignment != nullptr) {
10726 ExprResult AlignResult =
10727 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10728 if (AlignResult.isInvalid())
10729 return nullptr;
10730 Alignment = AlignResult.get();
10731 }
10732 if (Vars.empty())
10733 return nullptr;
10734
10735 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10736 EndLoc, Vars, Alignment);
10737}
10738
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010739OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10740 SourceLocation StartLoc,
10741 SourceLocation LParenLoc,
10742 SourceLocation EndLoc) {
10743 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010744 SmallVector<Expr *, 8> SrcExprs;
10745 SmallVector<Expr *, 8> DstExprs;
10746 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010747 for (auto &RefExpr : VarList) {
10748 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10749 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010750 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010751 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010752 SrcExprs.push_back(nullptr);
10753 DstExprs.push_back(nullptr);
10754 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010755 continue;
10756 }
10757
Alexey Bataeved09d242014-05-28 05:53:51 +000010758 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010759 // OpenMP [2.1, C/C++]
10760 // A list item is a variable name.
10761 // OpenMP [2.14.4.1, Restrictions, p.1]
10762 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010763 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010764 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010765 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10766 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010767 continue;
10768 }
10769
10770 Decl *D = DE->getDecl();
10771 VarDecl *VD = cast<VarDecl>(D);
10772
10773 QualType Type = VD->getType();
10774 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10775 // It will be analyzed later.
10776 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010777 SrcExprs.push_back(nullptr);
10778 DstExprs.push_back(nullptr);
10779 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010780 continue;
10781 }
10782
10783 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10784 // A list item that appears in a copyin clause must be threadprivate.
10785 if (!DSAStack->isThreadPrivate(VD)) {
10786 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010787 << getOpenMPClauseName(OMPC_copyin)
10788 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010789 continue;
10790 }
10791
10792 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10793 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010794 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010795 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010796 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010797 auto *SrcVD =
10798 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10799 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010800 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010801 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10802 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010803 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10804 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010805 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010806 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010807 // For arrays generate assignment operation for single element and replace
10808 // it by the original array element in CodeGen.
10809 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10810 PseudoDstExpr, PseudoSrcExpr);
10811 if (AssignmentOp.isInvalid())
10812 continue;
10813 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10814 /*DiscardedValue=*/true);
10815 if (AssignmentOp.isInvalid())
10816 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010817
10818 DSAStack->addDSA(VD, DE, OMPC_copyin);
10819 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010820 SrcExprs.push_back(PseudoSrcExpr);
10821 DstExprs.push_back(PseudoDstExpr);
10822 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010823 }
10824
Alexey Bataeved09d242014-05-28 05:53:51 +000010825 if (Vars.empty())
10826 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010827
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010828 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10829 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010830}
10831
Alexey Bataevbae9a792014-06-27 10:37:06 +000010832OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10833 SourceLocation StartLoc,
10834 SourceLocation LParenLoc,
10835 SourceLocation EndLoc) {
10836 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010837 SmallVector<Expr *, 8> SrcExprs;
10838 SmallVector<Expr *, 8> DstExprs;
10839 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010840 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010841 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10842 SourceLocation ELoc;
10843 SourceRange ERange;
10844 Expr *SimpleRefExpr = RefExpr;
10845 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10846 /*AllowArraySection=*/false);
10847 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010848 // It will be analyzed later.
10849 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010850 SrcExprs.push_back(nullptr);
10851 DstExprs.push_back(nullptr);
10852 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010853 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010854 ValueDecl *D = Res.first;
10855 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010856 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010857
Alexey Bataeve122da12016-03-17 10:50:17 +000010858 QualType Type = D->getType();
10859 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010860
10861 // OpenMP [2.14.4.2, Restrictions, p.2]
10862 // A list item that appears in a copyprivate clause may not appear in a
10863 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010864 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10865 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010866 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10867 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010868 Diag(ELoc, diag::err_omp_wrong_dsa)
10869 << getOpenMPClauseName(DVar.CKind)
10870 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010871 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010872 continue;
10873 }
10874
10875 // OpenMP [2.11.4.2, Restrictions, p.1]
10876 // All list items that appear in a copyprivate clause must be either
10877 // threadprivate or private in the enclosing context.
10878 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010879 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010880 if (DVar.CKind == OMPC_shared) {
10881 Diag(ELoc, diag::err_omp_required_access)
10882 << getOpenMPClauseName(OMPC_copyprivate)
10883 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010884 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010885 continue;
10886 }
10887 }
10888 }
10889
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010890 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010891 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010892 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010893 << getOpenMPClauseName(OMPC_copyprivate) << Type
10894 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010895 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010896 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010897 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010898 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010899 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010900 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010901 continue;
10902 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010903
Alexey Bataevbae9a792014-06-27 10:37:06 +000010904 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10905 // A variable of class type (or array thereof) that appears in a
10906 // copyin clause requires an accessible, unambiguous copy assignment
10907 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010908 Type = Context.getBaseElementType(Type.getNonReferenceType())
10909 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010910 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010911 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10912 D->hasAttrs() ? &D->getAttrs() : nullptr);
10913 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010914 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010915 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10916 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010917 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010918 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010919 PseudoDstExpr, PseudoSrcExpr);
10920 if (AssignmentOp.isInvalid())
10921 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010922 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010923 /*DiscardedValue=*/true);
10924 if (AssignmentOp.isInvalid())
10925 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010926
10927 // No need to mark vars as copyprivate, they are already threadprivate or
10928 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010929 assert(VD || IsOpenMPCapturedDecl(D));
10930 Vars.push_back(
10931 VD ? RefExpr->IgnoreParens()
10932 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010933 SrcExprs.push_back(PseudoSrcExpr);
10934 DstExprs.push_back(PseudoDstExpr);
10935 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010936 }
10937
10938 if (Vars.empty())
10939 return nullptr;
10940
Alexey Bataeva63048e2015-03-23 06:18:07 +000010941 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10942 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010943}
10944
Alexey Bataev6125da92014-07-21 11:26:11 +000010945OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10946 SourceLocation StartLoc,
10947 SourceLocation LParenLoc,
10948 SourceLocation EndLoc) {
10949 if (VarList.empty())
10950 return nullptr;
10951
10952 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10953}
Alexey Bataevdea47612014-07-23 07:46:59 +000010954
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010955OMPClause *
10956Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10957 SourceLocation DepLoc, SourceLocation ColonLoc,
10958 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10959 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010960 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010961 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010962 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010963 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010964 return nullptr;
10965 }
10966 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010967 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10968 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010969 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010970 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010971 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10972 /*Last=*/OMPC_DEPEND_unknown, Except)
10973 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010974 return nullptr;
10975 }
10976 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010977 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010978 llvm::APSInt DepCounter(/*BitWidth=*/32);
10979 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10980 if (DepKind == OMPC_DEPEND_sink) {
10981 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10982 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10983 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010984 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010985 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010986 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10987 DSAStack->getParentOrderedRegionParam()) {
10988 for (auto &RefExpr : VarList) {
10989 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010990 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010991 // It will be analyzed later.
10992 Vars.push_back(RefExpr);
10993 continue;
10994 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010995
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010996 SourceLocation ELoc = RefExpr->getExprLoc();
10997 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10998 if (DepKind == OMPC_DEPEND_sink) {
10999 if (DepCounter >= TotalDepCount) {
11000 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11001 continue;
11002 }
11003 ++DepCounter;
11004 // OpenMP [2.13.9, Summary]
11005 // depend(dependence-type : vec), where dependence-type is:
11006 // 'sink' and where vec is the iteration vector, which has the form:
11007 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11008 // where n is the value specified by the ordered clause in the loop
11009 // directive, xi denotes the loop iteration variable of the i-th nested
11010 // loop associated with the loop directive, and di is a constant
11011 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000011012 if (CurContext->isDependentContext()) {
11013 // It will be analyzed later.
11014 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011015 continue;
11016 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011017 SimpleExpr = SimpleExpr->IgnoreImplicit();
11018 OverloadedOperatorKind OOK = OO_None;
11019 SourceLocation OOLoc;
11020 Expr *LHS = SimpleExpr;
11021 Expr *RHS = nullptr;
11022 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11023 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11024 OOLoc = BO->getOperatorLoc();
11025 LHS = BO->getLHS()->IgnoreParenImpCasts();
11026 RHS = BO->getRHS()->IgnoreParenImpCasts();
11027 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11028 OOK = OCE->getOperator();
11029 OOLoc = OCE->getOperatorLoc();
11030 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11031 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11032 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11033 OOK = MCE->getMethodDecl()
11034 ->getNameInfo()
11035 .getName()
11036 .getCXXOverloadedOperator();
11037 OOLoc = MCE->getCallee()->getExprLoc();
11038 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11039 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11040 }
11041 SourceLocation ELoc;
11042 SourceRange ERange;
11043 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11044 /*AllowArraySection=*/false);
11045 if (Res.second) {
11046 // It will be analyzed later.
11047 Vars.push_back(RefExpr);
11048 }
11049 ValueDecl *D = Res.first;
11050 if (!D)
11051 continue;
11052
11053 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11054 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11055 continue;
11056 }
11057 if (RHS) {
11058 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11059 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11060 if (RHSRes.isInvalid())
11061 continue;
11062 }
11063 if (!CurContext->isDependentContext() &&
11064 DSAStack->getParentOrderedRegionParam() &&
11065 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000011066 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11067 DepCounter.getZExtValue());
11068 if (VD) {
11069 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11070 << 1 << VD;
11071 } else {
11072 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11073 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011074 continue;
11075 }
11076 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011077 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011078 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011079 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000011080 (ASE &&
11081 !ASE->getBase()
11082 ->getType()
11083 .getNonReferenceType()
11084 ->isPointerType() &&
11085 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011086 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11087 << RefExpr->getSourceRange();
11088 continue;
11089 }
11090 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11091 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000011092 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011093 RefExpr->IgnoreParenImpCasts());
11094 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11095 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11096 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11097 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011098 continue;
11099 }
11100 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011101 Vars.push_back(RefExpr->IgnoreParenImpCasts());
11102 }
11103
11104 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11105 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000011106 DSAStack->getParentOrderedRegionParam() &&
11107 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11108 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011109 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11110 }
11111 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11112 Vars.empty())
11113 return nullptr;
11114 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011115 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11116 DepKind, DepLoc, ColonLoc, Vars);
11117 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11118 DSAStack->addDoacrossDependClause(C, OpsOffs);
11119 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011120}
Michael Wonge710d542015-08-07 16:16:36 +000011121
11122OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11123 SourceLocation LParenLoc,
11124 SourceLocation EndLoc) {
11125 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011126 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011127
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011128 // OpenMP [2.9.1, Restrictions]
11129 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011130 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11131 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011132 return nullptr;
11133
Alexey Bataev931e19b2017-10-02 16:32:39 +000011134 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11135 if (isOpenMPTargetExecutionDirective(DKind) &&
11136 !CurContext->isDependentContext()) {
11137 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11138 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11139 HelperValStmt = buildPreInits(Context, Captures);
11140 }
11141
11142 return new (Context)
11143 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011144}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011145
Kelvin Li0bff7af2015-11-23 05:32:03 +000011146static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11147 DSAStackTy *Stack, QualType QTy) {
11148 NamedDecl *ND;
11149 if (QTy->isIncompleteType(&ND)) {
11150 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11151 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011152 }
11153 return true;
11154}
11155
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011156/// \brief Return true if it can be proven that the provided array expression
11157/// (array section or array subscript) does NOT specify the whole size of the
11158/// array whose base type is \a BaseQTy.
11159static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11160 const Expr *E,
11161 QualType BaseQTy) {
11162 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11163
11164 // If this is an array subscript, it refers to the whole size if the size of
11165 // the dimension is constant and equals 1. Also, an array section assumes the
11166 // format of an array subscript if no colon is used.
11167 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11168 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11169 return ATy->getSize().getSExtValue() != 1;
11170 // Size can't be evaluated statically.
11171 return false;
11172 }
11173
11174 assert(OASE && "Expecting array section if not an array subscript.");
11175 auto *LowerBound = OASE->getLowerBound();
11176 auto *Length = OASE->getLength();
11177
11178 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011179 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011180 if (LowerBound) {
11181 llvm::APSInt ConstLowerBound;
11182 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11183 return false; // Can't get the integer value as a constant.
11184 if (ConstLowerBound.getSExtValue())
11185 return true;
11186 }
11187
11188 // If we don't have a length we covering the whole dimension.
11189 if (!Length)
11190 return false;
11191
11192 // If the base is a pointer, we don't have a way to get the size of the
11193 // pointee.
11194 if (BaseQTy->isPointerType())
11195 return false;
11196
11197 // We can only check if the length is the same as the size of the dimension
11198 // if we have a constant array.
11199 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11200 if (!CATy)
11201 return false;
11202
11203 llvm::APSInt ConstLength;
11204 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11205 return false; // Can't get the integer value as a constant.
11206
11207 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11208}
11209
11210// Return true if it can be proven that the provided array expression (array
11211// section or array subscript) does NOT specify a single element of the array
11212// whose base type is \a BaseQTy.
11213static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011214 const Expr *E,
11215 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011216 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11217
11218 // An array subscript always refer to a single element. Also, an array section
11219 // assumes the format of an array subscript if no colon is used.
11220 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11221 return false;
11222
11223 assert(OASE && "Expecting array section if not an array subscript.");
11224 auto *Length = OASE->getLength();
11225
11226 // If we don't have a length we have to check if the array has unitary size
11227 // for this dimension. Also, we should always expect a length if the base type
11228 // is pointer.
11229 if (!Length) {
11230 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11231 return ATy->getSize().getSExtValue() != 1;
11232 // We cannot assume anything.
11233 return false;
11234 }
11235
11236 // Check if the length evaluates to 1.
11237 llvm::APSInt ConstLength;
11238 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11239 return false; // Can't get the integer value as a constant.
11240
11241 return ConstLength.getSExtValue() != 1;
11242}
11243
Samuel Antao661c0902016-05-26 17:39:58 +000011244// Return the expression of the base of the mappable expression or null if it
11245// cannot be determined and do all the necessary checks to see if the expression
11246// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011247// components of the expression.
11248static Expr *CheckMapClauseExpressionBase(
11249 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011250 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11251 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011252 SourceLocation ELoc = E->getExprLoc();
11253 SourceRange ERange = E->getSourceRange();
11254
11255 // The base of elements of list in a map clause have to be either:
11256 // - a reference to variable or field.
11257 // - a member expression.
11258 // - an array expression.
11259 //
11260 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11261 // reference to 'r'.
11262 //
11263 // If we have:
11264 //
11265 // struct SS {
11266 // Bla S;
11267 // foo() {
11268 // #pragma omp target map (S.Arr[:12]);
11269 // }
11270 // }
11271 //
11272 // We want to retrieve the member expression 'this->S';
11273
11274 Expr *RelevantExpr = nullptr;
11275
Samuel Antao5de996e2016-01-22 20:21:36 +000011276 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11277 // If a list item is an array section, it must specify contiguous storage.
11278 //
11279 // For this restriction it is sufficient that we make sure only references
11280 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011281 // exist except in the rightmost expression (unless they cover the whole
11282 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011283 //
11284 // r.ArrS[3:5].Arr[6:7]
11285 //
11286 // r.ArrS[3:5].x
11287 //
11288 // but these would be valid:
11289 // r.ArrS[3].Arr[6:7]
11290 //
11291 // r.ArrS[3].x
11292
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011293 bool AllowUnitySizeArraySection = true;
11294 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011295
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011296 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011297 E = E->IgnoreParenImpCasts();
11298
11299 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11300 if (!isa<VarDecl>(CurE->getDecl()))
11301 break;
11302
11303 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011304
11305 // If we got a reference to a declaration, we should not expect any array
11306 // section before that.
11307 AllowUnitySizeArraySection = false;
11308 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011309
11310 // Record the component.
11311 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
11312 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000011313 continue;
11314 }
11315
11316 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11317 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11318
11319 if (isa<CXXThisExpr>(BaseE))
11320 // We found a base expression: this->Val.
11321 RelevantExpr = CurE;
11322 else
11323 E = BaseE;
11324
11325 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11326 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11327 << CurE->getSourceRange();
11328 break;
11329 }
11330
11331 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11332
11333 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11334 // A bit-field cannot appear in a map clause.
11335 //
11336 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011337 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11338 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011339 break;
11340 }
11341
11342 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11343 // If the type of a list item is a reference to a type T then the type
11344 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011345 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011346
11347 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11348 // A list item cannot be a variable that is a member of a structure with
11349 // a union type.
11350 //
11351 if (auto *RT = CurType->getAs<RecordType>())
11352 if (RT->isUnionType()) {
11353 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11354 << CurE->getSourceRange();
11355 break;
11356 }
11357
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011358 // If we got a member expression, we should not expect any array section
11359 // before that:
11360 //
11361 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11362 // If a list item is an element of a structure, only the rightmost symbol
11363 // of the variable reference can be an array section.
11364 //
11365 AllowUnitySizeArraySection = false;
11366 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011367
11368 // Record the component.
11369 CurComponents.push_back(
11370 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000011371 continue;
11372 }
11373
11374 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11375 E = CurE->getBase()->IgnoreParenImpCasts();
11376
11377 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11378 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11379 << 0 << CurE->getSourceRange();
11380 break;
11381 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011382
11383 // If we got an array subscript that express the whole dimension we
11384 // can have any array expressions before. If it only expressing part of
11385 // the dimension, we can only have unitary-size array expressions.
11386 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11387 E->getType()))
11388 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011389
11390 // Record the component - we don't have any declaration associated.
11391 CurComponents.push_back(
11392 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011393 continue;
11394 }
11395
11396 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011397 E = CurE->getBase()->IgnoreParenImpCasts();
11398
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011399 auto CurType =
11400 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11401
Samuel Antao5de996e2016-01-22 20:21:36 +000011402 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11403 // If the type of a list item is a reference to a type T then the type
11404 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011405 if (CurType->isReferenceType())
11406 CurType = CurType->getPointeeType();
11407
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011408 bool IsPointer = CurType->isAnyPointerType();
11409
11410 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011411 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11412 << 0 << CurE->getSourceRange();
11413 break;
11414 }
11415
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011416 bool NotWhole =
11417 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11418 bool NotUnity =
11419 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11420
Samuel Antaodab51bb2016-07-18 23:22:11 +000011421 if (AllowWholeSizeArraySection) {
11422 // Any array section is currently allowed. Allowing a whole size array
11423 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011424 //
11425 // If this array section refers to the whole dimension we can still
11426 // accept other array sections before this one, except if the base is a
11427 // pointer. Otherwise, only unitary sections are accepted.
11428 if (NotWhole || IsPointer)
11429 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011430 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011431 // A unity or whole array section is not allowed and that is not
11432 // compatible with the properties of the current array section.
11433 SemaRef.Diag(
11434 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11435 << CurE->getSourceRange();
11436 break;
11437 }
Samuel Antao90927002016-04-26 14:54:23 +000011438
11439 // Record the component - we don't have any declaration associated.
11440 CurComponents.push_back(
11441 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011442 continue;
11443 }
11444
11445 // If nothing else worked, this is not a valid map clause expression.
11446 SemaRef.Diag(ELoc,
11447 diag::err_omp_expected_named_var_member_or_array_expression)
11448 << ERange;
11449 break;
11450 }
11451
11452 return RelevantExpr;
11453}
11454
11455// Return true if expression E associated with value VD has conflicts with other
11456// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011457static bool CheckMapConflicts(
11458 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11459 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011460 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11461 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011462 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011463 SourceLocation ELoc = E->getExprLoc();
11464 SourceRange ERange = E->getSourceRange();
11465
11466 // In order to easily check the conflicts we need to match each component of
11467 // the expression under test with the components of the expressions that are
11468 // already in the stack.
11469
Samuel Antao5de996e2016-01-22 20:21:36 +000011470 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011471 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011472 "Map clause expression with unexpected base!");
11473
11474 // Variables to help detecting enclosing problems in data environment nests.
11475 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011476 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011477
Samuel Antao90927002016-04-26 14:54:23 +000011478 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11479 VD, CurrentRegionOnly,
11480 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011481 StackComponents,
11482 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011483
Samuel Antao5de996e2016-01-22 20:21:36 +000011484 assert(!StackComponents.empty() &&
11485 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011486 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011487 "Map clause expression with unexpected base!");
11488
Samuel Antao90927002016-04-26 14:54:23 +000011489 // The whole expression in the stack.
11490 auto *RE = StackComponents.front().getAssociatedExpression();
11491
Samuel Antao5de996e2016-01-22 20:21:36 +000011492 // Expressions must start from the same base. Here we detect at which
11493 // point both expressions diverge from each other and see if we can
11494 // detect if the memory referred to both expressions is contiguous and
11495 // do not overlap.
11496 auto CI = CurComponents.rbegin();
11497 auto CE = CurComponents.rend();
11498 auto SI = StackComponents.rbegin();
11499 auto SE = StackComponents.rend();
11500 for (; CI != CE && SI != SE; ++CI, ++SI) {
11501
11502 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11503 // At most one list item can be an array item derived from a given
11504 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011505 if (CurrentRegionOnly &&
11506 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11507 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11508 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11509 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11510 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011511 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011512 << CI->getAssociatedExpression()->getSourceRange();
11513 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11514 diag::note_used_here)
11515 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011516 return true;
11517 }
11518
11519 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011520 if (CI->getAssociatedExpression()->getStmtClass() !=
11521 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011522 break;
11523
11524 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011525 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011526 break;
11527 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011528 // Check if the extra components of the expressions in the enclosing
11529 // data environment are redundant for the current base declaration.
11530 // If they are, the maps completely overlap, which is legal.
11531 for (; SI != SE; ++SI) {
11532 QualType Type;
11533 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011534 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011535 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011536 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11537 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011538 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11539 Type =
11540 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11541 }
11542 if (Type.isNull() || Type->isAnyPointerType() ||
11543 CheckArrayExpressionDoesNotReferToWholeSize(
11544 SemaRef, SI->getAssociatedExpression(), Type))
11545 break;
11546 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011547
11548 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11549 // List items of map clauses in the same construct must not share
11550 // original storage.
11551 //
11552 // If the expressions are exactly the same or one is a subset of the
11553 // other, it means they are sharing storage.
11554 if (CI == CE && SI == SE) {
11555 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011556 if (CKind == OMPC_map)
11557 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11558 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011559 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011560 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11561 << ERange;
11562 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011563 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11564 << RE->getSourceRange();
11565 return true;
11566 } else {
11567 // If we find the same expression in the enclosing data environment,
11568 // that is legal.
11569 IsEnclosedByDataEnvironmentExpr = true;
11570 return false;
11571 }
11572 }
11573
Samuel Antao90927002016-04-26 14:54:23 +000011574 QualType DerivedType =
11575 std::prev(CI)->getAssociatedDeclaration()->getType();
11576 SourceLocation DerivedLoc =
11577 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011578
11579 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11580 // If the type of a list item is a reference to a type T then the type
11581 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011582 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011583
11584 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11585 // A variable for which the type is pointer and an array section
11586 // derived from that variable must not appear as list items of map
11587 // clauses of the same construct.
11588 //
11589 // Also, cover one of the cases in:
11590 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11591 // If any part of the original storage of a list item has corresponding
11592 // storage in the device data environment, all of the original storage
11593 // must have corresponding storage in the device data environment.
11594 //
11595 if (DerivedType->isAnyPointerType()) {
11596 if (CI == CE || SI == SE) {
11597 SemaRef.Diag(
11598 DerivedLoc,
11599 diag::err_omp_pointer_mapped_along_with_derived_section)
11600 << DerivedLoc;
11601 } else {
11602 assert(CI != CE && SI != SE);
11603 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11604 << DerivedLoc;
11605 }
11606 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11607 << RE->getSourceRange();
11608 return true;
11609 }
11610
11611 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11612 // List items of map clauses in the same construct must not share
11613 // original storage.
11614 //
11615 // An expression is a subset of the other.
11616 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011617 if (CKind == OMPC_map)
11618 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11619 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011620 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011621 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11622 << ERange;
11623 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011624 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11625 << RE->getSourceRange();
11626 return true;
11627 }
11628
11629 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011630 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011631 if (!CurrentRegionOnly && SI != SE)
11632 EnclosingExpr = RE;
11633
11634 // The current expression is a subset of the expression in the data
11635 // environment.
11636 IsEnclosedByDataEnvironmentExpr |=
11637 (!CurrentRegionOnly && CI != CE && SI == SE);
11638
11639 return false;
11640 });
11641
11642 if (CurrentRegionOnly)
11643 return FoundError;
11644
11645 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11646 // If any part of the original storage of a list item has corresponding
11647 // storage in the device data environment, all of the original storage must
11648 // have corresponding storage in the device data environment.
11649 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11650 // If a list item is an element of a structure, and a different element of
11651 // the structure has a corresponding list item in the device data environment
11652 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011653 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011654 // data environment prior to the task encountering the construct.
11655 //
11656 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11657 SemaRef.Diag(ELoc,
11658 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11659 << ERange;
11660 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11661 << EnclosingExpr->getSourceRange();
11662 return true;
11663 }
11664
11665 return FoundError;
11666}
11667
Samuel Antao661c0902016-05-26 17:39:58 +000011668namespace {
11669// Utility struct that gathers all the related lists associated with a mappable
11670// expression.
11671struct MappableVarListInfo final {
11672 // The list of expressions.
11673 ArrayRef<Expr *> VarList;
11674 // The list of processed expressions.
11675 SmallVector<Expr *, 16> ProcessedVarList;
11676 // The mappble components for each expression.
11677 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11678 // The base declaration of the variable.
11679 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11680
11681 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11682 // We have a list of components and base declarations for each entry in the
11683 // variable list.
11684 VarComponents.reserve(VarList.size());
11685 VarBaseDeclarations.reserve(VarList.size());
11686 }
11687};
11688}
11689
11690// Check the validity of the provided variable list for the provided clause kind
11691// \a CKind. In the check process the valid expressions, and mappable expression
11692// components and variables are extracted and used to fill \a Vars,
11693// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11694// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11695static void
11696checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11697 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11698 SourceLocation StartLoc,
11699 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11700 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011701 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11702 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011703 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011704
Samuel Antao90927002016-04-26 14:54:23 +000011705 // Keep track of the mappable components and base declarations in this clause.
11706 // Each entry in the list is going to have a list of components associated. We
11707 // record each set of the components so that we can build the clause later on.
11708 // In the end we should have the same amount of declarations and component
11709 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011710
Samuel Antao661c0902016-05-26 17:39:58 +000011711 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011712 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011713 SourceLocation ELoc = RE->getExprLoc();
11714
Kelvin Li0bff7af2015-11-23 05:32:03 +000011715 auto *VE = RE->IgnoreParenLValueCasts();
11716
11717 if (VE->isValueDependent() || VE->isTypeDependent() ||
11718 VE->isInstantiationDependent() ||
11719 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011720 // We can only analyze this information once the missing information is
11721 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011722 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011723 continue;
11724 }
11725
11726 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011727
Samuel Antao5de996e2016-01-22 20:21:36 +000011728 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011729 SemaRef.Diag(ELoc,
11730 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011731 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011732 continue;
11733 }
11734
Samuel Antao90927002016-04-26 14:54:23 +000011735 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11736 ValueDecl *CurDeclaration = nullptr;
11737
11738 // Obtain the array or member expression bases if required. Also, fill the
11739 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011740 auto *BE =
11741 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011742 if (!BE)
11743 continue;
11744
Samuel Antao90927002016-04-26 14:54:23 +000011745 assert(!CurComponents.empty() &&
11746 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011747
Samuel Antao90927002016-04-26 14:54:23 +000011748 // For the following checks, we rely on the base declaration which is
11749 // expected to be associated with the last component. The declaration is
11750 // expected to be a variable or a field (if 'this' is being mapped).
11751 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11752 assert(CurDeclaration && "Null decl on map clause.");
11753 assert(
11754 CurDeclaration->isCanonicalDecl() &&
11755 "Expecting components to have associated only canonical declarations.");
11756
11757 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11758 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011759
11760 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011761 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011762
11763 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011764 // threadprivate variables cannot appear in a map clause.
11765 // OpenMP 4.5 [2.10.5, target update Construct]
11766 // threadprivate variables cannot appear in a from clause.
11767 if (VD && DSAS->isThreadPrivate(VD)) {
11768 auto DVar = DSAS->getTopDSA(VD, false);
11769 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11770 << getOpenMPClauseName(CKind);
11771 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011772 continue;
11773 }
11774
Samuel Antao5de996e2016-01-22 20:21:36 +000011775 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11776 // A list item cannot appear in both a map clause and a data-sharing
11777 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011778
Samuel Antao5de996e2016-01-22 20:21:36 +000011779 // Check conflicts with other map clause expressions. We check the conflicts
11780 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011781 // environment, because the restrictions are different. We only have to
11782 // check conflicts across regions for the map clauses.
11783 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11784 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011785 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011786 if (CKind == OMPC_map &&
11787 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11788 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011789 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011790
Samuel Antao661c0902016-05-26 17:39:58 +000011791 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011792 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11793 // If the type of a list item is a reference to a type T then the type will
11794 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011795 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011796
Samuel Antao661c0902016-05-26 17:39:58 +000011797 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11798 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011799 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011800 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011801 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11802 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011803 continue;
11804
Samuel Antao661c0902016-05-26 17:39:58 +000011805 if (CKind == OMPC_map) {
11806 // target enter data
11807 // OpenMP [2.10.2, Restrictions, p. 99]
11808 // A map-type must be specified in all map clauses and must be either
11809 // to or alloc.
11810 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11811 if (DKind == OMPD_target_enter_data &&
11812 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11813 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11814 << (IsMapTypeImplicit ? 1 : 0)
11815 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11816 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011817 continue;
11818 }
Samuel Antao661c0902016-05-26 17:39:58 +000011819
11820 // target exit_data
11821 // OpenMP [2.10.3, Restrictions, p. 102]
11822 // A map-type must be specified in all map clauses and must be either
11823 // from, release, or delete.
11824 if (DKind == OMPD_target_exit_data &&
11825 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11826 MapType == OMPC_MAP_delete)) {
11827 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11828 << (IsMapTypeImplicit ? 1 : 0)
11829 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11830 << getOpenMPDirectiveName(DKind);
11831 continue;
11832 }
11833
11834 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11835 // A list item cannot appear in both a map clause and a data-sharing
11836 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011837 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011838 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011839 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011840 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11841 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011842 auto DVar = DSAS->getTopDSA(VD, false);
11843 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011844 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011845 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011846 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011847 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11848 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11849 continue;
11850 }
11851 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011852 }
11853
Samuel Antao90927002016-04-26 14:54:23 +000011854 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011855 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011856
11857 // Store the components in the stack so that they can be used to check
11858 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011859 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11860 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011861
11862 // Save the components and declaration to create the clause. For purposes of
11863 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011864 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011865 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11866 MVLI.VarComponents.back().append(CurComponents.begin(),
11867 CurComponents.end());
11868 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11869 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011870 }
Samuel Antao661c0902016-05-26 17:39:58 +000011871}
11872
11873OMPClause *
11874Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11875 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11876 SourceLocation MapLoc, SourceLocation ColonLoc,
11877 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11878 SourceLocation LParenLoc, SourceLocation EndLoc) {
11879 MappableVarListInfo MVLI(VarList);
11880 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11881 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011882
Samuel Antao5de996e2016-01-22 20:21:36 +000011883 // We need to produce a map clause even if we don't have variables so that
11884 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011885 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11886 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11887 MVLI.VarComponents, MapTypeModifier, MapType,
11888 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011889}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011890
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011891QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11892 TypeResult ParsedType) {
11893 assert(ParsedType.isUsable());
11894
11895 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11896 if (ReductionType.isNull())
11897 return QualType();
11898
11899 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11900 // A type name in a declare reduction directive cannot be a function type, an
11901 // array type, a reference type, or a type qualified with const, volatile or
11902 // restrict.
11903 if (ReductionType.hasQualifiers()) {
11904 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11905 return QualType();
11906 }
11907
11908 if (ReductionType->isFunctionType()) {
11909 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11910 return QualType();
11911 }
11912 if (ReductionType->isReferenceType()) {
11913 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11914 return QualType();
11915 }
11916 if (ReductionType->isArrayType()) {
11917 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11918 return QualType();
11919 }
11920 return ReductionType;
11921}
11922
11923Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11924 Scope *S, DeclContext *DC, DeclarationName Name,
11925 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11926 AccessSpecifier AS, Decl *PrevDeclInScope) {
11927 SmallVector<Decl *, 8> Decls;
11928 Decls.reserve(ReductionTypes.size());
11929
11930 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000011931 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011932 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11933 // A reduction-identifier may not be re-declared in the current scope for the
11934 // same type or for a type that is compatible according to the base language
11935 // rules.
11936 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11937 OMPDeclareReductionDecl *PrevDRD = nullptr;
11938 bool InCompoundScope = true;
11939 if (S != nullptr) {
11940 // Find previous declaration with the same name not referenced in other
11941 // declarations.
11942 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11943 InCompoundScope =
11944 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11945 LookupName(Lookup, S);
11946 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11947 /*AllowInlineNamespace=*/false);
11948 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11949 auto Filter = Lookup.makeFilter();
11950 while (Filter.hasNext()) {
11951 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11952 if (InCompoundScope) {
11953 auto I = UsedAsPrevious.find(PrevDecl);
11954 if (I == UsedAsPrevious.end())
11955 UsedAsPrevious[PrevDecl] = false;
11956 if (auto *D = PrevDecl->getPrevDeclInScope())
11957 UsedAsPrevious[D] = true;
11958 }
11959 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11960 PrevDecl->getLocation();
11961 }
11962 Filter.done();
11963 if (InCompoundScope) {
11964 for (auto &PrevData : UsedAsPrevious) {
11965 if (!PrevData.second) {
11966 PrevDRD = PrevData.first;
11967 break;
11968 }
11969 }
11970 }
11971 } else if (PrevDeclInScope != nullptr) {
11972 auto *PrevDRDInScope = PrevDRD =
11973 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11974 do {
11975 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11976 PrevDRDInScope->getLocation();
11977 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11978 } while (PrevDRDInScope != nullptr);
11979 }
11980 for (auto &TyData : ReductionTypes) {
11981 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11982 bool Invalid = false;
11983 if (I != PreviousRedeclTypes.end()) {
11984 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11985 << TyData.first;
11986 Diag(I->second, diag::note_previous_definition);
11987 Invalid = true;
11988 }
11989 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11990 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11991 Name, TyData.first, PrevDRD);
11992 DC->addDecl(DRD);
11993 DRD->setAccess(AS);
11994 Decls.push_back(DRD);
11995 if (Invalid)
11996 DRD->setInvalidDecl();
11997 else
11998 PrevDRD = DRD;
11999 }
12000
12001 return DeclGroupPtrTy::make(
12002 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12003}
12004
12005void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12006 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12007
12008 // Enter new function scope.
12009 PushFunctionScope();
12010 getCurFunction()->setHasBranchProtectedScope();
12011 getCurFunction()->setHasOMPDeclareReductionCombiner();
12012
12013 if (S != nullptr)
12014 PushDeclContext(S, DRD);
12015 else
12016 CurContext = DRD;
12017
Faisal Valid143a0c2017-04-01 21:30:49 +000012018 PushExpressionEvaluationContext(
12019 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012020
12021 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012022 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12023 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12024 // uses semantics of argument handles by value, but it should be passed by
12025 // reference. C lang does not support references, so pass all parameters as
12026 // pointers.
12027 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012028 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012029 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012030 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12031 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12032 // uses semantics of argument handles by value, but it should be passed by
12033 // reference. C lang does not support references, so pass all parameters as
12034 // pointers.
12035 // Create 'T omp_out;' variable.
12036 auto *OmpOutParm =
12037 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12038 if (S != nullptr) {
12039 PushOnScopeChains(OmpInParm, S);
12040 PushOnScopeChains(OmpOutParm, S);
12041 } else {
12042 DRD->addDecl(OmpInParm);
12043 DRD->addDecl(OmpOutParm);
12044 }
12045}
12046
12047void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12048 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12049 DiscardCleanupsInEvaluationContext();
12050 PopExpressionEvaluationContext();
12051
12052 PopDeclContext();
12053 PopFunctionScopeInfo();
12054
12055 if (Combiner != nullptr)
12056 DRD->setCombiner(Combiner);
12057 else
12058 DRD->setInvalidDecl();
12059}
12060
Alexey Bataev070f43a2017-09-06 14:49:58 +000012061VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012062 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12063
12064 // Enter new function scope.
12065 PushFunctionScope();
12066 getCurFunction()->setHasBranchProtectedScope();
12067
12068 if (S != nullptr)
12069 PushDeclContext(S, DRD);
12070 else
12071 CurContext = DRD;
12072
Faisal Valid143a0c2017-04-01 21:30:49 +000012073 PushExpressionEvaluationContext(
12074 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012075
12076 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012077 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12078 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12079 // uses semantics of argument handles by value, but it should be passed by
12080 // reference. C lang does not support references, so pass all parameters as
12081 // pointers.
12082 // Create 'T omp_priv;' variable.
12083 auto *OmpPrivParm =
12084 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012085 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12086 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12087 // uses semantics of argument handles by value, but it should be passed by
12088 // reference. C lang does not support references, so pass all parameters as
12089 // pointers.
12090 // Create 'T omp_orig;' variable.
12091 auto *OmpOrigParm =
12092 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012093 if (S != nullptr) {
12094 PushOnScopeChains(OmpPrivParm, S);
12095 PushOnScopeChains(OmpOrigParm, S);
12096 } else {
12097 DRD->addDecl(OmpPrivParm);
12098 DRD->addDecl(OmpOrigParm);
12099 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012100 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012101}
12102
Alexey Bataev070f43a2017-09-06 14:49:58 +000012103void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12104 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012105 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12106 DiscardCleanupsInEvaluationContext();
12107 PopExpressionEvaluationContext();
12108
12109 PopDeclContext();
12110 PopFunctionScopeInfo();
12111
Alexey Bataev070f43a2017-09-06 14:49:58 +000012112 if (Initializer != nullptr) {
12113 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12114 } else if (OmpPrivParm->hasInit()) {
12115 DRD->setInitializer(OmpPrivParm->getInit(),
12116 OmpPrivParm->isDirectInit()
12117 ? OMPDeclareReductionDecl::DirectInit
12118 : OMPDeclareReductionDecl::CopyInit);
12119 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012120 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012121 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012122}
12123
12124Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12125 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12126 for (auto *D : DeclReductions.get()) {
12127 if (IsValid) {
12128 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12129 if (S != nullptr)
12130 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12131 } else
12132 D->setInvalidDecl();
12133 }
12134 return DeclReductions;
12135}
12136
David Majnemer9d168222016-08-05 17:44:54 +000012137OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012138 SourceLocation StartLoc,
12139 SourceLocation LParenLoc,
12140 SourceLocation EndLoc) {
12141 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012142 Stmt *HelperValStmt = nullptr;
12143 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012144
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012145 // OpenMP [teams Constrcut, Restrictions]
12146 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012147 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12148 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012149 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012150
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012151 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12152 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12153 if (CaptureRegion != OMPD_unknown) {
12154 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12155 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12156 HelperValStmt = buildPreInits(Context, Captures);
12157 }
12158
12159 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12160 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012161}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012162
12163OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12164 SourceLocation StartLoc,
12165 SourceLocation LParenLoc,
12166 SourceLocation EndLoc) {
12167 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012168 Stmt *HelperValStmt = nullptr;
12169 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012170
12171 // OpenMP [teams Constrcut, Restrictions]
12172 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012173 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12174 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012175 return nullptr;
12176
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012177 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12178 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12179 if (CaptureRegion != OMPD_unknown) {
12180 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12181 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12182 HelperValStmt = buildPreInits(Context, Captures);
12183 }
12184
12185 return new (Context) OMPThreadLimitClause(
12186 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012187}
Alexey Bataeva0569352015-12-01 10:17:31 +000012188
12189OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12190 SourceLocation StartLoc,
12191 SourceLocation LParenLoc,
12192 SourceLocation EndLoc) {
12193 Expr *ValExpr = Priority;
12194
12195 // OpenMP [2.9.1, task Constrcut]
12196 // The priority-value is a non-negative numerical scalar expression.
12197 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12198 /*StrictlyPositive=*/false))
12199 return nullptr;
12200
12201 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12202}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012203
12204OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12205 SourceLocation StartLoc,
12206 SourceLocation LParenLoc,
12207 SourceLocation EndLoc) {
12208 Expr *ValExpr = Grainsize;
12209
12210 // OpenMP [2.9.2, taskloop Constrcut]
12211 // The parameter of the grainsize clause must be a positive integer
12212 // expression.
12213 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12214 /*StrictlyPositive=*/true))
12215 return nullptr;
12216
12217 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12218}
Alexey Bataev382967a2015-12-08 12:06:20 +000012219
12220OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12221 SourceLocation StartLoc,
12222 SourceLocation LParenLoc,
12223 SourceLocation EndLoc) {
12224 Expr *ValExpr = NumTasks;
12225
12226 // OpenMP [2.9.2, taskloop Constrcut]
12227 // The parameter of the num_tasks clause must be a positive integer
12228 // expression.
12229 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12230 /*StrictlyPositive=*/true))
12231 return nullptr;
12232
12233 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12234}
12235
Alexey Bataev28c75412015-12-15 08:19:24 +000012236OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12237 SourceLocation LParenLoc,
12238 SourceLocation EndLoc) {
12239 // OpenMP [2.13.2, critical construct, Description]
12240 // ... where hint-expression is an integer constant expression that evaluates
12241 // to a valid lock hint.
12242 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12243 if (HintExpr.isInvalid())
12244 return nullptr;
12245 return new (Context)
12246 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12247}
12248
Carlo Bertollib4adf552016-01-15 18:50:31 +000012249OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12250 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12251 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12252 SourceLocation EndLoc) {
12253 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12254 std::string Values;
12255 Values += "'";
12256 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12257 Values += "'";
12258 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12259 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12260 return nullptr;
12261 }
12262 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012263 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012264 if (ChunkSize) {
12265 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12266 !ChunkSize->isInstantiationDependent() &&
12267 !ChunkSize->containsUnexpandedParameterPack()) {
12268 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12269 ExprResult Val =
12270 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12271 if (Val.isInvalid())
12272 return nullptr;
12273
12274 ValExpr = Val.get();
12275
12276 // OpenMP [2.7.1, Restrictions]
12277 // chunk_size must be a loop invariant integer expression with a positive
12278 // value.
12279 llvm::APSInt Result;
12280 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12281 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12282 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12283 << "dist_schedule" << ChunkSize->getSourceRange();
12284 return nullptr;
12285 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012286 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
12287 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000012288 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12289 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12290 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012291 }
12292 }
12293 }
12294
12295 return new (Context)
12296 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012297 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012298}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012299
12300OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12301 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12302 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12303 SourceLocation KindLoc, SourceLocation EndLoc) {
12304 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012305 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012306 std::string Value;
12307 SourceLocation Loc;
12308 Value += "'";
12309 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12310 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012311 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012312 Loc = MLoc;
12313 } else {
12314 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012315 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012316 Loc = KindLoc;
12317 }
12318 Value += "'";
12319 Diag(Loc, diag::err_omp_unexpected_clause_value)
12320 << Value << getOpenMPClauseName(OMPC_defaultmap);
12321 return nullptr;
12322 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012323 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012324
12325 return new (Context)
12326 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12327}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012328
12329bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12330 DeclContext *CurLexicalContext = getCurLexicalContext();
12331 if (!CurLexicalContext->isFileContext() &&
12332 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012333 !CurLexicalContext->isExternCXXContext() &&
12334 !isa<CXXRecordDecl>(CurLexicalContext) &&
12335 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12336 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12337 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012338 Diag(Loc, diag::err_omp_region_not_file_context);
12339 return false;
12340 }
12341 if (IsInOpenMPDeclareTargetContext) {
12342 Diag(Loc, diag::err_omp_enclosed_declare_target);
12343 return false;
12344 }
12345
12346 IsInOpenMPDeclareTargetContext = true;
12347 return true;
12348}
12349
12350void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12351 assert(IsInOpenMPDeclareTargetContext &&
12352 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12353
12354 IsInOpenMPDeclareTargetContext = false;
12355}
12356
David Majnemer9d168222016-08-05 17:44:54 +000012357void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12358 CXXScopeSpec &ScopeSpec,
12359 const DeclarationNameInfo &Id,
12360 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12361 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012362 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12363 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12364
12365 if (Lookup.isAmbiguous())
12366 return;
12367 Lookup.suppressDiagnostics();
12368
12369 if (!Lookup.isSingleResult()) {
12370 if (TypoCorrection Corrected =
12371 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12372 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12373 CTK_ErrorRecovery)) {
12374 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12375 << Id.getName());
12376 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12377 return;
12378 }
12379
12380 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12381 return;
12382 }
12383
12384 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12385 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12386 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12387 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12388
12389 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12390 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12391 ND->addAttr(A);
12392 if (ASTMutationListener *ML = Context.getASTMutationListener())
12393 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12394 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12395 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12396 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12397 << Id.getName();
12398 }
12399 } else
12400 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12401}
12402
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012403static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12404 Sema &SemaRef, Decl *D) {
12405 if (!D)
12406 return;
12407 Decl *LD = nullptr;
12408 if (isa<TagDecl>(D)) {
12409 LD = cast<TagDecl>(D)->getDefinition();
12410 } else if (isa<VarDecl>(D)) {
12411 LD = cast<VarDecl>(D)->getDefinition();
12412
12413 // If this is an implicit variable that is legal and we do not need to do
12414 // anything.
12415 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012416 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12417 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12418 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012419 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012420 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012421 return;
12422 }
12423
12424 } else if (isa<FunctionDecl>(D)) {
12425 const FunctionDecl *FD = nullptr;
12426 if (cast<FunctionDecl>(D)->hasBody(FD))
12427 LD = const_cast<FunctionDecl *>(FD);
12428
12429 // If the definition is associated with the current declaration in the
12430 // target region (it can be e.g. a lambda) that is legal and we do not need
12431 // to do anything else.
12432 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012433 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12434 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12435 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012436 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012437 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012438 return;
12439 }
12440 }
12441 if (!LD)
12442 LD = D;
12443 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12444 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12445 // Outlined declaration is not declared target.
12446 if (LD->isOutOfLine()) {
12447 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12448 SemaRef.Diag(SL, diag::note_used_here) << SR;
12449 } else {
12450 DeclContext *DC = LD->getDeclContext();
12451 while (DC) {
12452 if (isa<FunctionDecl>(DC) &&
12453 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12454 break;
12455 DC = DC->getParent();
12456 }
12457 if (DC)
12458 return;
12459
12460 // Is not declared in target context.
12461 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12462 SemaRef.Diag(SL, diag::note_used_here) << SR;
12463 }
12464 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012465 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12466 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12467 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012468 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012469 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012470 }
12471}
12472
12473static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12474 Sema &SemaRef, DSAStackTy *Stack,
12475 ValueDecl *VD) {
12476 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12477 return true;
12478 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12479 return false;
12480 return true;
12481}
12482
12483void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12484 if (!D || D->isInvalidDecl())
12485 return;
12486 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12487 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12488 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12489 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12490 if (DSAStack->isThreadPrivate(VD)) {
12491 Diag(SL, diag::err_omp_threadprivate_in_target);
12492 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12493 return;
12494 }
12495 }
12496 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12497 // Problem if any with var declared with incomplete type will be reported
12498 // as normal, so no need to check it here.
12499 if ((E || !VD->getType()->isIncompleteType()) &&
12500 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12501 // Mark decl as declared target to prevent further diagnostic.
12502 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012503 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12504 Context, OMPDeclareTargetDeclAttr::MT_To);
12505 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012506 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012507 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012508 }
12509 return;
12510 }
12511 }
12512 if (!E) {
12513 // Checking declaration inside declare target region.
12514 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12515 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012516 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12517 Context, OMPDeclareTargetDeclAttr::MT_To);
12518 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012519 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012520 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012521 }
12522 return;
12523 }
12524 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12525}
Samuel Antao661c0902016-05-26 17:39:58 +000012526
12527OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12528 SourceLocation StartLoc,
12529 SourceLocation LParenLoc,
12530 SourceLocation EndLoc) {
12531 MappableVarListInfo MVLI(VarList);
12532 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12533 if (MVLI.ProcessedVarList.empty())
12534 return nullptr;
12535
12536 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12537 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12538 MVLI.VarComponents);
12539}
Samuel Antaoec172c62016-05-26 17:49:04 +000012540
12541OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12542 SourceLocation StartLoc,
12543 SourceLocation LParenLoc,
12544 SourceLocation EndLoc) {
12545 MappableVarListInfo MVLI(VarList);
12546 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12547 if (MVLI.ProcessedVarList.empty())
12548 return nullptr;
12549
12550 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12551 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12552 MVLI.VarComponents);
12553}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012554
12555OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12556 SourceLocation StartLoc,
12557 SourceLocation LParenLoc,
12558 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012559 MappableVarListInfo MVLI(VarList);
12560 SmallVector<Expr *, 8> PrivateCopies;
12561 SmallVector<Expr *, 8> Inits;
12562
Carlo Bertolli2404b172016-07-13 15:37:16 +000012563 for (auto &RefExpr : VarList) {
12564 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12565 SourceLocation ELoc;
12566 SourceRange ERange;
12567 Expr *SimpleRefExpr = RefExpr;
12568 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12569 if (Res.second) {
12570 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012571 MVLI.ProcessedVarList.push_back(RefExpr);
12572 PrivateCopies.push_back(nullptr);
12573 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012574 }
12575 ValueDecl *D = Res.first;
12576 if (!D)
12577 continue;
12578
12579 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012580 Type = Type.getNonReferenceType().getUnqualifiedType();
12581
12582 auto *VD = dyn_cast<VarDecl>(D);
12583
12584 // Item should be a pointer or reference to pointer.
12585 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012586 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12587 << 0 << RefExpr->getSourceRange();
12588 continue;
12589 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012590
12591 // Build the private variable and the expression that refers to it.
12592 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12593 D->hasAttrs() ? &D->getAttrs() : nullptr);
12594 if (VDPrivate->isInvalidDecl())
12595 continue;
12596
12597 CurContext->addDecl(VDPrivate);
12598 auto VDPrivateRefExpr = buildDeclRefExpr(
12599 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12600
12601 // Add temporary variable to initialize the private copy of the pointer.
12602 auto *VDInit =
12603 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12604 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12605 RefExpr->getExprLoc());
12606 AddInitializerToDecl(VDPrivate,
12607 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012608 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012609
12610 // If required, build a capture to implement the privatization initialized
12611 // with the current list item value.
12612 DeclRefExpr *Ref = nullptr;
12613 if (!VD)
12614 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12615 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12616 PrivateCopies.push_back(VDPrivateRefExpr);
12617 Inits.push_back(VDInitRefExpr);
12618
12619 // We need to add a data sharing attribute for this variable to make sure it
12620 // is correctly captured. A variable that shows up in a use_device_ptr has
12621 // similar properties of a first private variable.
12622 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12623
12624 // Create a mappable component for the list item. List items in this clause
12625 // only need a component.
12626 MVLI.VarBaseDeclarations.push_back(D);
12627 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12628 MVLI.VarComponents.back().push_back(
12629 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012630 }
12631
Samuel Antaocc10b852016-07-28 14:23:26 +000012632 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012633 return nullptr;
12634
Samuel Antaocc10b852016-07-28 14:23:26 +000012635 return OMPUseDevicePtrClause::Create(
12636 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12637 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012638}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012639
12640OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12641 SourceLocation StartLoc,
12642 SourceLocation LParenLoc,
12643 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012644 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012645 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012646 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012647 SourceLocation ELoc;
12648 SourceRange ERange;
12649 Expr *SimpleRefExpr = RefExpr;
12650 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12651 if (Res.second) {
12652 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012653 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012654 }
12655 ValueDecl *D = Res.first;
12656 if (!D)
12657 continue;
12658
12659 QualType Type = D->getType();
12660 // item should be a pointer or array or reference to pointer or array
12661 if (!Type.getNonReferenceType()->isPointerType() &&
12662 !Type.getNonReferenceType()->isArrayType()) {
12663 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12664 << 0 << RefExpr->getSourceRange();
12665 continue;
12666 }
Samuel Antao6890b092016-07-28 14:25:09 +000012667
12668 // Check if the declaration in the clause does not show up in any data
12669 // sharing attribute.
12670 auto DVar = DSAStack->getTopDSA(D, false);
12671 if (isOpenMPPrivate(DVar.CKind)) {
12672 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12673 << getOpenMPClauseName(DVar.CKind)
12674 << getOpenMPClauseName(OMPC_is_device_ptr)
12675 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12676 ReportOriginalDSA(*this, DSAStack, D, DVar);
12677 continue;
12678 }
12679
12680 Expr *ConflictExpr;
12681 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012682 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012683 [&ConflictExpr](
12684 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12685 OpenMPClauseKind) -> bool {
12686 ConflictExpr = R.front().getAssociatedExpression();
12687 return true;
12688 })) {
12689 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12690 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12691 << ConflictExpr->getSourceRange();
12692 continue;
12693 }
12694
12695 // Store the components in the stack so that they can be used to check
12696 // against other clauses later on.
12697 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12698 DSAStack->addMappableExpressionComponents(
12699 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12700
12701 // Record the expression we've just processed.
12702 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12703
12704 // Create a mappable component for the list item. List items in this clause
12705 // only need a component. We use a null declaration to signal fields in
12706 // 'this'.
12707 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12708 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12709 "Unexpected device pointer expression!");
12710 MVLI.VarBaseDeclarations.push_back(
12711 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12712 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12713 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012714 }
12715
Samuel Antao6890b092016-07-28 14:25:09 +000012716 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012717 return nullptr;
12718
Samuel Antao6890b092016-07-28 14:25:09 +000012719 return OMPIsDevicePtrClause::Create(
12720 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12721 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012722}