blob: 3938f68968442538b6605c8c3a464fa5cf1dee4f [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) {
838 auto *VD = buildVarDecl(SemaRef, SourceLocation(),
839 SemaRef.Context.VoidPtrTy, ".task_red.");
840 TaskgroupReductionRef = buildDeclRefExpr(
841 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
842 }
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) {
861 auto *VD = buildVarDecl(SemaRef, SourceLocation(),
862 SemaRef.Context.VoidPtrTy, ".task_red.");
863 TaskgroupReductionRef = buildDeclRefExpr(
864 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
865 }
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;
969 }
970
Alexey Bataev4b465392017-04-26 15:06:24 +0000971 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000972 // Not in OpenMP execution region and top scope was already checked.
973 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000974
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000976 // in a Construct, C/C++, predetermined, p.4]
977 // Static data members are shared.
978 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
979 // in a Construct, C/C++, predetermined, p.7]
980 // Variables with static storage duration that are declared in a scope
981 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000982 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000983 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000984 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000985 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000986 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000987
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000988 DVar.CKind = OMPC_shared;
989 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000990 }
991
992 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000993 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
994 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000995 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
996 // in a Construct, C/C++, predetermined, p.6]
997 // Variables with const qualified type having no mutable member are
998 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000999 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001000 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001001 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1002 if (auto *CTD = CTSD->getSpecializedTemplate())
1003 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001004 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001005 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1006 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001007 // Variables with const-qualified type having no mutable member may be
1008 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001009 DSAVarData DVarTemp = hasDSA(
1010 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1011 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001012 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1013 return DVar;
1014
Alexey Bataev758e55e2013-09-06 18:03:48 +00001015 DVar.CKind = OMPC_shared;
1016 return DVar;
1017 }
1018
Alexey Bataev758e55e2013-09-06 18:03:48 +00001019 // Explicitly specified attributes and local variables with predetermined
1020 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001021 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001022 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001023 if (FromParent && I != EndI)
1024 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001025 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001026 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001027 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001028 DVar.CKind = I->SharingMap[D].Attributes;
1029 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001030 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001031 }
1032
1033 return DVar;
1034}
1035
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001036DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1037 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001038 if (isStackEmpty()) {
1039 StackTy::reverse_iterator I;
1040 return getDSA(I, D);
1041 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001042 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001043 auto StartI = Stack.back().first.rbegin();
1044 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001045 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001046 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001047 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048}
1049
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001050DSAStackTy::DSAVarData
1051DSAStackTy::hasDSA(ValueDecl *D,
1052 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1053 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1054 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001055 if (isStackEmpty())
1056 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001057 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001058 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001059 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001060 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001061 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001062 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001063 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001064 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001065 auto NewI = I;
1066 DSAVarData DVar = getDSA(NewI, D);
1067 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001068 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001069 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001070 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001071}
1072
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001073DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1074 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1075 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1076 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001077 if (isStackEmpty())
1078 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001079 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001080 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001081 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001082 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001083 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001084 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001085 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001086 auto NewI = StartI;
1087 DSAVarData DVar = getDSA(NewI, D);
1088 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001089}
1090
Alexey Bataevaac108a2015-06-23 04:51:00 +00001091bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001092 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001093 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001094 if (CPred(ClauseKindMode))
1095 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001096 if (isStackEmpty())
1097 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001098 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001099 auto StartI = Stack.back().first.begin();
1100 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001101 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001102 return false;
1103 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001104 return (StartI->SharingMap.count(D) > 0) &&
1105 StartI->SharingMap[D].RefExpr.getPointer() &&
1106 CPred(StartI->SharingMap[D].Attributes) &&
1107 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001108}
1109
Samuel Antao4be30e92015-10-02 17:14:03 +00001110bool DSAStackTy::hasExplicitDirective(
1111 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1112 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001113 if (isStackEmpty())
1114 return false;
1115 auto StartI = Stack.back().first.begin();
1116 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001117 if (std::distance(StartI, EndI) <= (int)Level)
1118 return false;
1119 std::advance(StartI, Level);
1120 return DPred(StartI->Directive);
1121}
1122
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001123bool DSAStackTy::hasDirective(
1124 const llvm::function_ref<bool(OpenMPDirectiveKind,
1125 const DeclarationNameInfo &, SourceLocation)>
1126 &DPred,
1127 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001128 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001129 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001130 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001131 auto StartI = std::next(Stack.back().first.rbegin());
1132 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001133 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001134 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001135 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1136 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1137 return true;
1138 }
1139 return false;
1140}
1141
Alexey Bataev758e55e2013-09-06 18:03:48 +00001142void Sema::InitDataSharingAttributesStack() {
1143 VarDataSharingAttributesStack = new DSAStackTy(*this);
1144}
1145
1146#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1147
Alexey Bataev4b465392017-04-26 15:06:24 +00001148void Sema::pushOpenMPFunctionRegion() {
1149 DSAStack->pushFunction();
1150}
1151
1152void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1153 DSAStack->popFunction(OldFSI);
1154}
1155
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001156bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001157 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1158
1159 auto &Ctx = getASTContext();
1160 bool IsByRef = true;
1161
1162 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001163 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001164 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001165
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001166 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001167 // This table summarizes how a given variable should be passed to the device
1168 // given its type and the clauses where it appears. This table is based on
1169 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1170 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1171 //
1172 // =========================================================================
1173 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1174 // | |(tofrom:scalar)| | pvt | | | |
1175 // =========================================================================
1176 // | scl | | | | - | | bycopy|
1177 // | scl | | - | x | - | - | bycopy|
1178 // | scl | | x | - | - | - | null |
1179 // | scl | x | | | - | | byref |
1180 // | scl | x | - | x | - | - | bycopy|
1181 // | scl | x | x | - | - | - | null |
1182 // | scl | | - | - | - | x | byref |
1183 // | scl | x | - | - | - | x | byref |
1184 //
1185 // | agg | n.a. | | | - | | byref |
1186 // | agg | n.a. | - | x | - | - | byref |
1187 // | agg | n.a. | x | - | - | - | null |
1188 // | agg | n.a. | - | - | - | x | byref |
1189 // | agg | n.a. | - | - | - | x[] | byref |
1190 //
1191 // | ptr | n.a. | | | - | | bycopy|
1192 // | ptr | n.a. | - | x | - | - | bycopy|
1193 // | ptr | n.a. | x | - | - | - | null |
1194 // | ptr | n.a. | - | - | - | x | byref |
1195 // | ptr | n.a. | - | - | - | x[] | bycopy|
1196 // | ptr | n.a. | - | - | x | | bycopy|
1197 // | ptr | n.a. | - | - | x | x | bycopy|
1198 // | ptr | n.a. | - | - | x | x[] | bycopy|
1199 // =========================================================================
1200 // Legend:
1201 // scl - scalar
1202 // ptr - pointer
1203 // agg - aggregate
1204 // x - applies
1205 // - - invalid in this combination
1206 // [] - mapped with an array section
1207 // byref - should be mapped by reference
1208 // byval - should be mapped by value
1209 // null - initialize a local variable to null on the device
1210 //
1211 // Observations:
1212 // - All scalar declarations that show up in a map clause have to be passed
1213 // by reference, because they may have been mapped in the enclosing data
1214 // environment.
1215 // - If the scalar value does not fit the size of uintptr, it has to be
1216 // passed by reference, regardless the result in the table above.
1217 // - For pointers mapped by value that have either an implicit map or an
1218 // array section, the runtime library may pass the NULL value to the
1219 // device instead of the value passed to it by the compiler.
1220
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001221 if (Ty->isReferenceType())
1222 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001223
1224 // Locate map clauses and see if the variable being captured is referred to
1225 // in any of those clauses. Here we only care about variables, not fields,
1226 // because fields are part of aggregates.
1227 bool IsVariableUsedInMapClause = false;
1228 bool IsVariableAssociatedWithSection = false;
1229
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001230 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1231 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001232 MapExprComponents,
1233 OpenMPClauseKind WhereFoundClauseKind) {
1234 // Only the map clause information influences how a variable is
1235 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001236 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001237 if (WhereFoundClauseKind != OMPC_map)
1238 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001239
1240 auto EI = MapExprComponents.rbegin();
1241 auto EE = MapExprComponents.rend();
1242
1243 assert(EI != EE && "Invalid map expression!");
1244
1245 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1246 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1247
1248 ++EI;
1249 if (EI == EE)
1250 return false;
1251
1252 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1253 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1254 isa<MemberExpr>(EI->getAssociatedExpression())) {
1255 IsVariableAssociatedWithSection = true;
1256 // There is nothing more we need to know about this variable.
1257 return true;
1258 }
1259
1260 // Keep looking for more map info.
1261 return false;
1262 });
1263
1264 if (IsVariableUsedInMapClause) {
1265 // If variable is identified in a map clause it is always captured by
1266 // reference except if it is a pointer that is dereferenced somehow.
1267 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1268 } else {
1269 // By default, all the data that has a scalar type is mapped by copy.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001270 IsByRef = !Ty->isScalarType() ||
1271 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
Samuel Antao86ace552016-04-27 22:40:57 +00001272 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001273 }
1274
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001275 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1276 IsByRef = !DSAStack->hasExplicitDSA(
1277 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1278 Level, /*NotLastprivate=*/true);
1279 }
1280
Samuel Antao86ace552016-04-27 22:40:57 +00001281 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001282 // and alignment, because the runtime library only deals with uintptr types.
1283 // If it does not fit the uintptr size, we need to pass the data by reference
1284 // instead.
1285 if (!IsByRef &&
1286 (Ctx.getTypeSizeInChars(Ty) >
1287 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001288 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001289 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001290 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001291
1292 return IsByRef;
1293}
1294
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001295unsigned Sema::getOpenMPNestingLevel() const {
1296 assert(getLangOpts().OpenMP);
1297 return DSAStack->getNestingLevel();
1298}
1299
Alexey Bataev90c228f2016-02-08 09:29:13 +00001300VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001301 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001302 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001303
1304 // If we are attempting to capture a global variable in a directive with
1305 // 'target' we return true so that this global is also mapped to the device.
1306 //
1307 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1308 // then it should not be captured. Therefore, an extra check has to be
1309 // inserted here once support for 'declare target' is added.
1310 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001311 auto *VD = dyn_cast<VarDecl>(D);
1312 if (VD && !VD->hasLocalStorage()) {
Alexey Bataev61498fb2017-08-29 19:30:57 +00001313 if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001314 !DSAStack->isClauseParsingMode())
1315 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001316 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001317 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1318 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001319 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001320 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001321 false))
1322 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001323 }
1324
Alexey Bataev48977c32015-08-04 08:10:48 +00001325 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1326 (!DSAStack->isClauseParsingMode() ||
1327 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001328 auto &&Info = DSAStack->isLoopControlVariable(D);
1329 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001330 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001331 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001332 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001333 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001334 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001335 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001336 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001337 DVarPrivate = DSAStack->hasDSA(
1338 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1339 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001340 if (DVarPrivate.CKind != OMPC_unknown)
1341 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001342 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001343 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001344}
1345
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001346bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001347 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1348 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001349 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1350 Level) ||
1351 // Consider taskgroup reduction descriptor variable a private to avoid
1352 // possible capture in the region.
1353 (DSAStack->hasExplicitDirective(
1354 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1355 Level) &&
1356 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001357}
1358
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001359void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1360 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1361 D = getCanonicalDecl(D);
1362 OpenMPClauseKind OMPC = OMPC_unknown;
1363 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1364 const unsigned NewLevel = I - 1;
1365 if (DSAStack->hasExplicitDSA(D,
1366 [&OMPC](const OpenMPClauseKind K) {
1367 if (isOpenMPPrivate(K)) {
1368 OMPC = K;
1369 return true;
1370 }
1371 return false;
1372 },
1373 NewLevel))
1374 break;
1375 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1376 D, NewLevel,
1377 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1378 OpenMPClauseKind) { return true; })) {
1379 OMPC = OMPC_map;
1380 break;
1381 }
1382 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1383 NewLevel)) {
1384 OMPC = OMPC_firstprivate;
1385 break;
1386 }
1387 }
1388 if (OMPC != OMPC_unknown)
1389 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1390}
1391
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001392bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001393 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1394 // Return true if the current level is no longer enclosed in a target region.
1395
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001396 auto *VD = dyn_cast<VarDecl>(D);
1397 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001398 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1399 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001400}
1401
Alexey Bataeved09d242014-05-28 05:53:51 +00001402void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001403
1404void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1405 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001406 Scope *CurScope, SourceLocation Loc) {
1407 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001408 PushExpressionEvaluationContext(
1409 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001410}
1411
Alexey Bataevaac108a2015-06-23 04:51:00 +00001412void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1413 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001414}
1415
Alexey Bataevaac108a2015-06-23 04:51:00 +00001416void Sema::EndOpenMPClause() {
1417 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001418}
1419
Alexey Bataev758e55e2013-09-06 18:03:48 +00001420void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001421 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1422 // A variable of class type (or array thereof) that appears in a lastprivate
1423 // clause requires an accessible, unambiguous default constructor for the
1424 // class type, unless the list item is also specified in a firstprivate
1425 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001426 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001427 for (auto *C : D->clauses()) {
1428 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1429 SmallVector<Expr *, 8> PrivateCopies;
1430 for (auto *DE : Clause->varlists()) {
1431 if (DE->isValueDependent() || DE->isTypeDependent()) {
1432 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001433 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001434 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001435 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001436 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1437 QualType Type = VD->getType().getNonReferenceType();
1438 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001439 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001440 // Generate helper private variable and initialize it with the
1441 // default value. The address of the original variable is replaced
1442 // by the address of the new private variable in CodeGen. This new
1443 // variable is not added to IdResolver, so the code in the OpenMP
1444 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001445 auto *VDPrivate = buildVarDecl(
1446 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001447 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001448 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001449 if (VDPrivate->isInvalidDecl())
1450 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001451 PrivateCopies.push_back(buildDeclRefExpr(
1452 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001453 } else {
1454 // The variable is also a firstprivate, so initialization sequence
1455 // for private copy is generated already.
1456 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001457 }
1458 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001459 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001460 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001461 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001462 }
1463 }
1464 }
1465
Alexey Bataev758e55e2013-09-06 18:03:48 +00001466 DSAStack->pop();
1467 DiscardCleanupsInEvaluationContext();
1468 PopExpressionEvaluationContext();
1469}
1470
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001471static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1472 Expr *NumIterations, Sema &SemaRef,
1473 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001474
Alexey Bataeva769e072013-03-22 06:34:35 +00001475namespace {
1476
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001477class VarDeclFilterCCC : public CorrectionCandidateCallback {
1478private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001479 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001480
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001481public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001482 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001483 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001484 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001485 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001486 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001487 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1488 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001489 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001490 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001491 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001492};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001493
1494class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1495private:
1496 Sema &SemaRef;
1497
1498public:
1499 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1500 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1501 NamedDecl *ND = Candidate.getCorrectionDecl();
1502 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1503 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1504 SemaRef.getCurScope());
1505 }
1506 return false;
1507 }
1508};
1509
Alexey Bataeved09d242014-05-28 05:53:51 +00001510} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001511
1512ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1513 CXXScopeSpec &ScopeSpec,
1514 const DeclarationNameInfo &Id) {
1515 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1516 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1517
1518 if (Lookup.isAmbiguous())
1519 return ExprError();
1520
1521 VarDecl *VD;
1522 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001523 if (TypoCorrection Corrected = CorrectTypo(
1524 Id, LookupOrdinaryName, CurScope, nullptr,
1525 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001526 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001527 PDiag(Lookup.empty()
1528 ? diag::err_undeclared_var_use_suggest
1529 : diag::err_omp_expected_var_arg_suggest)
1530 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001531 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001532 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001533 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1534 : diag::err_omp_expected_var_arg)
1535 << Id.getName();
1536 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001537 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001538 } else {
1539 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001540 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001541 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1542 return ExprError();
1543 }
1544 }
1545 Lookup.suppressDiagnostics();
1546
1547 // OpenMP [2.9.2, Syntax, C/C++]
1548 // Variables must be file-scope, namespace-scope, or static block-scope.
1549 if (!VD->hasGlobalStorage()) {
1550 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001551 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1552 bool IsDecl =
1553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001554 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001555 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1556 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001557 return ExprError();
1558 }
1559
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001560 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1561 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001562 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1563 // A threadprivate directive for file-scope variables must appear outside
1564 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001565 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1566 !getCurLexicalContext()->isTranslationUnit()) {
1567 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001568 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1569 bool IsDecl =
1570 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1571 Diag(VD->getLocation(),
1572 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1573 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001574 return ExprError();
1575 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001576 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1577 // A threadprivate directive for static class member variables must appear
1578 // in the class definition, in the same scope in which the member
1579 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001580 if (CanonicalVD->isStaticDataMember() &&
1581 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1582 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001583 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1584 bool IsDecl =
1585 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1586 Diag(VD->getLocation(),
1587 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1588 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001589 return ExprError();
1590 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001591 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1592 // A threadprivate directive for namespace-scope variables must appear
1593 // outside any definition or declaration other than the namespace
1594 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001595 if (CanonicalVD->getDeclContext()->isNamespace() &&
1596 (!getCurLexicalContext()->isFileContext() ||
1597 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1598 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001599 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1600 bool IsDecl =
1601 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1602 Diag(VD->getLocation(),
1603 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1604 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001605 return ExprError();
1606 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001607 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1608 // A threadprivate directive for static block-scope variables must appear
1609 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001610 if (CanonicalVD->isStaticLocal() && CurScope &&
1611 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001612 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001613 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1614 bool IsDecl =
1615 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1616 Diag(VD->getLocation(),
1617 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1618 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001619 return ExprError();
1620 }
1621
1622 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1623 // A threadprivate directive must lexically precede all references to any
1624 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001625 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001626 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001627 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001628 return ExprError();
1629 }
1630
1631 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001632 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1633 SourceLocation(), VD,
1634 /*RefersToEnclosingVariableOrCapture=*/false,
1635 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001636}
1637
Alexey Bataeved09d242014-05-28 05:53:51 +00001638Sema::DeclGroupPtrTy
1639Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1640 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001641 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001642 CurContext->addDecl(D);
1643 return DeclGroupPtrTy::make(DeclGroupRef(D));
1644 }
David Blaikie0403cb12016-01-15 23:43:25 +00001645 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001646}
1647
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001648namespace {
1649class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1650 Sema &SemaRef;
1651
1652public:
1653 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001654 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001655 if (VD->hasLocalStorage()) {
1656 SemaRef.Diag(E->getLocStart(),
1657 diag::err_omp_local_var_in_threadprivate_init)
1658 << E->getSourceRange();
1659 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1660 << VD << VD->getSourceRange();
1661 return true;
1662 }
1663 }
1664 return false;
1665 }
1666 bool VisitStmt(const Stmt *S) {
1667 for (auto Child : S->children()) {
1668 if (Child && Visit(Child))
1669 return true;
1670 }
1671 return false;
1672 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001673 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001674};
1675} // namespace
1676
Alexey Bataeved09d242014-05-28 05:53:51 +00001677OMPThreadPrivateDecl *
1678Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001679 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001680 for (auto &RefExpr : VarList) {
1681 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001682 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1683 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001684
Alexey Bataev376b4a42016-02-09 09:41:09 +00001685 // Mark variable as used.
1686 VD->setReferenced();
1687 VD->markUsed(Context);
1688
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001689 QualType QType = VD->getType();
1690 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1691 // It will be analyzed later.
1692 Vars.push_back(DE);
1693 continue;
1694 }
1695
Alexey Bataeva769e072013-03-22 06:34:35 +00001696 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1697 // A threadprivate variable must not have an incomplete type.
1698 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001699 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001700 continue;
1701 }
1702
1703 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1704 // A threadprivate variable must not have a reference type.
1705 if (VD->getType()->isReferenceType()) {
1706 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001707 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1708 bool IsDecl =
1709 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1710 Diag(VD->getLocation(),
1711 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1712 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001713 continue;
1714 }
1715
Samuel Antaof8b50122015-07-13 22:54:53 +00001716 // Check if this is a TLS variable. If TLS is not being supported, produce
1717 // the corresponding diagnostic.
1718 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1719 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1720 getLangOpts().OpenMPUseTLS &&
1721 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001722 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1723 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001724 Diag(ILoc, diag::err_omp_var_thread_local)
1725 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001726 bool IsDecl =
1727 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1728 Diag(VD->getLocation(),
1729 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1730 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001731 continue;
1732 }
1733
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001734 // Check if initial value of threadprivate variable reference variable with
1735 // local storage (it is not supported by runtime).
1736 if (auto Init = VD->getAnyInitializer()) {
1737 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001738 if (Checker.Visit(Init))
1739 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001740 }
1741
Alexey Bataeved09d242014-05-28 05:53:51 +00001742 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001743 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001744 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1745 Context, SourceRange(Loc, Loc)));
1746 if (auto *ML = Context.getASTMutationListener())
1747 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001748 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001749 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001750 if (!Vars.empty()) {
1751 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1752 Vars);
1753 D->setAccess(AS_public);
1754 }
1755 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001756}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001757
Alexey Bataev7ff55242014-06-19 09:13:45 +00001758static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001759 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001760 bool IsLoopIterVar = false) {
1761 if (DVar.RefExpr) {
1762 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1763 << getOpenMPClauseName(DVar.CKind);
1764 return;
1765 }
1766 enum {
1767 PDSA_StaticMemberShared,
1768 PDSA_StaticLocalVarShared,
1769 PDSA_LoopIterVarPrivate,
1770 PDSA_LoopIterVarLinear,
1771 PDSA_LoopIterVarLastprivate,
1772 PDSA_ConstVarShared,
1773 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001774 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001775 PDSA_LocalVarPrivate,
1776 PDSA_Implicit
1777 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001778 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001779 auto ReportLoc = D->getLocation();
1780 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001781 if (IsLoopIterVar) {
1782 if (DVar.CKind == OMPC_private)
1783 Reason = PDSA_LoopIterVarPrivate;
1784 else if (DVar.CKind == OMPC_lastprivate)
1785 Reason = PDSA_LoopIterVarLastprivate;
1786 else
1787 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001788 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1789 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001790 Reason = PDSA_TaskVarFirstprivate;
1791 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001792 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001793 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001794 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001795 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001796 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001797 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001798 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001799 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001800 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001801 ReportHint = true;
1802 Reason = PDSA_LocalVarPrivate;
1803 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001804 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001805 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001806 << Reason << ReportHint
1807 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1808 } else if (DVar.ImplicitDSALoc.isValid()) {
1809 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1810 << getOpenMPClauseName(DVar.CKind);
1811 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001812}
1813
Alexey Bataev758e55e2013-09-06 18:03:48 +00001814namespace {
1815class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1816 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001817 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001818 bool ErrorFound;
1819 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001820 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001821 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001822 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001823 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001824
Alexey Bataev758e55e2013-09-06 18:03:48 +00001825public:
1826 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001827 if (E->isTypeDependent() || E->isValueDependent() ||
1828 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1829 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001830 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001831 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001832 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001833 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001834 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001835
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001836 auto DVar = Stack->getTopDSA(VD, false);
1837 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001838 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001839 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001840
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001841 auto ELoc = E->getExprLoc();
1842 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001843 // The default(none) clause requires that each variable that is referenced
1844 // in the construct, and does not have a predetermined data-sharing
1845 // attribute, must have its data-sharing attribute explicitly determined
1846 // by being listed in a data-sharing attribute clause.
1847 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001848 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001849 VarsWithInheritedDSA.count(VD) == 0) {
1850 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001851 return;
1852 }
1853
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001854 if (isOpenMPTargetExecutionDirective(DKind) &&
1855 !Stack->isLoopControlVariable(VD).first) {
1856 if (!Stack->checkMappableExprComponentListsForDecl(
1857 VD, /*CurrentRegionOnly=*/true,
1858 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1859 StackComponents,
1860 OpenMPClauseKind) {
1861 // Variable is used if it has been marked as an array, array
1862 // section or the variable iself.
1863 return StackComponents.size() == 1 ||
1864 std::all_of(
1865 std::next(StackComponents.rbegin()),
1866 StackComponents.rend(),
1867 [](const OMPClauseMappableExprCommon::
1868 MappableComponent &MC) {
1869 return MC.getAssociatedDeclaration() ==
1870 nullptr &&
1871 (isa<OMPArraySectionExpr>(
1872 MC.getAssociatedExpression()) ||
1873 isa<ArraySubscriptExpr>(
1874 MC.getAssociatedExpression()));
1875 });
1876 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001877 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001878 // By default lambdas are captured as firstprivates.
1879 if (const auto *RD =
1880 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001881 IsFirstprivate = RD->isLambda();
1882 IsFirstprivate =
1883 IsFirstprivate ||
1884 (VD->getType().getNonReferenceType()->isScalarType() &&
1885 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1886 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001887 ImplicitFirstprivate.emplace_back(E);
1888 else
1889 ImplicitMap.emplace_back(E);
1890 return;
1891 }
1892 }
1893
Alexey Bataev758e55e2013-09-06 18:03:48 +00001894 // OpenMP [2.9.3.6, Restrictions, p.2]
1895 // A list item that appears in a reduction clause of the innermost
1896 // enclosing worksharing or parallel construct may not be accessed in an
1897 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001898 DVar = Stack->hasInnermostDSA(
1899 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1900 [](OpenMPDirectiveKind K) -> bool {
1901 return isOpenMPParallelDirective(K) ||
1902 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1903 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001904 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001905 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001906 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001907 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1908 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001909 return;
1910 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001911
1912 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001913 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001914 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1915 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001916 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001917 }
1918 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001919 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001920 if (E->isTypeDependent() || E->isValueDependent() ||
1921 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1922 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001923 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1924 if (!FD)
1925 return;
1926 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001927 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001928 auto DVar = Stack->getTopDSA(FD, false);
1929 // Check if the variable has explicit DSA set and stop analysis if it
1930 // so.
1931 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1932 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001933
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001934 if (isOpenMPTargetExecutionDirective(DKind) &&
1935 !Stack->isLoopControlVariable(FD).first &&
1936 !Stack->checkMappableExprComponentListsForDecl(
1937 FD, /*CurrentRegionOnly=*/true,
1938 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1939 StackComponents,
1940 OpenMPClauseKind) {
1941 return isa<CXXThisExpr>(
1942 cast<MemberExpr>(
1943 StackComponents.back().getAssociatedExpression())
1944 ->getBase()
1945 ->IgnoreParens());
1946 })) {
1947 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1948 // A bit-field cannot appear in a map clause.
1949 //
1950 if (FD->isBitField()) {
1951 SemaRef.Diag(E->getMemberLoc(),
1952 diag::err_omp_bit_fields_forbidden_in_clause)
1953 << E->getSourceRange() << getOpenMPClauseName(OMPC_map);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001954 return;
1955 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001956 ImplicitMap.emplace_back(E);
1957 return;
1958 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001959
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001960 auto ELoc = E->getExprLoc();
1961 // OpenMP [2.9.3.6, Restrictions, p.2]
1962 // A list item that appears in a reduction clause of the innermost
1963 // enclosing worksharing or parallel construct may not be accessed in
1964 // an explicit task.
1965 DVar = Stack->hasInnermostDSA(
1966 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1967 [](OpenMPDirectiveKind K) -> bool {
1968 return isOpenMPParallelDirective(K) ||
1969 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1970 },
1971 /*FromParent=*/true);
1972 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1973 ErrorFound = true;
1974 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1975 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1976 return;
1977 }
1978
1979 // Define implicit data-sharing attributes for task.
1980 DVar = Stack->getImplicitDSA(FD, false);
1981 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1982 !Stack->isLoopControlVariable(FD).first)
1983 ImplicitFirstprivate.push_back(E);
1984 return;
1985 }
1986 if (isOpenMPTargetExecutionDirective(DKind) && !FD->isBitField()) {
1987 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
1988 CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map);
1989 auto *VD = cast<ValueDecl>(
1990 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
1991 if (!Stack->checkMappableExprComponentListsForDecl(
1992 VD, /*CurrentRegionOnly=*/true,
1993 [&CurComponents](
1994 OMPClauseMappableExprCommon::MappableExprComponentListRef
1995 StackComponents,
1996 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001997 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00001998 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001999 for (const auto &SC : llvm::reverse(StackComponents)) {
2000 // Do both expressions have the same kind?
2001 if (CCI->getAssociatedExpression()->getStmtClass() !=
2002 SC.getAssociatedExpression()->getStmtClass())
2003 if (!(isa<OMPArraySectionExpr>(
2004 SC.getAssociatedExpression()) &&
2005 isa<ArraySubscriptExpr>(
2006 CCI->getAssociatedExpression())))
2007 return false;
2008
2009 Decl *CCD = CCI->getAssociatedDeclaration();
2010 Decl *SCD = SC.getAssociatedDeclaration();
2011 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2012 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2013 if (SCD != CCD)
2014 return false;
2015 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002016 if (CCI == CCE)
2017 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002018 }
2019 return true;
2020 })) {
2021 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002022 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002023 } else
2024 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002025 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002026 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002027 for (auto *C : S->clauses()) {
2028 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002029 // for task|target directives.
2030 // Skip analysis of arguments of implicitly defined map clause for target
2031 // directives.
2032 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2033 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002034 for (auto *CC : C->children()) {
2035 if (CC)
2036 Visit(CC);
2037 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002038 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002039 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002040 }
2041 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002042 for (auto *C : S->children()) {
2043 if (C && !isa<OMPExecutableDirective>(C))
2044 Visit(C);
2045 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002046 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002047
2048 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002049 ArrayRef<Expr *> getImplicitFirstprivate() const {
2050 return ImplicitFirstprivate;
2051 }
2052 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002053 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002054 return VarsWithInheritedDSA;
2055 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002056
Alexey Bataev7ff55242014-06-19 09:13:45 +00002057 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2058 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002059};
Alexey Bataeved09d242014-05-28 05:53:51 +00002060} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002061
Alexey Bataevbae9a792014-06-27 10:37:06 +00002062void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002063 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002064 case OMPD_parallel:
2065 case OMPD_parallel_for:
2066 case OMPD_parallel_for_simd:
2067 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002068 case OMPD_teams:
2069 case OMPD_teams_distribute: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002070 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002071 QualType KmpInt32PtrTy =
2072 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002073 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002074 std::make_pair(".global_tid.", KmpInt32PtrTy),
2075 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2076 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002077 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002078 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2079 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002080 break;
2081 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002082 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002083 case OMPD_target_parallel: {
2084 Sema::CapturedParamNameType ParamsTarget[] = {
2085 std::make_pair(StringRef(), QualType()) // __context with shared vars
2086 };
2087 // Start a captured region for 'target' with no implicit parameters.
2088 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2089 ParamsTarget);
2090 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2091 QualType KmpInt32PtrTy =
2092 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002093 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002094 std::make_pair(".global_tid.", KmpInt32PtrTy),
2095 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2096 std::make_pair(StringRef(), QualType()) // __context with shared vars
2097 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002098 // Start a captured region for 'teams' or 'parallel'. Both regions have
2099 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002100 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002101 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002102 break;
2103 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002104 case OMPD_simd:
2105 case OMPD_for:
2106 case OMPD_for_simd:
2107 case OMPD_sections:
2108 case OMPD_section:
2109 case OMPD_single:
2110 case OMPD_master:
2111 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002112 case OMPD_taskgroup:
2113 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00002114 case OMPD_ordered:
2115 case OMPD_atomic:
2116 case OMPD_target_data:
2117 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00002118 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00002119 case OMPD_target_parallel_for_simd:
2120 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002121 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002122 std::make_pair(StringRef(), QualType()) // __context with shared vars
2123 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002124 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2125 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002126 break;
2127 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002128 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002129 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002130 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2131 FunctionProtoType::ExtProtoInfo EPI;
2132 EPI.Variadic = true;
2133 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002134 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002135 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002136 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2137 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2138 std::make_pair(".copy_fn.",
2139 Context.getPointerType(CopyFnType).withConst()),
2140 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002141 std::make_pair(StringRef(), QualType()) // __context with shared vars
2142 };
2143 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2144 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002145 // Mark this captured region as inlined, because we don't use outlined
2146 // function directly.
2147 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2148 AlwaysInlineAttr::CreateImplicit(
2149 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002150 break;
2151 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002152 case OMPD_taskloop:
2153 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002154 QualType KmpInt32Ty =
2155 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2156 QualType KmpUInt64Ty =
2157 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2158 QualType KmpInt64Ty =
2159 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2160 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2161 FunctionProtoType::ExtProtoInfo EPI;
2162 EPI.Variadic = true;
2163 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002164 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002165 std::make_pair(".global_tid.", KmpInt32Ty),
2166 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2167 std::make_pair(".privates.",
2168 Context.VoidPtrTy.withConst().withRestrict()),
2169 std::make_pair(
2170 ".copy_fn.",
2171 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2172 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2173 std::make_pair(".lb.", KmpUInt64Ty),
2174 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2175 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002176 std::make_pair(".reductions.",
2177 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002178 std::make_pair(StringRef(), QualType()) // __context with shared vars
2179 };
2180 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2181 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002182 // Mark this captured region as inlined, because we don't use outlined
2183 // function directly.
2184 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2185 AlwaysInlineAttr::CreateImplicit(
2186 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002187 break;
2188 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002189 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00002190 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00002191 case OMPD_distribute_parallel_for:
Kelvin Li579e41c2016-11-30 23:51:03 +00002192 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00002193 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00002194 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00002195 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00002196 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00002197 case OMPD_target_teams_distribute_parallel_for_simd:
2198 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002199 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2200 QualType KmpInt32PtrTy =
2201 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2202 Sema::CapturedParamNameType Params[] = {
2203 std::make_pair(".global_tid.", KmpInt32PtrTy),
2204 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2205 std::make_pair(".previous.lb.", Context.getSizeType()),
2206 std::make_pair(".previous.ub.", Context.getSizeType()),
2207 std::make_pair(StringRef(), QualType()) // __context with shared vars
2208 };
2209 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2210 Params);
2211 break;
2212 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002213 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002214 case OMPD_taskyield:
2215 case OMPD_barrier:
2216 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002217 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002218 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002219 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00002220 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00002221 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002222 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002223 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002224 case OMPD_declare_target:
2225 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00002226 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00002227 llvm_unreachable("OpenMP Directive is not allowed");
2228 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002229 llvm_unreachable("Unknown OpenMP directive");
2230 }
2231}
2232
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002233int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2234 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2235 getOpenMPCaptureRegions(CaptureRegions, DKind);
2236 return CaptureRegions.size();
2237}
2238
Alexey Bataev3392d762016-02-16 11:18:12 +00002239static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002240 Expr *CaptureExpr, bool WithInit,
2241 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002242 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002243 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002244 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002245 QualType Ty = Init->getType();
2246 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2247 if (S.getLangOpts().CPlusPlus)
2248 Ty = C.getLValueReferenceType(Ty);
2249 else {
2250 Ty = C.getPointerType(Ty);
2251 ExprResult Res =
2252 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2253 if (!Res.isUsable())
2254 return nullptr;
2255 Init = Res.get();
2256 }
Alexey Bataev61205072016-03-02 04:57:40 +00002257 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002258 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002259 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2260 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002261 if (!WithInit)
2262 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002263 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002264 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002265 return CED;
2266}
2267
Alexey Bataev61205072016-03-02 04:57:40 +00002268static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2269 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002270 OMPCapturedExprDecl *CD;
2271 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2272 CD = cast<OMPCapturedExprDecl>(VD);
2273 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002274 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2275 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002276 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002277 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002278}
2279
Alexey Bataev5a3af132016-03-29 08:58:54 +00002280static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2281 if (!Ref) {
2282 auto *CD =
2283 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2284 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2285 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2286 CaptureExpr->getExprLoc());
2287 }
2288 ExprResult Res = Ref;
2289 if (!S.getLangOpts().CPlusPlus &&
2290 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2291 Ref->getType()->isPointerType())
2292 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2293 if (!Res.isUsable())
2294 return ExprError();
2295 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002296}
2297
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002298namespace {
2299// OpenMP directives parsed in this section are represented as a
2300// CapturedStatement with an associated statement. If a syntax error
2301// is detected during the parsing of the associated statement, the
2302// compiler must abort processing and close the CapturedStatement.
2303//
2304// Combined directives such as 'target parallel' have more than one
2305// nested CapturedStatements. This RAII ensures that we unwind out
2306// of all the nested CapturedStatements when an error is found.
2307class CaptureRegionUnwinderRAII {
2308private:
2309 Sema &S;
2310 bool &ErrorFound;
2311 OpenMPDirectiveKind DKind;
2312
2313public:
2314 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2315 OpenMPDirectiveKind DKind)
2316 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2317 ~CaptureRegionUnwinderRAII() {
2318 if (ErrorFound) {
2319 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2320 while (--ThisCaptureLevel >= 0)
2321 S.ActOnCapturedRegionError();
2322 }
2323 }
2324};
2325} // namespace
2326
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002327StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2328 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002329 bool ErrorFound = false;
2330 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2331 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002332 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002333 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002334 return StmtError();
2335 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002336
2337 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002338 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002339 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002340 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002341 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002342 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002343 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2344 Clause->getClauseKind() == OMPC_in_reduction) {
2345 // Capture taskgroup task_reduction descriptors inside the tasking regions
2346 // with the corresponding in_reduction items.
2347 auto *IRC = cast<OMPInReductionClause>(Clause);
2348 for (auto *E : IRC->taskgroup_descriptors())
2349 if (E)
2350 MarkDeclarationsReferencedInExpr(E);
2351 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002352 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002353 Clause->getClauseKind() == OMPC_copyprivate ||
2354 (getLangOpts().OpenMPUseTLS &&
2355 getASTContext().getTargetInfo().isTLSSupported() &&
2356 Clause->getClauseKind() == OMPC_copyin)) {
2357 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002358 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002359 for (auto *VarRef : Clause->children()) {
2360 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002361 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002362 }
2363 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002364 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002365 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002366 if (auto *C = OMPClauseWithPreInit::get(Clause))
2367 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002368 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2369 if (auto *E = C->getPostUpdateExpr())
2370 MarkDeclarationsReferencedInExpr(E);
2371 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002372 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002373 if (Clause->getClauseKind() == OMPC_schedule)
2374 SC = cast<OMPScheduleClause>(Clause);
2375 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002376 OC = cast<OMPOrderedClause>(Clause);
2377 else if (Clause->getClauseKind() == OMPC_linear)
2378 LCs.push_back(cast<OMPLinearClause>(Clause));
2379 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002380 // OpenMP, 2.7.1 Loop Construct, Restrictions
2381 // The nonmonotonic modifier cannot be specified if an ordered clause is
2382 // specified.
2383 if (SC &&
2384 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2385 SC->getSecondScheduleModifier() ==
2386 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2387 OC) {
2388 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2389 ? SC->getFirstScheduleModifierLoc()
2390 : SC->getSecondScheduleModifierLoc(),
2391 diag::err_omp_schedule_nonmonotonic_ordered)
2392 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2393 ErrorFound = true;
2394 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002395 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2396 for (auto *C : LCs) {
2397 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2398 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2399 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002400 ErrorFound = true;
2401 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002402 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2403 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2404 OC->getNumForLoops()) {
2405 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2406 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2407 ErrorFound = true;
2408 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002409 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002410 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002411 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002412 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002413 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2414 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2415 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2416 // Mark all variables in private list clauses as used in inner region.
2417 // Required for proper codegen of combined directives.
2418 // TODO: add processing for other clauses.
2419 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2420 for (auto *C : PICs) {
2421 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2422 // Find the particular capture region for the clause if the
2423 // directive is a combined one with multiple capture regions.
2424 // If the directive is not a combined one, the capture region
2425 // associated with the clause is OMPD_unknown and is generated
2426 // only once.
2427 if (CaptureRegion == ThisCaptureRegion ||
2428 CaptureRegion == OMPD_unknown) {
2429 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2430 for (auto *D : DS->decls())
2431 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2432 }
2433 }
2434 }
2435 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002436 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002437 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002438 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002439}
2440
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002441static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2442 OpenMPDirectiveKind CancelRegion,
2443 SourceLocation StartLoc) {
2444 // CancelRegion is only needed for cancel and cancellation_point.
2445 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2446 return false;
2447
2448 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2449 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2450 return false;
2451
2452 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2453 << getOpenMPDirectiveName(CancelRegion);
2454 return true;
2455}
2456
2457static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002458 OpenMPDirectiveKind CurrentRegion,
2459 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002460 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002461 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002462 if (Stack->getCurScope()) {
2463 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002464 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002465 bool NestingProhibited = false;
2466 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002467 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002468 enum {
2469 NoRecommend,
2470 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002471 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002472 ShouldBeInTargetRegion,
2473 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002474 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002475 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002476 // OpenMP [2.16, Nesting of Regions]
2477 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002478 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002479 // An ordered construct with the simd clause is the only OpenMP
2480 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002481 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002482 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2483 // message.
2484 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2485 ? diag::err_omp_prohibited_region_simd
2486 : diag::warn_omp_nesting_simd);
2487 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002488 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002489 if (ParentRegion == OMPD_atomic) {
2490 // OpenMP [2.16, Nesting of Regions]
2491 // OpenMP constructs may not be nested inside an atomic region.
2492 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2493 return true;
2494 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002495 if (CurrentRegion == OMPD_section) {
2496 // OpenMP [2.7.2, sections Construct, Restrictions]
2497 // Orphaned section directives are prohibited. That is, the section
2498 // directives must appear within the sections construct and must not be
2499 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002500 if (ParentRegion != OMPD_sections &&
2501 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002502 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2503 << (ParentRegion != OMPD_unknown)
2504 << getOpenMPDirectiveName(ParentRegion);
2505 return true;
2506 }
2507 return false;
2508 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002509 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002510 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002511 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002512 if (ParentRegion == OMPD_unknown &&
2513 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002514 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002515 if (CurrentRegion == OMPD_cancellation_point ||
2516 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002517 // OpenMP [2.16, Nesting of Regions]
2518 // A cancellation point construct for which construct-type-clause is
2519 // taskgroup must be nested inside a task construct. A cancellation
2520 // point construct for which construct-type-clause is not taskgroup must
2521 // be closely nested inside an OpenMP construct that matches the type
2522 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002523 // A cancel construct for which construct-type-clause is taskgroup must be
2524 // nested inside a task construct. A cancel construct for which
2525 // construct-type-clause is not taskgroup must be closely nested inside an
2526 // OpenMP construct that matches the type specified in
2527 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002528 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002529 !((CancelRegion == OMPD_parallel &&
2530 (ParentRegion == OMPD_parallel ||
2531 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002532 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002533 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2534 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002535 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2536 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002537 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2538 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002539 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002540 // OpenMP [2.16, Nesting of Regions]
2541 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002542 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002543 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002544 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002545 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2546 // OpenMP [2.16, Nesting of Regions]
2547 // A critical region may not be nested (closely or otherwise) inside a
2548 // critical region with the same name. Note that this restriction is not
2549 // sufficient to prevent deadlock.
2550 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002551 bool DeadLock = Stack->hasDirective(
2552 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2553 const DeclarationNameInfo &DNI,
2554 SourceLocation Loc) -> bool {
2555 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2556 PreviousCriticalLoc = Loc;
2557 return true;
2558 } else
2559 return false;
2560 },
2561 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002562 if (DeadLock) {
2563 SemaRef.Diag(StartLoc,
2564 diag::err_omp_prohibited_region_critical_same_name)
2565 << CurrentName.getName();
2566 if (PreviousCriticalLoc.isValid())
2567 SemaRef.Diag(PreviousCriticalLoc,
2568 diag::note_omp_previous_critical_region);
2569 return true;
2570 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002571 } else if (CurrentRegion == OMPD_barrier) {
2572 // OpenMP [2.16, Nesting of Regions]
2573 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002574 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002575 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2576 isOpenMPTaskingDirective(ParentRegion) ||
2577 ParentRegion == OMPD_master ||
2578 ParentRegion == OMPD_critical ||
2579 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002580 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002581 !isOpenMPParallelDirective(CurrentRegion) &&
2582 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002583 // OpenMP [2.16, Nesting of Regions]
2584 // A worksharing region may not be closely nested inside a worksharing,
2585 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002586 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2587 isOpenMPTaskingDirective(ParentRegion) ||
2588 ParentRegion == OMPD_master ||
2589 ParentRegion == OMPD_critical ||
2590 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002591 Recommend = ShouldBeInParallelRegion;
2592 } else if (CurrentRegion == OMPD_ordered) {
2593 // OpenMP [2.16, Nesting of Regions]
2594 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002595 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002596 // An ordered region must be closely nested inside a loop region (or
2597 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002598 // OpenMP [2.8.1,simd Construct, Restrictions]
2599 // An ordered construct with the simd clause is the only OpenMP construct
2600 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002601 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002602 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002603 !(isOpenMPSimdDirective(ParentRegion) ||
2604 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002605 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002606 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002607 // OpenMP [2.16, Nesting of Regions]
2608 // If specified, a teams construct must be contained within a target
2609 // construct.
2610 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002611 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002612 Recommend = ShouldBeInTargetRegion;
2613 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2614 }
Kelvin Libf594a52016-12-17 05:48:59 +00002615 if (!NestingProhibited &&
2616 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2617 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2618 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002619 // OpenMP [2.16, Nesting of Regions]
2620 // distribute, parallel, parallel sections, parallel workshare, and the
2621 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2622 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002623 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2624 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002625 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002626 }
David Majnemer9d168222016-08-05 17:44:54 +00002627 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002628 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002629 // OpenMP 4.5 [2.17 Nesting of Regions]
2630 // The region associated with the distribute construct must be strictly
2631 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002632 NestingProhibited =
2633 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002634 Recommend = ShouldBeInTeamsRegion;
2635 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002636 if (!NestingProhibited &&
2637 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2638 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2639 // OpenMP 4.5 [2.17 Nesting of Regions]
2640 // If a target, target update, target data, target enter data, or
2641 // target exit data construct is encountered during execution of a
2642 // target region, the behavior is unspecified.
2643 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002644 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2645 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002646 if (isOpenMPTargetExecutionDirective(K)) {
2647 OffendingRegion = K;
2648 return true;
2649 } else
2650 return false;
2651 },
2652 false /* don't skip top directive */);
2653 CloseNesting = false;
2654 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002655 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002656 if (OrphanSeen) {
2657 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2658 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2659 } else {
2660 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2661 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2662 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2663 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002664 return true;
2665 }
2666 }
2667 return false;
2668}
2669
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002670static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2671 ArrayRef<OMPClause *> Clauses,
2672 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2673 bool ErrorFound = false;
2674 unsigned NamedModifiersNumber = 0;
2675 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2676 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002677 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002678 for (const auto *C : Clauses) {
2679 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2680 // At most one if clause without a directive-name-modifier can appear on
2681 // the directive.
2682 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2683 if (FoundNameModifiers[CurNM]) {
2684 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2685 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2686 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2687 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002688 } else if (CurNM != OMPD_unknown) {
2689 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002690 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002691 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002692 FoundNameModifiers[CurNM] = IC;
2693 if (CurNM == OMPD_unknown)
2694 continue;
2695 // Check if the specified name modifier is allowed for the current
2696 // directive.
2697 // At most one if clause with the particular directive-name-modifier can
2698 // appear on the directive.
2699 bool MatchFound = false;
2700 for (auto NM : AllowedNameModifiers) {
2701 if (CurNM == NM) {
2702 MatchFound = true;
2703 break;
2704 }
2705 }
2706 if (!MatchFound) {
2707 S.Diag(IC->getNameModifierLoc(),
2708 diag::err_omp_wrong_if_directive_name_modifier)
2709 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2710 ErrorFound = true;
2711 }
2712 }
2713 }
2714 // If any if clause on the directive includes a directive-name-modifier then
2715 // all if clauses on the directive must include a directive-name-modifier.
2716 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2717 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2718 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2719 diag::err_omp_no_more_if_clause);
2720 } else {
2721 std::string Values;
2722 std::string Sep(", ");
2723 unsigned AllowedCnt = 0;
2724 unsigned TotalAllowedNum =
2725 AllowedNameModifiers.size() - NamedModifiersNumber;
2726 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2727 ++Cnt) {
2728 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2729 if (!FoundNameModifiers[NM]) {
2730 Values += "'";
2731 Values += getOpenMPDirectiveName(NM);
2732 Values += "'";
2733 if (AllowedCnt + 2 == TotalAllowedNum)
2734 Values += " or ";
2735 else if (AllowedCnt + 1 != TotalAllowedNum)
2736 Values += Sep;
2737 ++AllowedCnt;
2738 }
2739 }
2740 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2741 diag::err_omp_unnamed_if_clause)
2742 << (TotalAllowedNum > 1) << Values;
2743 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002744 for (auto Loc : NameModifierLoc) {
2745 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2746 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002747 ErrorFound = true;
2748 }
2749 return ErrorFound;
2750}
2751
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002752StmtResult Sema::ActOnOpenMPExecutableDirective(
2753 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2754 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2755 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002756 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002757 // First check CancelRegion which is then used in checkNestingOfRegions.
2758 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2759 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002760 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002761 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002762
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002763 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002764 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002765 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002766 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002767 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002768 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2769
2770 // Check default data sharing attributes for referenced variables.
2771 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002772 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2773 Stmt *S = AStmt;
2774 while (--ThisCaptureLevel >= 0)
2775 S = cast<CapturedStmt>(S)->getCapturedStmt();
2776 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002777 if (DSAChecker.isErrorFound())
2778 return StmtError();
2779 // Generate list of implicitly defined firstprivate variables.
2780 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002781
Alexey Bataev88202be2017-07-27 13:20:36 +00002782 SmallVector<Expr *, 4> ImplicitFirstprivates(
2783 DSAChecker.getImplicitFirstprivate().begin(),
2784 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002785 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2786 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002787 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2788 for (auto *C : Clauses) {
2789 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2790 for (auto *E : IRC->taskgroup_descriptors())
2791 if (E)
2792 ImplicitFirstprivates.emplace_back(E);
2793 }
2794 }
2795 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002796 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002797 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2798 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002799 ClausesWithImplicit.push_back(Implicit);
2800 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002801 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002802 } else
2803 ErrorFound = true;
2804 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002805 if (!ImplicitMaps.empty()) {
2806 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2807 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2808 SourceLocation(), SourceLocation(), ImplicitMaps,
2809 SourceLocation(), SourceLocation(), SourceLocation())) {
2810 ClausesWithImplicit.emplace_back(Implicit);
2811 ErrorFound |=
2812 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2813 } else
2814 ErrorFound = true;
2815 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002816 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002817
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002818 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002819 switch (Kind) {
2820 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002821 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2822 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002823 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002824 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002825 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002826 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2827 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002828 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002829 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002830 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2831 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002832 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002833 case OMPD_for_simd:
2834 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2835 EndLoc, VarsWithInheritedDSA);
2836 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002837 case OMPD_sections:
2838 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2839 EndLoc);
2840 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002841 case OMPD_section:
2842 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002843 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002844 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2845 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002846 case OMPD_single:
2847 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2848 EndLoc);
2849 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002850 case OMPD_master:
2851 assert(ClausesWithImplicit.empty() &&
2852 "No clauses are allowed for 'omp master' directive");
2853 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2854 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002855 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002856 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2857 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002858 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002859 case OMPD_parallel_for:
2860 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2861 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002862 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002863 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002864 case OMPD_parallel_for_simd:
2865 Res = ActOnOpenMPParallelForSimdDirective(
2866 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002867 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002868 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002869 case OMPD_parallel_sections:
2870 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2871 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002872 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002873 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002874 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002875 Res =
2876 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002877 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002878 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002879 case OMPD_taskyield:
2880 assert(ClausesWithImplicit.empty() &&
2881 "No clauses are allowed for 'omp taskyield' directive");
2882 assert(AStmt == nullptr &&
2883 "No associated statement allowed for 'omp taskyield' directive");
2884 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2885 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002886 case OMPD_barrier:
2887 assert(ClausesWithImplicit.empty() &&
2888 "No clauses are allowed for 'omp barrier' directive");
2889 assert(AStmt == nullptr &&
2890 "No associated statement allowed for 'omp barrier' directive");
2891 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2892 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002893 case OMPD_taskwait:
2894 assert(ClausesWithImplicit.empty() &&
2895 "No clauses are allowed for 'omp taskwait' directive");
2896 assert(AStmt == nullptr &&
2897 "No associated statement allowed for 'omp taskwait' directive");
2898 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2899 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002900 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002901 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2902 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002903 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002904 case OMPD_flush:
2905 assert(AStmt == nullptr &&
2906 "No associated statement allowed for 'omp flush' directive");
2907 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2908 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002909 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002910 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2911 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002912 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002913 case OMPD_atomic:
2914 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2915 EndLoc);
2916 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002917 case OMPD_teams:
2918 Res =
2919 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2920 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002921 case OMPD_target:
2922 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2923 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002924 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002925 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002926 case OMPD_target_parallel:
2927 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2928 StartLoc, EndLoc);
2929 AllowedNameModifiers.push_back(OMPD_target);
2930 AllowedNameModifiers.push_back(OMPD_parallel);
2931 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002932 case OMPD_target_parallel_for:
2933 Res = ActOnOpenMPTargetParallelForDirective(
2934 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2935 AllowedNameModifiers.push_back(OMPD_target);
2936 AllowedNameModifiers.push_back(OMPD_parallel);
2937 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002938 case OMPD_cancellation_point:
2939 assert(ClausesWithImplicit.empty() &&
2940 "No clauses are allowed for 'omp cancellation point' directive");
2941 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2942 "cancellation point' directive");
2943 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2944 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002945 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002946 assert(AStmt == nullptr &&
2947 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002948 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2949 CancelRegion);
2950 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002951 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002952 case OMPD_target_data:
2953 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2954 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002955 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002956 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002957 case OMPD_target_enter_data:
2958 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2959 EndLoc);
2960 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2961 break;
Samuel Antao72590762016-01-19 20:04:50 +00002962 case OMPD_target_exit_data:
2963 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2964 EndLoc);
2965 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2966 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002967 case OMPD_taskloop:
2968 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2969 EndLoc, VarsWithInheritedDSA);
2970 AllowedNameModifiers.push_back(OMPD_taskloop);
2971 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002972 case OMPD_taskloop_simd:
2973 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2974 EndLoc, VarsWithInheritedDSA);
2975 AllowedNameModifiers.push_back(OMPD_taskloop);
2976 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002977 case OMPD_distribute:
2978 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2979 EndLoc, VarsWithInheritedDSA);
2980 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002981 case OMPD_target_update:
2982 assert(!AStmt && "Statement is not allowed for target update");
2983 Res =
2984 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2985 AllowedNameModifiers.push_back(OMPD_target_update);
2986 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002987 case OMPD_distribute_parallel_for:
2988 Res = ActOnOpenMPDistributeParallelForDirective(
2989 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2990 AllowedNameModifiers.push_back(OMPD_parallel);
2991 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002992 case OMPD_distribute_parallel_for_simd:
2993 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2994 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2995 AllowedNameModifiers.push_back(OMPD_parallel);
2996 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002997 case OMPD_distribute_simd:
2998 Res = ActOnOpenMPDistributeSimdDirective(
2999 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3000 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003001 case OMPD_target_parallel_for_simd:
3002 Res = ActOnOpenMPTargetParallelForSimdDirective(
3003 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3004 AllowedNameModifiers.push_back(OMPD_target);
3005 AllowedNameModifiers.push_back(OMPD_parallel);
3006 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003007 case OMPD_target_simd:
3008 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3009 EndLoc, VarsWithInheritedDSA);
3010 AllowedNameModifiers.push_back(OMPD_target);
3011 break;
Kelvin Li02532872016-08-05 14:37:37 +00003012 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003013 Res = ActOnOpenMPTeamsDistributeDirective(
3014 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003015 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003016 case OMPD_teams_distribute_simd:
3017 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3018 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3019 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003020 case OMPD_teams_distribute_parallel_for_simd:
3021 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3022 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3023 AllowedNameModifiers.push_back(OMPD_parallel);
3024 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003025 case OMPD_teams_distribute_parallel_for:
3026 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3027 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3028 AllowedNameModifiers.push_back(OMPD_parallel);
3029 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003030 case OMPD_target_teams:
3031 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3032 EndLoc);
3033 AllowedNameModifiers.push_back(OMPD_target);
3034 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003035 case OMPD_target_teams_distribute:
3036 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3037 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3038 AllowedNameModifiers.push_back(OMPD_target);
3039 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003040 case OMPD_target_teams_distribute_parallel_for:
3041 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3042 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3043 AllowedNameModifiers.push_back(OMPD_target);
3044 AllowedNameModifiers.push_back(OMPD_parallel);
3045 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003046 case OMPD_target_teams_distribute_parallel_for_simd:
3047 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3048 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3049 AllowedNameModifiers.push_back(OMPD_target);
3050 AllowedNameModifiers.push_back(OMPD_parallel);
3051 break;
Kelvin Lida681182017-01-10 18:08:18 +00003052 case OMPD_target_teams_distribute_simd:
3053 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3054 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3055 AllowedNameModifiers.push_back(OMPD_target);
3056 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003057 case OMPD_declare_target:
3058 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003059 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003060 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003061 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003062 llvm_unreachable("OpenMP Directive is not allowed");
3063 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003064 llvm_unreachable("Unknown OpenMP directive");
3065 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003066
Alexey Bataev4acb8592014-07-07 13:01:15 +00003067 for (auto P : VarsWithInheritedDSA) {
3068 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3069 << P.first << P.second->getSourceRange();
3070 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003071 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3072
3073 if (!AllowedNameModifiers.empty())
3074 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3075 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003076
Alexey Bataeved09d242014-05-28 05:53:51 +00003077 if (ErrorFound)
3078 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003079 return Res;
3080}
3081
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003082Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3083 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003084 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003085 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3086 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003087 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003088 assert(Linears.size() == LinModifiers.size());
3089 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003090 if (!DG || DG.get().isNull())
3091 return DeclGroupPtrTy();
3092
3093 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003094 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003095 return DG;
3096 }
3097 auto *ADecl = DG.get().getSingleDecl();
3098 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3099 ADecl = FTD->getTemplatedDecl();
3100
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003101 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3102 if (!FD) {
3103 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003104 return DeclGroupPtrTy();
3105 }
3106
Alexey Bataev2af33e32016-04-07 12:45:37 +00003107 // OpenMP [2.8.2, declare simd construct, Description]
3108 // The parameter of the simdlen clause must be a constant positive integer
3109 // expression.
3110 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003111 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003112 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003113 // OpenMP [2.8.2, declare simd construct, Description]
3114 // The special this pointer can be used as if was one of the arguments to the
3115 // function in any of the linear, aligned, or uniform clauses.
3116 // The uniform clause declares one or more arguments to have an invariant
3117 // value for all concurrent invocations of the function in the execution of a
3118 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003119 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3120 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003121 for (auto *E : Uniforms) {
3122 E = E->IgnoreParenImpCasts();
3123 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3124 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3125 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3126 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003127 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3128 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003129 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003130 }
3131 if (isa<CXXThisExpr>(E)) {
3132 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003133 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003134 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003135 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3136 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003137 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003138 // OpenMP [2.8.2, declare simd construct, Description]
3139 // The aligned clause declares that the object to which each list item points
3140 // is aligned to the number of bytes expressed in the optional parameter of
3141 // the aligned clause.
3142 // The special this pointer can be used as if was one of the arguments to the
3143 // function in any of the linear, aligned, or uniform clauses.
3144 // The type of list items appearing in the aligned clause must be array,
3145 // pointer, reference to array, or reference to pointer.
3146 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3147 Expr *AlignedThis = nullptr;
3148 for (auto *E : Aligneds) {
3149 E = E->IgnoreParenImpCasts();
3150 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3151 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3152 auto *CanonPVD = PVD->getCanonicalDecl();
3153 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3154 FD->getParamDecl(PVD->getFunctionScopeIndex())
3155 ->getCanonicalDecl() == CanonPVD) {
3156 // OpenMP [2.8.1, simd construct, Restrictions]
3157 // A list-item cannot appear in more than one aligned clause.
3158 if (AlignedArgs.count(CanonPVD) > 0) {
3159 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3160 << 1 << E->getSourceRange();
3161 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3162 diag::note_omp_explicit_dsa)
3163 << getOpenMPClauseName(OMPC_aligned);
3164 continue;
3165 }
3166 AlignedArgs[CanonPVD] = E;
3167 QualType QTy = PVD->getType()
3168 .getNonReferenceType()
3169 .getUnqualifiedType()
3170 .getCanonicalType();
3171 const Type *Ty = QTy.getTypePtrOrNull();
3172 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3173 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3174 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3175 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3176 }
3177 continue;
3178 }
3179 }
3180 if (isa<CXXThisExpr>(E)) {
3181 if (AlignedThis) {
3182 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3183 << 2 << E->getSourceRange();
3184 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3185 << getOpenMPClauseName(OMPC_aligned);
3186 }
3187 AlignedThis = E;
3188 continue;
3189 }
3190 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3191 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3192 }
3193 // The optional parameter of the aligned clause, alignment, must be a constant
3194 // positive integer expression. If no optional parameter is specified,
3195 // implementation-defined default alignments for SIMD instructions on the
3196 // target platforms are assumed.
3197 SmallVector<Expr *, 4> NewAligns;
3198 for (auto *E : Alignments) {
3199 ExprResult Align;
3200 if (E)
3201 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3202 NewAligns.push_back(Align.get());
3203 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003204 // OpenMP [2.8.2, declare simd construct, Description]
3205 // The linear clause declares one or more list items to be private to a SIMD
3206 // lane and to have a linear relationship with respect to the iteration space
3207 // of a loop.
3208 // The special this pointer can be used as if was one of the arguments to the
3209 // function in any of the linear, aligned, or uniform clauses.
3210 // When a linear-step expression is specified in a linear clause it must be
3211 // either a constant integer expression or an integer-typed parameter that is
3212 // specified in a uniform clause on the directive.
3213 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3214 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3215 auto MI = LinModifiers.begin();
3216 for (auto *E : Linears) {
3217 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3218 ++MI;
3219 E = E->IgnoreParenImpCasts();
3220 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3221 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3222 auto *CanonPVD = PVD->getCanonicalDecl();
3223 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3224 FD->getParamDecl(PVD->getFunctionScopeIndex())
3225 ->getCanonicalDecl() == CanonPVD) {
3226 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3227 // A list-item cannot appear in more than one linear clause.
3228 if (LinearArgs.count(CanonPVD) > 0) {
3229 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3230 << getOpenMPClauseName(OMPC_linear)
3231 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3232 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3233 diag::note_omp_explicit_dsa)
3234 << getOpenMPClauseName(OMPC_linear);
3235 continue;
3236 }
3237 // Each argument can appear in at most one uniform or linear clause.
3238 if (UniformedArgs.count(CanonPVD) > 0) {
3239 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3240 << getOpenMPClauseName(OMPC_linear)
3241 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3242 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3243 diag::note_omp_explicit_dsa)
3244 << getOpenMPClauseName(OMPC_uniform);
3245 continue;
3246 }
3247 LinearArgs[CanonPVD] = E;
3248 if (E->isValueDependent() || E->isTypeDependent() ||
3249 E->isInstantiationDependent() ||
3250 E->containsUnexpandedParameterPack())
3251 continue;
3252 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3253 PVD->getOriginalType());
3254 continue;
3255 }
3256 }
3257 if (isa<CXXThisExpr>(E)) {
3258 if (UniformedLinearThis) {
3259 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3260 << getOpenMPClauseName(OMPC_linear)
3261 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3262 << E->getSourceRange();
3263 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3264 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3265 : OMPC_linear);
3266 continue;
3267 }
3268 UniformedLinearThis = E;
3269 if (E->isValueDependent() || E->isTypeDependent() ||
3270 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3271 continue;
3272 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3273 E->getType());
3274 continue;
3275 }
3276 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3277 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3278 }
3279 Expr *Step = nullptr;
3280 Expr *NewStep = nullptr;
3281 SmallVector<Expr *, 4> NewSteps;
3282 for (auto *E : Steps) {
3283 // Skip the same step expression, it was checked already.
3284 if (Step == E || !E) {
3285 NewSteps.push_back(E ? NewStep : nullptr);
3286 continue;
3287 }
3288 Step = E;
3289 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3290 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3291 auto *CanonPVD = PVD->getCanonicalDecl();
3292 if (UniformedArgs.count(CanonPVD) == 0) {
3293 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3294 << Step->getSourceRange();
3295 } else if (E->isValueDependent() || E->isTypeDependent() ||
3296 E->isInstantiationDependent() ||
3297 E->containsUnexpandedParameterPack() ||
3298 CanonPVD->getType()->hasIntegerRepresentation())
3299 NewSteps.push_back(Step);
3300 else {
3301 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3302 << Step->getSourceRange();
3303 }
3304 continue;
3305 }
3306 NewStep = Step;
3307 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3308 !Step->isInstantiationDependent() &&
3309 !Step->containsUnexpandedParameterPack()) {
3310 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3311 .get();
3312 if (NewStep)
3313 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3314 }
3315 NewSteps.push_back(NewStep);
3316 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003317 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3318 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003319 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003320 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3321 const_cast<Expr **>(Linears.data()), Linears.size(),
3322 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3323 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003324 ADecl->addAttr(NewAttr);
3325 return ConvertDeclToDeclGroup(ADecl);
3326}
3327
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003328StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3329 Stmt *AStmt,
3330 SourceLocation StartLoc,
3331 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003332 if (!AStmt)
3333 return StmtError();
3334
Alexey Bataev9959db52014-05-06 10:08:46 +00003335 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3336 // 1.2.2 OpenMP Language Terminology
3337 // Structured block - An executable statement with a single entry at the
3338 // top and a single exit at the bottom.
3339 // The point of exit cannot be a branch out of the structured block.
3340 // longjmp() and throw() must not violate the entry/exit criteria.
3341 CS->getCapturedDecl()->setNothrow();
3342
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003343 getCurFunction()->setHasBranchProtectedScope();
3344
Alexey Bataev25e5b442015-09-15 12:52:43 +00003345 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3346 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003347}
3348
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003349namespace {
3350/// \brief Helper class for checking canonical form of the OpenMP loops and
3351/// extracting iteration space of each loop in the loop nest, that will be used
3352/// for IR generation.
3353class OpenMPIterationSpaceChecker {
3354 /// \brief Reference to Sema.
3355 Sema &SemaRef;
3356 /// \brief A location for diagnostics (when there is no some better location).
3357 SourceLocation DefaultLoc;
3358 /// \brief A location for diagnostics (when increment is not compatible).
3359 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003360 /// \brief A source location for referring to loop init later.
3361 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003362 /// \brief A source location for referring to condition later.
3363 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003364 /// \brief A source location for referring to increment later.
3365 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003366 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003367 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003368 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003369 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003370 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003371 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003372 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003373 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003374 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003375 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003376 /// \brief This flag is true when condition is one of:
3377 /// Var < UB
3378 /// Var <= UB
3379 /// UB > Var
3380 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003381 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003382 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003383 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003384 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003385 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003386
3387public:
3388 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003389 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003390 /// \brief Check init-expr for canonical loop form and save loop counter
3391 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003392 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003393 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3394 /// for less/greater and for strict/non-strict comparison.
3395 bool CheckCond(Expr *S);
3396 /// \brief Check incr-expr for canonical loop form and return true if it
3397 /// does not conform, otherwise save loop step (#Step).
3398 bool CheckInc(Expr *S);
3399 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003400 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003401 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003402 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003403 /// \brief Source range of the loop init.
3404 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3405 /// \brief Source range of the loop condition.
3406 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3407 /// \brief Source range of the loop increment.
3408 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3409 /// \brief True if the step should be subtracted.
3410 bool ShouldSubtractStep() const { return SubtractStep; }
3411 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003412 Expr *
3413 BuildNumIterations(Scope *S, const bool LimitedType,
3414 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003415 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003416 Expr *BuildPreCond(Scope *S, Expr *Cond,
3417 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003418 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003419 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3420 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003421 /// \brief Build reference expression to the private counter be used for
3422 /// codegen.
3423 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003424 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003425 Expr *BuildCounterInit() const;
3426 /// \brief Build step of the counter be used for codegen.
3427 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003428 /// \brief Return true if any expression is dependent.
3429 bool Dependent() const;
3430
3431private:
3432 /// \brief Check the right-hand side of an assignment in the increment
3433 /// expression.
3434 bool CheckIncRHS(Expr *RHS);
3435 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003436 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003437 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003438 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003439 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003440 /// \brief Helper to set loop increment.
3441 bool SetStep(Expr *NewStep, bool Subtract);
3442};
3443
3444bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003445 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003446 assert(!LB && !UB && !Step);
3447 return false;
3448 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003449 return LCDecl->getType()->isDependentType() ||
3450 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3451 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003452}
3453
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003454bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3455 Expr *NewLCRefExpr,
3456 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003457 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003458 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003459 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003460 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003461 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003462 LCDecl = getCanonicalDecl(NewLCDecl);
3463 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003464 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3465 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003466 if ((Ctor->isCopyOrMoveConstructor() ||
3467 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3468 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003469 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003470 LB = NewLB;
3471 return false;
3472}
3473
3474bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003475 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003476 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003477 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3478 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003479 if (!NewUB)
3480 return true;
3481 UB = NewUB;
3482 TestIsLessOp = LessOp;
3483 TestIsStrictOp = StrictOp;
3484 ConditionSrcRange = SR;
3485 ConditionLoc = SL;
3486 return false;
3487}
3488
3489bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3490 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003491 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003492 if (!NewStep)
3493 return true;
3494 if (!NewStep->isValueDependent()) {
3495 // Check that the step is integer expression.
3496 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003497 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3498 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003499 if (Val.isInvalid())
3500 return true;
3501 NewStep = Val.get();
3502
3503 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3504 // If test-expr is of form var relational-op b and relational-op is < or
3505 // <= then incr-expr must cause var to increase on each iteration of the
3506 // loop. If test-expr is of form var relational-op b and relational-op is
3507 // > or >= then incr-expr must cause var to decrease on each iteration of
3508 // the loop.
3509 // If test-expr is of form b relational-op var and relational-op is < or
3510 // <= then incr-expr must cause var to decrease on each iteration of the
3511 // loop. If test-expr is of form b relational-op var and relational-op is
3512 // > or >= then incr-expr must cause var to increase on each iteration of
3513 // the loop.
3514 llvm::APSInt Result;
3515 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3516 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3517 bool IsConstNeg =
3518 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003519 bool IsConstPos =
3520 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003521 bool IsConstZero = IsConstant && !Result.getBoolValue();
3522 if (UB && (IsConstZero ||
3523 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003524 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003525 SemaRef.Diag(NewStep->getExprLoc(),
3526 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003527 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003528 SemaRef.Diag(ConditionLoc,
3529 diag::note_omp_loop_cond_requres_compatible_incr)
3530 << TestIsLessOp << ConditionSrcRange;
3531 return true;
3532 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003533 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003534 NewStep =
3535 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3536 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003537 Subtract = !Subtract;
3538 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003539 }
3540
3541 Step = NewStep;
3542 SubtractStep = Subtract;
3543 return false;
3544}
3545
Alexey Bataev9c821032015-04-30 04:23:23 +00003546bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003547 // Check init-expr for canonical loop form and save loop counter
3548 // variable - #Var and its initialization value - #LB.
3549 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3550 // var = lb
3551 // integer-type var = lb
3552 // random-access-iterator-type var = lb
3553 // pointer-type var = lb
3554 //
3555 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003556 if (EmitDiags) {
3557 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3558 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003559 return true;
3560 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003561 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3562 if (!ExprTemp->cleanupsHaveSideEffects())
3563 S = ExprTemp->getSubExpr();
3564
Alexander Musmana5f070a2014-10-01 06:03:56 +00003565 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003566 if (Expr *E = dyn_cast<Expr>(S))
3567 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003568 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003569 if (BO->getOpcode() == BO_Assign) {
3570 auto *LHS = BO->getLHS()->IgnoreParens();
3571 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3572 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3573 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3574 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3575 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3576 }
3577 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3578 if (ME->isArrow() &&
3579 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3580 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3581 }
3582 }
David Majnemer9d168222016-08-05 17:44:54 +00003583 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003584 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003585 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003586 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003587 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003588 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003589 SemaRef.Diag(S->getLocStart(),
3590 diag::ext_omp_loop_not_canonical_init)
3591 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003592 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003593 }
3594 }
3595 }
David Majnemer9d168222016-08-05 17:44:54 +00003596 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003597 if (CE->getOperator() == OO_Equal) {
3598 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003599 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003600 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3601 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3602 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3603 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3604 }
3605 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3606 if (ME->isArrow() &&
3607 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3608 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3609 }
3610 }
3611 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003612
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003613 if (Dependent() || SemaRef.CurContext->isDependentContext())
3614 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003615 if (EmitDiags) {
3616 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3617 << S->getSourceRange();
3618 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003619 return true;
3620}
3621
Alexey Bataev23b69422014-06-18 07:08:49 +00003622/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003623/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003624static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003625 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003626 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003627 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003628 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3629 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003630 if ((Ctor->isCopyOrMoveConstructor() ||
3631 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3632 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003633 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003634 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003635 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003636 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003637 }
3638 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3639 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3640 return getCanonicalDecl(ME->getMemberDecl());
3641 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003642}
3643
3644bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3645 // Check test-expr for canonical form, save upper-bound UB, flags for
3646 // less/greater and for strict/non-strict comparison.
3647 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3648 // var relational-op b
3649 // b relational-op var
3650 //
3651 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003652 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003653 return true;
3654 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003655 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003656 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003657 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003658 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003659 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003660 return SetUB(BO->getRHS(),
3661 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3662 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3663 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003664 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003665 return SetUB(BO->getLHS(),
3666 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3667 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3668 BO->getSourceRange(), BO->getOperatorLoc());
3669 }
David Majnemer9d168222016-08-05 17:44:54 +00003670 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003671 if (CE->getNumArgs() == 2) {
3672 auto Op = CE->getOperator();
3673 switch (Op) {
3674 case OO_Greater:
3675 case OO_GreaterEqual:
3676 case OO_Less:
3677 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003678 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003679 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3680 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3681 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003682 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003683 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3684 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3685 CE->getOperatorLoc());
3686 break;
3687 default:
3688 break;
3689 }
3690 }
3691 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003692 if (Dependent() || SemaRef.CurContext->isDependentContext())
3693 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003694 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003695 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003696 return true;
3697}
3698
3699bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3700 // RHS of canonical loop form increment can be:
3701 // var + incr
3702 // incr + var
3703 // var - incr
3704 //
3705 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003706 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003707 if (BO->isAdditiveOp()) {
3708 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003709 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003710 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003711 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003712 return SetStep(BO->getLHS(), false);
3713 }
David Majnemer9d168222016-08-05 17:44:54 +00003714 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003715 bool IsAdd = CE->getOperator() == OO_Plus;
3716 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003717 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003718 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003719 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003720 return SetStep(CE->getArg(0), false);
3721 }
3722 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003723 if (Dependent() || SemaRef.CurContext->isDependentContext())
3724 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003725 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003726 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003727 return true;
3728}
3729
3730bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3731 // Check incr-expr for canonical loop form and return true if it
3732 // does not conform.
3733 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3734 // ++var
3735 // var++
3736 // --var
3737 // var--
3738 // var += incr
3739 // var -= incr
3740 // var = var + incr
3741 // var = incr + var
3742 // var = var - incr
3743 //
3744 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003745 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003746 return true;
3747 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003748 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3749 if (!ExprTemp->cleanupsHaveSideEffects())
3750 S = ExprTemp->getSubExpr();
3751
Alexander Musmana5f070a2014-10-01 06:03:56 +00003752 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003753 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003754 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003755 if (UO->isIncrementDecrementOp() &&
3756 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003757 return SetStep(SemaRef
3758 .ActOnIntegerConstant(UO->getLocStart(),
3759 (UO->isDecrementOp() ? -1 : 1))
3760 .get(),
3761 false);
3762 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003763 switch (BO->getOpcode()) {
3764 case BO_AddAssign:
3765 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003766 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003767 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3768 break;
3769 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003770 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003771 return CheckIncRHS(BO->getRHS());
3772 break;
3773 default:
3774 break;
3775 }
David Majnemer9d168222016-08-05 17:44:54 +00003776 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003777 switch (CE->getOperator()) {
3778 case OO_PlusPlus:
3779 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003780 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003781 return SetStep(SemaRef
3782 .ActOnIntegerConstant(
3783 CE->getLocStart(),
3784 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3785 .get(),
3786 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003787 break;
3788 case OO_PlusEqual:
3789 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003790 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003791 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3792 break;
3793 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003794 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003795 return CheckIncRHS(CE->getArg(1));
3796 break;
3797 default:
3798 break;
3799 }
3800 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003801 if (Dependent() || SemaRef.CurContext->isDependentContext())
3802 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003803 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003804 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003805 return true;
3806}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003807
Alexey Bataev5a3af132016-03-29 08:58:54 +00003808static ExprResult
3809tryBuildCapture(Sema &SemaRef, Expr *Capture,
3810 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003811 if (SemaRef.CurContext->isDependentContext())
3812 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003813 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3814 return SemaRef.PerformImplicitConversion(
3815 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3816 /*AllowExplicit=*/true);
3817 auto I = Captures.find(Capture);
3818 if (I != Captures.end())
3819 return buildCapture(SemaRef, Capture, I->second);
3820 DeclRefExpr *Ref = nullptr;
3821 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3822 Captures[Capture] = Ref;
3823 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003824}
3825
Alexander Musmana5f070a2014-10-01 06:03:56 +00003826/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003827Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3828 Scope *S, const bool LimitedType,
3829 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003830 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003831 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003832 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003833 SemaRef.getLangOpts().CPlusPlus) {
3834 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003835 auto *UBExpr = TestIsLessOp ? UB : LB;
3836 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003837 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3838 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003839 if (!Upper || !Lower)
3840 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003841
3842 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3843
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003844 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003845 // BuildBinOp already emitted error, this one is to point user to upper
3846 // and lower bound, and to tell what is passed to 'operator-'.
3847 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3848 << Upper->getSourceRange() << Lower->getSourceRange();
3849 return nullptr;
3850 }
3851 }
3852
3853 if (!Diff.isUsable())
3854 return nullptr;
3855
3856 // Upper - Lower [- 1]
3857 if (TestIsStrictOp)
3858 Diff = SemaRef.BuildBinOp(
3859 S, DefaultLoc, BO_Sub, Diff.get(),
3860 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3861 if (!Diff.isUsable())
3862 return nullptr;
3863
3864 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003865 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3866 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003867 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003868 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003869 if (!Diff.isUsable())
3870 return nullptr;
3871
3872 // Parentheses (for dumping/debugging purposes only).
3873 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3874 if (!Diff.isUsable())
3875 return nullptr;
3876
3877 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003878 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003879 if (!Diff.isUsable())
3880 return nullptr;
3881
Alexander Musman174b3ca2014-10-06 11:16:29 +00003882 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003883 QualType Type = Diff.get()->getType();
3884 auto &C = SemaRef.Context;
3885 bool UseVarType = VarType->hasIntegerRepresentation() &&
3886 C.getTypeSize(Type) > C.getTypeSize(VarType);
3887 if (!Type->isIntegerType() || UseVarType) {
3888 unsigned NewSize =
3889 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3890 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3891 : Type->hasSignedIntegerRepresentation();
3892 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003893 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3894 Diff = SemaRef.PerformImplicitConversion(
3895 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3896 if (!Diff.isUsable())
3897 return nullptr;
3898 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003899 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003900 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003901 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3902 if (NewSize != C.getTypeSize(Type)) {
3903 if (NewSize < C.getTypeSize(Type)) {
3904 assert(NewSize == 64 && "incorrect loop var size");
3905 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3906 << InitSrcRange << ConditionSrcRange;
3907 }
3908 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003909 NewSize, Type->hasSignedIntegerRepresentation() ||
3910 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003911 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3912 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3913 Sema::AA_Converting, true);
3914 if (!Diff.isUsable())
3915 return nullptr;
3916 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003917 }
3918 }
3919
Alexander Musmana5f070a2014-10-01 06:03:56 +00003920 return Diff.get();
3921}
3922
Alexey Bataev5a3af132016-03-29 08:58:54 +00003923Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3924 Scope *S, Expr *Cond,
3925 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003926 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3927 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3928 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003929
Alexey Bataev5a3af132016-03-29 08:58:54 +00003930 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3931 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3932 if (!NewLB.isUsable() || !NewUB.isUsable())
3933 return nullptr;
3934
Alexey Bataev62dbb972015-04-22 11:59:37 +00003935 auto CondExpr = SemaRef.BuildBinOp(
3936 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3937 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003938 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003939 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003940 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3941 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003942 CondExpr = SemaRef.PerformImplicitConversion(
3943 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3944 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003945 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003946 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3947 // Otherwise use original loop conditon and evaluate it in runtime.
3948 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3949}
3950
Alexander Musmana5f070a2014-10-01 06:03:56 +00003951/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003952DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003953 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003954 auto *VD = dyn_cast<VarDecl>(LCDecl);
3955 if (!VD) {
3956 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3957 auto *Ref = buildDeclRefExpr(
3958 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003959 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3960 // If the loop control decl is explicitly marked as private, do not mark it
3961 // as captured again.
3962 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3963 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003964 return Ref;
3965 }
3966 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003967 DefaultLoc);
3968}
3969
3970Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003971 if (LCDecl && !LCDecl->isInvalidDecl()) {
3972 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003973 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003974 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3975 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003976 if (PrivateVar->isInvalidDecl())
3977 return nullptr;
3978 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3979 }
3980 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003981}
3982
Samuel Antao4c8035b2016-12-12 18:00:20 +00003983/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003984Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3985
3986/// \brief Build step of the counter be used for codegen.
3987Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3988
3989/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003990struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003991 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003992 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003993 /// \brief This expression calculates the number of iterations in the loop.
3994 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003995 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003996 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003997 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003998 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003999 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004000 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004001 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004002 /// \brief This is step for the #CounterVar used to generate its update:
4003 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004004 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004005 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004006 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004007 /// \brief Source range of the loop init.
4008 SourceRange InitSrcRange;
4009 /// \brief Source range of the loop condition.
4010 SourceRange CondSrcRange;
4011 /// \brief Source range of the loop increment.
4012 SourceRange IncSrcRange;
4013};
4014
Alexey Bataev23b69422014-06-18 07:08:49 +00004015} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004016
Alexey Bataev9c821032015-04-30 04:23:23 +00004017void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4018 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4019 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004020 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4021 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004022 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4023 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004024 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4025 if (auto *D = ISC.GetLoopDecl()) {
4026 auto *VD = dyn_cast<VarDecl>(D);
4027 if (!VD) {
4028 if (auto *Private = IsOpenMPCapturedDecl(D))
4029 VD = Private;
4030 else {
4031 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4032 /*WithInit=*/false);
4033 VD = cast<VarDecl>(Ref->getDecl());
4034 }
4035 }
4036 DSAStack->addLoopControlVariable(D, VD);
4037 }
4038 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004039 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004040 }
4041}
4042
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004043/// \brief Called on a for stmt to check and extract its iteration space
4044/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004045static bool CheckOpenMPIterationSpace(
4046 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4047 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004048 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004049 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004050 LoopIterationSpace &ResultIterSpace,
4051 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004052 // OpenMP [2.6, Canonical Loop Form]
4053 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004054 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004055 if (!For) {
4056 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004057 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4058 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4059 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4060 if (NestedLoopCount > 1) {
4061 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4062 SemaRef.Diag(DSA.getConstructLoc(),
4063 diag::note_omp_collapse_ordered_expr)
4064 << 2 << CollapseLoopCountExpr->getSourceRange()
4065 << OrderedLoopCountExpr->getSourceRange();
4066 else if (CollapseLoopCountExpr)
4067 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4068 diag::note_omp_collapse_ordered_expr)
4069 << 0 << CollapseLoopCountExpr->getSourceRange();
4070 else
4071 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4072 diag::note_omp_collapse_ordered_expr)
4073 << 1 << OrderedLoopCountExpr->getSourceRange();
4074 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004075 return true;
4076 }
4077 assert(For->getBody());
4078
4079 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4080
4081 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004082 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004083 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004084 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004085
4086 bool HasErrors = false;
4087
4088 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004089 if (auto *LCDecl = ISC.GetLoopDecl()) {
4090 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004091
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004092 // OpenMP [2.6, Canonical Loop Form]
4093 // Var is one of the following:
4094 // A variable of signed or unsigned integer type.
4095 // For C++, a variable of a random access iterator type.
4096 // For C, a variable of a pointer type.
4097 auto VarType = LCDecl->getType().getNonReferenceType();
4098 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4099 !VarType->isPointerType() &&
4100 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4101 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4102 << SemaRef.getLangOpts().CPlusPlus;
4103 HasErrors = true;
4104 }
4105
4106 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4107 // a Construct
4108 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4109 // parallel for construct is (are) private.
4110 // The loop iteration variable in the associated for-loop of a simd
4111 // construct with just one associated for-loop is linear with a
4112 // constant-linear-step that is the increment of the associated for-loop.
4113 // Exclude loop var from the list of variables with implicitly defined data
4114 // sharing attributes.
4115 VarsWithImplicitDSA.erase(LCDecl);
4116
4117 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4118 // in a Construct, C/C++].
4119 // The loop iteration variable in the associated for-loop of a simd
4120 // construct with just one associated for-loop may be listed in a linear
4121 // clause with a constant-linear-step that is the increment of the
4122 // associated for-loop.
4123 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4124 // parallel for construct may be listed in a private or lastprivate clause.
4125 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4126 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4127 // declared in the loop and it is predetermined as a private.
4128 auto PredeterminedCKind =
4129 isOpenMPSimdDirective(DKind)
4130 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4131 : OMPC_private;
4132 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4133 DVar.CKind != PredeterminedCKind) ||
4134 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4135 isOpenMPDistributeDirective(DKind)) &&
4136 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4137 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4138 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4139 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4140 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4141 << getOpenMPClauseName(PredeterminedCKind);
4142 if (DVar.RefExpr == nullptr)
4143 DVar.CKind = PredeterminedCKind;
4144 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4145 HasErrors = true;
4146 } else if (LoopDeclRefExpr != nullptr) {
4147 // Make the loop iteration variable private (for worksharing constructs),
4148 // linear (for simd directives with the only one associated loop) or
4149 // lastprivate (for simd directives with several collapsed or ordered
4150 // loops).
4151 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004152 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4153 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004154 /*FromParent=*/false);
4155 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4156 }
4157
4158 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4159
4160 // Check test-expr.
4161 HasErrors |= ISC.CheckCond(For->getCond());
4162
4163 // Check incr-expr.
4164 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004165 }
4166
Alexander Musmana5f070a2014-10-01 06:03:56 +00004167 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004168 return HasErrors;
4169
Alexander Musmana5f070a2014-10-01 06:03:56 +00004170 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004171 ResultIterSpace.PreCond =
4172 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004173 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004174 DSA.getCurScope(),
4175 (isOpenMPWorksharingDirective(DKind) ||
4176 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4177 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004178 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004179 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004180 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4181 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4182 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4183 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4184 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4185 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4186
Alexey Bataev62dbb972015-04-22 11:59:37 +00004187 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4188 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004189 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004190 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004191 ResultIterSpace.CounterInit == nullptr ||
4192 ResultIterSpace.CounterStep == nullptr);
4193
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004194 return HasErrors;
4195}
4196
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004197/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004198static ExprResult
4199BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4200 ExprResult Start,
4201 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004202 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004203 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4204 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004205 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004206 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004207 VarRef.get()->getType())) {
4208 NewStart = SemaRef.PerformImplicitConversion(
4209 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4210 /*AllowExplicit=*/true);
4211 if (!NewStart.isUsable())
4212 return ExprError();
4213 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004214
4215 auto Init =
4216 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4217 return Init;
4218}
4219
Alexander Musmana5f070a2014-10-01 06:03:56 +00004220/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004221static ExprResult
4222BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4223 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4224 ExprResult Step, bool Subtract,
4225 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004226 // Add parentheses (for debugging purposes only).
4227 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4228 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4229 !Step.isUsable())
4230 return ExprError();
4231
Alexey Bataev5a3af132016-03-29 08:58:54 +00004232 ExprResult NewStep = Step;
4233 if (Captures)
4234 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004235 if (NewStep.isInvalid())
4236 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004237 ExprResult Update =
4238 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004239 if (!Update.isUsable())
4240 return ExprError();
4241
Alexey Bataevc0214e02016-02-16 12:13:49 +00004242 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4243 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004244 ExprResult NewStart = Start;
4245 if (Captures)
4246 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004247 if (NewStart.isInvalid())
4248 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004249
Alexey Bataevc0214e02016-02-16 12:13:49 +00004250 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4251 ExprResult SavedUpdate = Update;
4252 ExprResult UpdateVal;
4253 if (VarRef.get()->getType()->isOverloadableType() ||
4254 NewStart.get()->getType()->isOverloadableType() ||
4255 Update.get()->getType()->isOverloadableType()) {
4256 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4257 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4258 Update =
4259 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4260 if (Update.isUsable()) {
4261 UpdateVal =
4262 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4263 VarRef.get(), SavedUpdate.get());
4264 if (UpdateVal.isUsable()) {
4265 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4266 UpdateVal.get());
4267 }
4268 }
4269 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4270 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004271
Alexey Bataevc0214e02016-02-16 12:13:49 +00004272 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4273 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4274 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4275 NewStart.get(), SavedUpdate.get());
4276 if (!Update.isUsable())
4277 return ExprError();
4278
Alexey Bataev11481f52016-02-17 10:29:05 +00004279 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4280 VarRef.get()->getType())) {
4281 Update = SemaRef.PerformImplicitConversion(
4282 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4283 if (!Update.isUsable())
4284 return ExprError();
4285 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004286
4287 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4288 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004289 return Update;
4290}
4291
4292/// \brief Convert integer expression \a E to make it have at least \a Bits
4293/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004294static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004295 if (E == nullptr)
4296 return ExprError();
4297 auto &C = SemaRef.Context;
4298 QualType OldType = E->getType();
4299 unsigned HasBits = C.getTypeSize(OldType);
4300 if (HasBits >= Bits)
4301 return ExprResult(E);
4302 // OK to convert to signed, because new type has more bits than old.
4303 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4304 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4305 true);
4306}
4307
4308/// \brief Check if the given expression \a E is a constant integer that fits
4309/// into \a Bits bits.
4310static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4311 if (E == nullptr)
4312 return false;
4313 llvm::APSInt Result;
4314 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4315 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4316 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004317}
4318
Alexey Bataev5a3af132016-03-29 08:58:54 +00004319/// Build preinits statement for the given declarations.
4320static Stmt *buildPreInits(ASTContext &Context,
4321 SmallVectorImpl<Decl *> &PreInits) {
4322 if (!PreInits.empty()) {
4323 return new (Context) DeclStmt(
4324 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4325 SourceLocation(), SourceLocation());
4326 }
4327 return nullptr;
4328}
4329
4330/// Build preinits statement for the given declarations.
4331static Stmt *buildPreInits(ASTContext &Context,
4332 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4333 if (!Captures.empty()) {
4334 SmallVector<Decl *, 16> PreInits;
4335 for (auto &Pair : Captures)
4336 PreInits.push_back(Pair.second->getDecl());
4337 return buildPreInits(Context, PreInits);
4338 }
4339 return nullptr;
4340}
4341
4342/// Build postupdate expression for the given list of postupdates expressions.
4343static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4344 Expr *PostUpdate = nullptr;
4345 if (!PostUpdates.empty()) {
4346 for (auto *E : PostUpdates) {
4347 Expr *ConvE = S.BuildCStyleCastExpr(
4348 E->getExprLoc(),
4349 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4350 E->getExprLoc(), E)
4351 .get();
4352 PostUpdate = PostUpdate
4353 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4354 PostUpdate, ConvE)
4355 .get()
4356 : ConvE;
4357 }
4358 }
4359 return PostUpdate;
4360}
4361
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004362/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004363/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4364/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004365static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004366CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4367 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4368 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004369 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004370 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004371 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004372 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004373 // Found 'collapse' clause - calculate collapse number.
4374 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004375 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004376 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004377 }
4378 if (OrderedLoopCountExpr) {
4379 // Found 'ordered' clause - calculate collapse number.
4380 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004381 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4382 if (Result.getLimitedValue() < NestedLoopCount) {
4383 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4384 diag::err_omp_wrong_ordered_loop_count)
4385 << OrderedLoopCountExpr->getSourceRange();
4386 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4387 diag::note_collapse_loop_count)
4388 << CollapseLoopCountExpr->getSourceRange();
4389 }
4390 NestedLoopCount = Result.getLimitedValue();
4391 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004392 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004393 // This is helper routine for loop directives (e.g., 'for', 'simd',
4394 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004395 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004396 SmallVector<LoopIterationSpace, 4> IterSpaces;
4397 IterSpaces.resize(NestedLoopCount);
4398 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004399 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004400 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004401 NestedLoopCount, CollapseLoopCountExpr,
4402 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004403 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004404 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004405 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004406 // OpenMP [2.8.1, simd construct, Restrictions]
4407 // All loops associated with the construct must be perfectly nested; that
4408 // is, there must be no intervening code nor any OpenMP directive between
4409 // any two loops.
4410 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004411 }
4412
Alexander Musmana5f070a2014-10-01 06:03:56 +00004413 Built.clear(/* size */ NestedLoopCount);
4414
4415 if (SemaRef.CurContext->isDependentContext())
4416 return NestedLoopCount;
4417
4418 // An example of what is generated for the following code:
4419 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004420 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004421 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004422 // for (k = 0; k < NK; ++k)
4423 // for (j = J0; j < NJ; j+=2) {
4424 // <loop body>
4425 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004426 //
4427 // We generate the code below.
4428 // Note: the loop body may be outlined in CodeGen.
4429 // Note: some counters may be C++ classes, operator- is used to find number of
4430 // iterations and operator+= to calculate counter value.
4431 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4432 // or i64 is currently supported).
4433 //
4434 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4435 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4436 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4437 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4438 // // similar updates for vars in clauses (e.g. 'linear')
4439 // <loop body (using local i and j)>
4440 // }
4441 // i = NI; // assign final values of counters
4442 // j = NJ;
4443 //
4444
4445 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4446 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004447 // Precondition tests if there is at least one iteration (all conditions are
4448 // true).
4449 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004450 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004451 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004452 32 /* Bits */, SemaRef
4453 .PerformImplicitConversion(
4454 N0->IgnoreImpCasts(), N0->getType(),
4455 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004456 .get(),
4457 SemaRef);
4458 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004459 64 /* Bits */, SemaRef
4460 .PerformImplicitConversion(
4461 N0->IgnoreImpCasts(), N0->getType(),
4462 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004463 .get(),
4464 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004465
4466 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4467 return NestedLoopCount;
4468
4469 auto &C = SemaRef.Context;
4470 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4471
4472 Scope *CurScope = DSA.getCurScope();
4473 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004474 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004475 PreCond =
4476 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4477 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004478 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004479 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004480 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004481 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4482 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004483 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004484 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004485 SemaRef
4486 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4487 Sema::AA_Converting,
4488 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004489 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004490 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004491 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004492 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004493 SemaRef
4494 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4495 Sema::AA_Converting,
4496 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004497 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004498 }
4499
4500 // Choose either the 32-bit or 64-bit version.
4501 ExprResult LastIteration = LastIteration64;
4502 if (LastIteration32.isUsable() &&
4503 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4504 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4505 FitsInto(
4506 32 /* Bits */,
4507 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4508 LastIteration64.get(), SemaRef)))
4509 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004510 QualType VType = LastIteration.get()->getType();
4511 QualType RealVType = VType;
4512 QualType StrideVType = VType;
4513 if (isOpenMPTaskLoopDirective(DKind)) {
4514 VType =
4515 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4516 StrideVType =
4517 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4518 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004519
4520 if (!LastIteration.isUsable())
4521 return 0;
4522
4523 // Save the number of iterations.
4524 ExprResult NumIterations = LastIteration;
4525 {
4526 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004527 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4528 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004529 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4530 if (!LastIteration.isUsable())
4531 return 0;
4532 }
4533
4534 // Calculate the last iteration number beforehand instead of doing this on
4535 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4536 llvm::APSInt Result;
4537 bool IsConstant =
4538 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4539 ExprResult CalcLastIteration;
4540 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004541 ExprResult SaveRef =
4542 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004543 LastIteration = SaveRef;
4544
4545 // Prepare SaveRef + 1.
4546 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004547 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004548 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4549 if (!NumIterations.isUsable())
4550 return 0;
4551 }
4552
4553 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4554
David Majnemer9d168222016-08-05 17:44:54 +00004555 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004556 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004557 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4558 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004559 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004560 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4561 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004562 SemaRef.AddInitializerToDecl(LBDecl,
4563 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4564 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004565
4566 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004567 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4568 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004569 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004570 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004571
4572 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4573 // This will be used to implement clause 'lastprivate'.
4574 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004575 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4576 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004577 SemaRef.AddInitializerToDecl(ILDecl,
4578 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4579 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004580
4581 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004582 VarDecl *STDecl =
4583 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4584 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004585 SemaRef.AddInitializerToDecl(STDecl,
4586 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4587 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004588
4589 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004590 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004591 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4592 UB.get(), LastIteration.get());
4593 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4594 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4595 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4596 CondOp.get());
4597 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004598
4599 // If we have a combined directive that combines 'distribute', 'for' or
4600 // 'simd' we need to be able to access the bounds of the schedule of the
4601 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4602 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4603 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004604
Carlo Bertolliffafe102017-04-20 00:39:39 +00004605 // Lower bound variable, initialized with zero.
4606 VarDecl *CombLBDecl =
4607 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4608 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4609 SemaRef.AddInitializerToDecl(
4610 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4611 /*DirectInit*/ false);
4612
4613 // Upper bound variable, initialized with last iteration number.
4614 VarDecl *CombUBDecl =
4615 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4616 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4617 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4618 /*DirectInit*/ false);
4619
4620 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4621 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4622 ExprResult CombCondOp =
4623 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4624 LastIteration.get(), CombUB.get());
4625 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4626 CombCondOp.get());
4627 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4628
4629 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004630 // We expect to have at least 2 more parameters than the 'parallel'
4631 // directive does - the lower and upper bounds of the previous schedule.
4632 assert(CD->getNumParams() >= 4 &&
4633 "Unexpected number of parameters in loop combined directive");
4634
4635 // Set the proper type for the bounds given what we learned from the
4636 // enclosed loops.
4637 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4638 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4639
4640 // Previous lower and upper bounds are obtained from the region
4641 // parameters.
4642 PrevLB =
4643 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4644 PrevUB =
4645 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4646 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004647 }
4648
4649 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004650 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004651 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004652 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004653 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4654 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004655 Expr *RHS =
4656 (isOpenMPWorksharingDirective(DKind) ||
4657 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4658 ? LB.get()
4659 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004660 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4661 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004662
4663 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4664 Expr *CombRHS =
4665 (isOpenMPWorksharingDirective(DKind) ||
4666 isOpenMPTaskLoopDirective(DKind) ||
4667 isOpenMPDistributeDirective(DKind))
4668 ? CombLB.get()
4669 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4670 CombInit =
4671 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4672 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4673 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004674 }
4675
Alexander Musmanc6388682014-12-15 07:07:06 +00004676 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004677 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004678 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004679 (isOpenMPWorksharingDirective(DKind) ||
4680 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004681 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4682 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4683 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004684 ExprResult CombCond;
4685 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4686 CombCond =
4687 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4688 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004689 // Loop increment (IV = IV + 1)
4690 SourceLocation IncLoc;
4691 ExprResult Inc =
4692 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4693 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4694 if (!Inc.isUsable())
4695 return 0;
4696 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004697 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4698 if (!Inc.isUsable())
4699 return 0;
4700
4701 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4702 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004703 // In combined construct, add combined version that use CombLB and CombUB
4704 // base variables for the update
4705 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004706 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4707 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004708 // LB + ST
4709 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4710 if (!NextLB.isUsable())
4711 return 0;
4712 // LB = LB + ST
4713 NextLB =
4714 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4715 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4716 if (!NextLB.isUsable())
4717 return 0;
4718 // UB + ST
4719 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4720 if (!NextUB.isUsable())
4721 return 0;
4722 // UB = UB + ST
4723 NextUB =
4724 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4725 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4726 if (!NextUB.isUsable())
4727 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004728 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4729 CombNextLB =
4730 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4731 if (!NextLB.isUsable())
4732 return 0;
4733 // LB = LB + ST
4734 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4735 CombNextLB.get());
4736 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4737 if (!CombNextLB.isUsable())
4738 return 0;
4739 // UB + ST
4740 CombNextUB =
4741 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4742 if (!CombNextUB.isUsable())
4743 return 0;
4744 // UB = UB + ST
4745 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4746 CombNextUB.get());
4747 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4748 if (!CombNextUB.isUsable())
4749 return 0;
4750 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004751 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004752
Carlo Bertolliffafe102017-04-20 00:39:39 +00004753 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004754 // directive with for as IV = IV + ST; ensure upper bound expression based
4755 // on PrevUB instead of NumIterations - used to implement 'for' when found
4756 // in combination with 'distribute', like in 'distribute parallel for'
4757 SourceLocation DistIncLoc;
4758 ExprResult DistCond, DistInc, PrevEUB;
4759 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4760 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4761 assert(DistCond.isUsable() && "distribute cond expr was not built");
4762
4763 DistInc =
4764 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4765 assert(DistInc.isUsable() && "distribute inc expr was not built");
4766 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4767 DistInc.get());
4768 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4769 assert(DistInc.isUsable() && "distribute inc expr was not built");
4770
4771 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4772 // construct
4773 SourceLocation DistEUBLoc;
4774 ExprResult IsUBGreater =
4775 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4776 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4777 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4778 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4779 CondOp.get());
4780 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4781 }
4782
Alexander Musmana5f070a2014-10-01 06:03:56 +00004783 // Build updates and final values of the loop counters.
4784 bool HasErrors = false;
4785 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004786 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004787 Built.Updates.resize(NestedLoopCount);
4788 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004789 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004790 {
4791 ExprResult Div;
4792 // Go from inner nested loop to outer.
4793 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4794 LoopIterationSpace &IS = IterSpaces[Cnt];
4795 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4796 // Build: Iter = (IV / Div) % IS.NumIters
4797 // where Div is product of previous iterations' IS.NumIters.
4798 ExprResult Iter;
4799 if (Div.isUsable()) {
4800 Iter =
4801 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4802 } else {
4803 Iter = IV;
4804 assert((Cnt == (int)NestedLoopCount - 1) &&
4805 "unusable div expected on first iteration only");
4806 }
4807
4808 if (Cnt != 0 && Iter.isUsable())
4809 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4810 IS.NumIterations);
4811 if (!Iter.isUsable()) {
4812 HasErrors = true;
4813 break;
4814 }
4815
Alexey Bataev39f915b82015-05-08 10:41:21 +00004816 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004817 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4818 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4819 IS.CounterVar->getExprLoc(),
4820 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004821 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004822 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004823 if (!Init.isUsable()) {
4824 HasErrors = true;
4825 break;
4826 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004827 ExprResult Update = BuildCounterUpdate(
4828 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4829 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004830 if (!Update.isUsable()) {
4831 HasErrors = true;
4832 break;
4833 }
4834
4835 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4836 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004837 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004838 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004839 if (!Final.isUsable()) {
4840 HasErrors = true;
4841 break;
4842 }
4843
4844 // Build Div for the next iteration: Div <- Div * IS.NumIters
4845 if (Cnt != 0) {
4846 if (Div.isUnset())
4847 Div = IS.NumIterations;
4848 else
4849 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4850 IS.NumIterations);
4851
4852 // Add parentheses (for debugging purposes only).
4853 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004854 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004855 if (!Div.isUsable()) {
4856 HasErrors = true;
4857 break;
4858 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004859 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004860 }
4861 if (!Update.isUsable() || !Final.isUsable()) {
4862 HasErrors = true;
4863 break;
4864 }
4865 // Save results
4866 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004867 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004868 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004869 Built.Updates[Cnt] = Update.get();
4870 Built.Finals[Cnt] = Final.get();
4871 }
4872 }
4873
4874 if (HasErrors)
4875 return 0;
4876
4877 // Save results
4878 Built.IterationVarRef = IV.get();
4879 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004880 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004881 Built.CalcLastIteration =
4882 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004883 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004884 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004885 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004886 Built.Init = Init.get();
4887 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004888 Built.LB = LB.get();
4889 Built.UB = UB.get();
4890 Built.IL = IL.get();
4891 Built.ST = ST.get();
4892 Built.EUB = EUB.get();
4893 Built.NLB = NextLB.get();
4894 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004895 Built.PrevLB = PrevLB.get();
4896 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004897 Built.DistInc = DistInc.get();
4898 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004899 Built.DistCombinedFields.LB = CombLB.get();
4900 Built.DistCombinedFields.UB = CombUB.get();
4901 Built.DistCombinedFields.EUB = CombEUB.get();
4902 Built.DistCombinedFields.Init = CombInit.get();
4903 Built.DistCombinedFields.Cond = CombCond.get();
4904 Built.DistCombinedFields.NLB = CombNextLB.get();
4905 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004906
Alexey Bataev8b427062016-05-25 12:36:08 +00004907 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4908 // Fill data for doacross depend clauses.
4909 for (auto Pair : DSA.getDoacrossDependClauses()) {
4910 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4911 Pair.first->setCounterValue(CounterVal);
4912 else {
4913 if (NestedLoopCount != Pair.second.size() ||
4914 NestedLoopCount != LoopMultipliers.size() + 1) {
4915 // Erroneous case - clause has some problems.
4916 Pair.first->setCounterValue(CounterVal);
4917 continue;
4918 }
4919 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4920 auto I = Pair.second.rbegin();
4921 auto IS = IterSpaces.rbegin();
4922 auto ILM = LoopMultipliers.rbegin();
4923 Expr *UpCounterVal = CounterVal;
4924 Expr *Multiplier = nullptr;
4925 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4926 if (I->first) {
4927 assert(IS->CounterStep);
4928 Expr *NormalizedOffset =
4929 SemaRef
4930 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4931 I->first, IS->CounterStep)
4932 .get();
4933 if (Multiplier) {
4934 NormalizedOffset =
4935 SemaRef
4936 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4937 NormalizedOffset, Multiplier)
4938 .get();
4939 }
4940 assert(I->second == OO_Plus || I->second == OO_Minus);
4941 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004942 UpCounterVal = SemaRef
4943 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4944 UpCounterVal, NormalizedOffset)
4945 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004946 }
4947 Multiplier = *ILM;
4948 ++I;
4949 ++IS;
4950 ++ILM;
4951 }
4952 Pair.first->setCounterValue(UpCounterVal);
4953 }
4954 }
4955
Alexey Bataevabfc0692014-06-25 06:52:00 +00004956 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004957}
4958
Alexey Bataev10e775f2015-07-30 11:36:16 +00004959static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004960 auto CollapseClauses =
4961 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4962 if (CollapseClauses.begin() != CollapseClauses.end())
4963 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004964 return nullptr;
4965}
4966
Alexey Bataev10e775f2015-07-30 11:36:16 +00004967static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004968 auto OrderedClauses =
4969 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4970 if (OrderedClauses.begin() != OrderedClauses.end())
4971 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004972 return nullptr;
4973}
4974
Kelvin Lic5609492016-07-15 04:39:07 +00004975static bool checkSimdlenSafelenSpecified(Sema &S,
4976 const ArrayRef<OMPClause *> Clauses) {
4977 OMPSafelenClause *Safelen = nullptr;
4978 OMPSimdlenClause *Simdlen = nullptr;
4979
4980 for (auto *Clause : Clauses) {
4981 if (Clause->getClauseKind() == OMPC_safelen)
4982 Safelen = cast<OMPSafelenClause>(Clause);
4983 else if (Clause->getClauseKind() == OMPC_simdlen)
4984 Simdlen = cast<OMPSimdlenClause>(Clause);
4985 if (Safelen && Simdlen)
4986 break;
4987 }
4988
4989 if (Simdlen && Safelen) {
4990 llvm::APSInt SimdlenRes, SafelenRes;
4991 auto SimdlenLength = Simdlen->getSimdlen();
4992 auto SafelenLength = Safelen->getSafelen();
4993 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4994 SimdlenLength->isInstantiationDependent() ||
4995 SimdlenLength->containsUnexpandedParameterPack())
4996 return false;
4997 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4998 SafelenLength->isInstantiationDependent() ||
4999 SafelenLength->containsUnexpandedParameterPack())
5000 return false;
5001 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5002 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5003 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5004 // If both simdlen and safelen clauses are specified, the value of the
5005 // simdlen parameter must be less than or equal to the value of the safelen
5006 // parameter.
5007 if (SimdlenRes > SafelenRes) {
5008 S.Diag(SimdlenLength->getExprLoc(),
5009 diag::err_omp_wrong_simdlen_safelen_values)
5010 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5011 return true;
5012 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005013 }
5014 return false;
5015}
5016
Alexey Bataev4acb8592014-07-07 13:01:15 +00005017StmtResult Sema::ActOnOpenMPSimdDirective(
5018 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5019 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005020 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005021 if (!AStmt)
5022 return StmtError();
5023
5024 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005025 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005026 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5027 // define the nested loops number.
5028 unsigned NestedLoopCount = CheckOpenMPLoop(
5029 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5030 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005031 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005032 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005033
Alexander Musmana5f070a2014-10-01 06:03:56 +00005034 assert((CurContext->isDependentContext() || B.builtAll()) &&
5035 "omp simd loop exprs were not built");
5036
Alexander Musman3276a272015-03-21 10:12:56 +00005037 if (!CurContext->isDependentContext()) {
5038 // Finalize the clauses that need pre-built expressions for CodeGen.
5039 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005040 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005041 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005042 B.NumIterations, *this, CurScope,
5043 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005044 return StmtError();
5045 }
5046 }
5047
Kelvin Lic5609492016-07-15 04:39:07 +00005048 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005049 return StmtError();
5050
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005051 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005052 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5053 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005054}
5055
Alexey Bataev4acb8592014-07-07 13:01:15 +00005056StmtResult Sema::ActOnOpenMPForDirective(
5057 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5058 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005059 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005060 if (!AStmt)
5061 return StmtError();
5062
5063 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005064 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005065 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5066 // define the nested loops number.
5067 unsigned NestedLoopCount = CheckOpenMPLoop(
5068 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5069 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005070 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005071 return StmtError();
5072
Alexander Musmana5f070a2014-10-01 06:03:56 +00005073 assert((CurContext->isDependentContext() || B.builtAll()) &&
5074 "omp for loop exprs were not built");
5075
Alexey Bataev54acd402015-08-04 11:18:19 +00005076 if (!CurContext->isDependentContext()) {
5077 // Finalize the clauses that need pre-built expressions for CodeGen.
5078 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005079 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005080 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005081 B.NumIterations, *this, CurScope,
5082 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005083 return StmtError();
5084 }
5085 }
5086
Alexey Bataevf29276e2014-06-18 04:14:57 +00005087 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005088 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005089 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005090}
5091
Alexander Musmanf82886e2014-09-18 05:12:34 +00005092StmtResult Sema::ActOnOpenMPForSimdDirective(
5093 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5094 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005095 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005096 if (!AStmt)
5097 return StmtError();
5098
5099 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005100 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005101 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5102 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005103 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005104 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5105 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5106 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005107 if (NestedLoopCount == 0)
5108 return StmtError();
5109
Alexander Musmanc6388682014-12-15 07:07:06 +00005110 assert((CurContext->isDependentContext() || B.builtAll()) &&
5111 "omp for simd loop exprs were not built");
5112
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005113 if (!CurContext->isDependentContext()) {
5114 // Finalize the clauses that need pre-built expressions for CodeGen.
5115 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005116 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005117 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005118 B.NumIterations, *this, CurScope,
5119 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005120 return StmtError();
5121 }
5122 }
5123
Kelvin Lic5609492016-07-15 04:39:07 +00005124 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005125 return StmtError();
5126
Alexander Musmanf82886e2014-09-18 05:12:34 +00005127 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005128 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5129 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005130}
5131
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005132StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5133 Stmt *AStmt,
5134 SourceLocation StartLoc,
5135 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005136 if (!AStmt)
5137 return StmtError();
5138
5139 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005140 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005141 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005142 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005143 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005144 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005145 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005146 return StmtError();
5147 // All associated statements must be '#pragma omp section' except for
5148 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005149 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005150 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5151 if (SectionStmt)
5152 Diag(SectionStmt->getLocStart(),
5153 diag::err_omp_sections_substmt_not_section);
5154 return StmtError();
5155 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005156 cast<OMPSectionDirective>(SectionStmt)
5157 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005158 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005159 } else {
5160 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5161 return StmtError();
5162 }
5163
5164 getCurFunction()->setHasBranchProtectedScope();
5165
Alexey Bataev25e5b442015-09-15 12:52:43 +00005166 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5167 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005168}
5169
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005170StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5171 SourceLocation StartLoc,
5172 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005173 if (!AStmt)
5174 return StmtError();
5175
5176 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005177
5178 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005179 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005180
Alexey Bataev25e5b442015-09-15 12:52:43 +00005181 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5182 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005183}
5184
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005185StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5186 Stmt *AStmt,
5187 SourceLocation StartLoc,
5188 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005189 if (!AStmt)
5190 return StmtError();
5191
5192 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005193
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005194 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005195
Alexey Bataev3255bf32015-01-19 05:20:46 +00005196 // OpenMP [2.7.3, single Construct, Restrictions]
5197 // The copyprivate clause must not be used with the nowait clause.
5198 OMPClause *Nowait = nullptr;
5199 OMPClause *Copyprivate = nullptr;
5200 for (auto *Clause : Clauses) {
5201 if (Clause->getClauseKind() == OMPC_nowait)
5202 Nowait = Clause;
5203 else if (Clause->getClauseKind() == OMPC_copyprivate)
5204 Copyprivate = Clause;
5205 if (Copyprivate && Nowait) {
5206 Diag(Copyprivate->getLocStart(),
5207 diag::err_omp_single_copyprivate_with_nowait);
5208 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5209 return StmtError();
5210 }
5211 }
5212
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005213 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5214}
5215
Alexander Musman80c22892014-07-17 08:54:58 +00005216StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5217 SourceLocation StartLoc,
5218 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005219 if (!AStmt)
5220 return StmtError();
5221
5222 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005223
5224 getCurFunction()->setHasBranchProtectedScope();
5225
5226 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5227}
5228
Alexey Bataev28c75412015-12-15 08:19:24 +00005229StmtResult Sema::ActOnOpenMPCriticalDirective(
5230 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5231 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005232 if (!AStmt)
5233 return StmtError();
5234
5235 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005236
Alexey Bataev28c75412015-12-15 08:19:24 +00005237 bool ErrorFound = false;
5238 llvm::APSInt Hint;
5239 SourceLocation HintLoc;
5240 bool DependentHint = false;
5241 for (auto *C : Clauses) {
5242 if (C->getClauseKind() == OMPC_hint) {
5243 if (!DirName.getName()) {
5244 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5245 ErrorFound = true;
5246 }
5247 Expr *E = cast<OMPHintClause>(C)->getHint();
5248 if (E->isTypeDependent() || E->isValueDependent() ||
5249 E->isInstantiationDependent())
5250 DependentHint = true;
5251 else {
5252 Hint = E->EvaluateKnownConstInt(Context);
5253 HintLoc = C->getLocStart();
5254 }
5255 }
5256 }
5257 if (ErrorFound)
5258 return StmtError();
5259 auto Pair = DSAStack->getCriticalWithHint(DirName);
5260 if (Pair.first && DirName.getName() && !DependentHint) {
5261 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5262 Diag(StartLoc, diag::err_omp_critical_with_hint);
5263 if (HintLoc.isValid()) {
5264 Diag(HintLoc, diag::note_omp_critical_hint_here)
5265 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5266 } else
5267 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5268 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5269 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5270 << 1
5271 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5272 /*Radix=*/10, /*Signed=*/false);
5273 } else
5274 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5275 }
5276 }
5277
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005278 getCurFunction()->setHasBranchProtectedScope();
5279
Alexey Bataev28c75412015-12-15 08:19:24 +00005280 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5281 Clauses, AStmt);
5282 if (!Pair.first && DirName.getName() && !DependentHint)
5283 DSAStack->addCriticalWithHint(Dir, Hint);
5284 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005285}
5286
Alexey Bataev4acb8592014-07-07 13:01:15 +00005287StmtResult Sema::ActOnOpenMPParallelForDirective(
5288 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5289 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005290 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005291 if (!AStmt)
5292 return StmtError();
5293
Alexey Bataev4acb8592014-07-07 13:01:15 +00005294 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5295 // 1.2.2 OpenMP Language Terminology
5296 // Structured block - An executable statement with a single entry at the
5297 // top and a single exit at the bottom.
5298 // The point of exit cannot be a branch out of the structured block.
5299 // longjmp() and throw() must not violate the entry/exit criteria.
5300 CS->getCapturedDecl()->setNothrow();
5301
Alexander Musmanc6388682014-12-15 07:07:06 +00005302 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005303 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5304 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005305 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005306 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5307 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5308 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005309 if (NestedLoopCount == 0)
5310 return StmtError();
5311
Alexander Musmana5f070a2014-10-01 06:03:56 +00005312 assert((CurContext->isDependentContext() || B.builtAll()) &&
5313 "omp parallel for loop exprs were not built");
5314
Alexey Bataev54acd402015-08-04 11:18:19 +00005315 if (!CurContext->isDependentContext()) {
5316 // Finalize the clauses that need pre-built expressions for CodeGen.
5317 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005318 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005319 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005320 B.NumIterations, *this, CurScope,
5321 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005322 return StmtError();
5323 }
5324 }
5325
Alexey Bataev4acb8592014-07-07 13:01:15 +00005326 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005327 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005328 NestedLoopCount, Clauses, AStmt, B,
5329 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005330}
5331
Alexander Musmane4e893b2014-09-23 09:33:00 +00005332StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5333 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5334 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005335 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005336 if (!AStmt)
5337 return StmtError();
5338
Alexander Musmane4e893b2014-09-23 09:33:00 +00005339 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5340 // 1.2.2 OpenMP Language Terminology
5341 // Structured block - An executable statement with a single entry at the
5342 // top and a single exit at the bottom.
5343 // The point of exit cannot be a branch out of the structured block.
5344 // longjmp() and throw() must not violate the entry/exit criteria.
5345 CS->getCapturedDecl()->setNothrow();
5346
Alexander Musmanc6388682014-12-15 07:07:06 +00005347 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005348 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5349 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005350 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005351 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5352 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5353 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005354 if (NestedLoopCount == 0)
5355 return StmtError();
5356
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005357 if (!CurContext->isDependentContext()) {
5358 // Finalize the clauses that need pre-built expressions for CodeGen.
5359 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005360 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005361 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005362 B.NumIterations, *this, CurScope,
5363 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005364 return StmtError();
5365 }
5366 }
5367
Kelvin Lic5609492016-07-15 04:39:07 +00005368 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005369 return StmtError();
5370
Alexander Musmane4e893b2014-09-23 09:33:00 +00005371 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005372 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005373 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005374}
5375
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005376StmtResult
5377Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5378 Stmt *AStmt, SourceLocation StartLoc,
5379 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005380 if (!AStmt)
5381 return StmtError();
5382
5383 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005384 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005385 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005386 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005387 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005388 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005389 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005390 return StmtError();
5391 // All associated statements must be '#pragma omp section' except for
5392 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005393 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005394 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5395 if (SectionStmt)
5396 Diag(SectionStmt->getLocStart(),
5397 diag::err_omp_parallel_sections_substmt_not_section);
5398 return StmtError();
5399 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005400 cast<OMPSectionDirective>(SectionStmt)
5401 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005402 }
5403 } else {
5404 Diag(AStmt->getLocStart(),
5405 diag::err_omp_parallel_sections_not_compound_stmt);
5406 return StmtError();
5407 }
5408
5409 getCurFunction()->setHasBranchProtectedScope();
5410
Alexey Bataev25e5b442015-09-15 12:52:43 +00005411 return OMPParallelSectionsDirective::Create(
5412 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005413}
5414
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005415StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5416 Stmt *AStmt, SourceLocation StartLoc,
5417 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005418 if (!AStmt)
5419 return StmtError();
5420
David Majnemer9d168222016-08-05 17:44:54 +00005421 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005422 // 1.2.2 OpenMP Language Terminology
5423 // Structured block - An executable statement with a single entry at the
5424 // top and a single exit at the bottom.
5425 // The point of exit cannot be a branch out of the structured block.
5426 // longjmp() and throw() must not violate the entry/exit criteria.
5427 CS->getCapturedDecl()->setNothrow();
5428
5429 getCurFunction()->setHasBranchProtectedScope();
5430
Alexey Bataev25e5b442015-09-15 12:52:43 +00005431 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5432 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005433}
5434
Alexey Bataev68446b72014-07-18 07:47:19 +00005435StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5436 SourceLocation EndLoc) {
5437 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5438}
5439
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005440StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5441 SourceLocation EndLoc) {
5442 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5443}
5444
Alexey Bataev2df347a2014-07-18 10:17:07 +00005445StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5446 SourceLocation EndLoc) {
5447 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5448}
5449
Alexey Bataev169d96a2017-07-18 20:17:46 +00005450StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5451 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005452 SourceLocation StartLoc,
5453 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005454 if (!AStmt)
5455 return StmtError();
5456
5457 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005458
5459 getCurFunction()->setHasBranchProtectedScope();
5460
Alexey Bataev169d96a2017-07-18 20:17:46 +00005461 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005462 AStmt,
5463 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005464}
5465
Alexey Bataev6125da92014-07-21 11:26:11 +00005466StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5467 SourceLocation StartLoc,
5468 SourceLocation EndLoc) {
5469 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5470 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5471}
5472
Alexey Bataev346265e2015-09-25 10:37:12 +00005473StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5474 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005475 SourceLocation StartLoc,
5476 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005477 OMPClause *DependFound = nullptr;
5478 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005479 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005480 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005481 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005482 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005483 for (auto *C : Clauses) {
5484 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5485 DependFound = C;
5486 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5487 if (DependSourceClause) {
5488 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5489 << getOpenMPDirectiveName(OMPD_ordered)
5490 << getOpenMPClauseName(OMPC_depend) << 2;
5491 ErrorFound = true;
5492 } else
5493 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005494 if (DependSinkClause) {
5495 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5496 << 0;
5497 ErrorFound = true;
5498 }
5499 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5500 if (DependSourceClause) {
5501 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5502 << 1;
5503 ErrorFound = true;
5504 }
5505 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005506 }
5507 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005508 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005509 else if (C->getClauseKind() == OMPC_simd)
5510 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005511 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005512 if (!ErrorFound && !SC &&
5513 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005514 // OpenMP [2.8.1,simd Construct, Restrictions]
5515 // An ordered construct with the simd clause is the only OpenMP construct
5516 // that can appear in the simd region.
5517 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005518 ErrorFound = true;
5519 } else if (DependFound && (TC || SC)) {
5520 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5521 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5522 ErrorFound = true;
5523 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5524 Diag(DependFound->getLocStart(),
5525 diag::err_omp_ordered_directive_without_param);
5526 ErrorFound = true;
5527 } else if (TC || Clauses.empty()) {
5528 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5529 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5530 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5531 << (TC != nullptr);
5532 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5533 ErrorFound = true;
5534 }
5535 }
5536 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005537 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005538
5539 if (AStmt) {
5540 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5541
5542 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005543 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005544
5545 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005546}
5547
Alexey Bataev1d160b12015-03-13 12:27:31 +00005548namespace {
5549/// \brief Helper class for checking expression in 'omp atomic [update]'
5550/// construct.
5551class OpenMPAtomicUpdateChecker {
5552 /// \brief Error results for atomic update expressions.
5553 enum ExprAnalysisErrorCode {
5554 /// \brief A statement is not an expression statement.
5555 NotAnExpression,
5556 /// \brief Expression is not builtin binary or unary operation.
5557 NotABinaryOrUnaryExpression,
5558 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5559 NotAnUnaryIncDecExpression,
5560 /// \brief An expression is not of scalar type.
5561 NotAScalarType,
5562 /// \brief A binary operation is not an assignment operation.
5563 NotAnAssignmentOp,
5564 /// \brief RHS part of the binary operation is not a binary expression.
5565 NotABinaryExpression,
5566 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5567 /// expression.
5568 NotABinaryOperator,
5569 /// \brief RHS binary operation does not have reference to the updated LHS
5570 /// part.
5571 NotAnUpdateExpression,
5572 /// \brief No errors is found.
5573 NoError
5574 };
5575 /// \brief Reference to Sema.
5576 Sema &SemaRef;
5577 /// \brief A location for note diagnostics (when error is found).
5578 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005579 /// \brief 'x' lvalue part of the source atomic expression.
5580 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005581 /// \brief 'expr' rvalue part of the source atomic expression.
5582 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005583 /// \brief Helper expression of the form
5584 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5585 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5586 Expr *UpdateExpr;
5587 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5588 /// important for non-associative operations.
5589 bool IsXLHSInRHSPart;
5590 BinaryOperatorKind Op;
5591 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005592 /// \brief true if the source expression is a postfix unary operation, false
5593 /// if it is a prefix unary operation.
5594 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005595
5596public:
5597 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005598 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005599 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005600 /// \brief Check specified statement that it is suitable for 'atomic update'
5601 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005602 /// expression. If DiagId and NoteId == 0, then only check is performed
5603 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005604 /// \param DiagId Diagnostic which should be emitted if error is found.
5605 /// \param NoteId Diagnostic note for the main error message.
5606 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005607 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005608 /// \brief Return the 'x' lvalue part of the source atomic expression.
5609 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005610 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5611 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005612 /// \brief Return the update expression used in calculation of the updated
5613 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5614 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5615 Expr *getUpdateExpr() const { return UpdateExpr; }
5616 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5617 /// false otherwise.
5618 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5619
Alexey Bataevb78ca832015-04-01 03:33:17 +00005620 /// \brief true if the source expression is a postfix unary operation, false
5621 /// if it is a prefix unary operation.
5622 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5623
Alexey Bataev1d160b12015-03-13 12:27:31 +00005624private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005625 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5626 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005627};
5628} // namespace
5629
5630bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5631 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5632 ExprAnalysisErrorCode ErrorFound = NoError;
5633 SourceLocation ErrorLoc, NoteLoc;
5634 SourceRange ErrorRange, NoteRange;
5635 // Allowed constructs are:
5636 // x = x binop expr;
5637 // x = expr binop x;
5638 if (AtomicBinOp->getOpcode() == BO_Assign) {
5639 X = AtomicBinOp->getLHS();
5640 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5641 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5642 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5643 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5644 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005645 Op = AtomicInnerBinOp->getOpcode();
5646 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005647 auto *LHS = AtomicInnerBinOp->getLHS();
5648 auto *RHS = AtomicInnerBinOp->getRHS();
5649 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5650 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5651 /*Canonical=*/true);
5652 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5653 /*Canonical=*/true);
5654 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5655 /*Canonical=*/true);
5656 if (XId == LHSId) {
5657 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005658 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005659 } else if (XId == RHSId) {
5660 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005661 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005662 } else {
5663 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5664 ErrorRange = AtomicInnerBinOp->getSourceRange();
5665 NoteLoc = X->getExprLoc();
5666 NoteRange = X->getSourceRange();
5667 ErrorFound = NotAnUpdateExpression;
5668 }
5669 } else {
5670 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5671 ErrorRange = AtomicInnerBinOp->getSourceRange();
5672 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5673 NoteRange = SourceRange(NoteLoc, NoteLoc);
5674 ErrorFound = NotABinaryOperator;
5675 }
5676 } else {
5677 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5678 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5679 ErrorFound = NotABinaryExpression;
5680 }
5681 } else {
5682 ErrorLoc = AtomicBinOp->getExprLoc();
5683 ErrorRange = AtomicBinOp->getSourceRange();
5684 NoteLoc = AtomicBinOp->getOperatorLoc();
5685 NoteRange = SourceRange(NoteLoc, NoteLoc);
5686 ErrorFound = NotAnAssignmentOp;
5687 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005688 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005689 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5690 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5691 return true;
5692 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005693 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005694 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005695}
5696
5697bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5698 unsigned NoteId) {
5699 ExprAnalysisErrorCode ErrorFound = NoError;
5700 SourceLocation ErrorLoc, NoteLoc;
5701 SourceRange ErrorRange, NoteRange;
5702 // Allowed constructs are:
5703 // x++;
5704 // x--;
5705 // ++x;
5706 // --x;
5707 // x binop= expr;
5708 // x = x binop expr;
5709 // x = expr binop x;
5710 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5711 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5712 if (AtomicBody->getType()->isScalarType() ||
5713 AtomicBody->isInstantiationDependent()) {
5714 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5715 AtomicBody->IgnoreParenImpCasts())) {
5716 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005717 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005718 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005719 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005720 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005721 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005722 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005723 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5724 AtomicBody->IgnoreParenImpCasts())) {
5725 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005726 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005727 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005728 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5729 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005730 // Check for Unary Operation
5731 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005732 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005733 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5734 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005735 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005736 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5737 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005738 } else {
5739 ErrorFound = NotAnUnaryIncDecExpression;
5740 ErrorLoc = AtomicUnaryOp->getExprLoc();
5741 ErrorRange = AtomicUnaryOp->getSourceRange();
5742 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5743 NoteRange = SourceRange(NoteLoc, NoteLoc);
5744 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005745 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005746 ErrorFound = NotABinaryOrUnaryExpression;
5747 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5748 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5749 }
5750 } else {
5751 ErrorFound = NotAScalarType;
5752 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5753 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5754 }
5755 } else {
5756 ErrorFound = NotAnExpression;
5757 NoteLoc = ErrorLoc = S->getLocStart();
5758 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5759 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005760 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005761 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5762 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5763 return true;
5764 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005765 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005766 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005767 // Build an update expression of form 'OpaqueValueExpr(x) binop
5768 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5769 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5770 auto *OVEX = new (SemaRef.getASTContext())
5771 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5772 auto *OVEExpr = new (SemaRef.getASTContext())
5773 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5774 auto Update =
5775 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5776 IsXLHSInRHSPart ? OVEExpr : OVEX);
5777 if (Update.isInvalid())
5778 return true;
5779 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5780 Sema::AA_Casting);
5781 if (Update.isInvalid())
5782 return true;
5783 UpdateExpr = Update.get();
5784 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005785 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005786}
5787
Alexey Bataev0162e452014-07-22 10:10:35 +00005788StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5789 Stmt *AStmt,
5790 SourceLocation StartLoc,
5791 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005792 if (!AStmt)
5793 return StmtError();
5794
David Majnemer9d168222016-08-05 17:44:54 +00005795 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005796 // 1.2.2 OpenMP Language Terminology
5797 // Structured block - An executable statement with a single entry at the
5798 // top and a single exit at the bottom.
5799 // The point of exit cannot be a branch out of the structured block.
5800 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005801 OpenMPClauseKind AtomicKind = OMPC_unknown;
5802 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005803 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005804 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005805 C->getClauseKind() == OMPC_update ||
5806 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005807 if (AtomicKind != OMPC_unknown) {
5808 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5809 << SourceRange(C->getLocStart(), C->getLocEnd());
5810 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5811 << getOpenMPClauseName(AtomicKind);
5812 } else {
5813 AtomicKind = C->getClauseKind();
5814 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005815 }
5816 }
5817 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005818
Alexey Bataev459dec02014-07-24 06:46:57 +00005819 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005820 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5821 Body = EWC->getSubExpr();
5822
Alexey Bataev62cec442014-11-18 10:14:22 +00005823 Expr *X = nullptr;
5824 Expr *V = nullptr;
5825 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005826 Expr *UE = nullptr;
5827 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005828 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005829 // OpenMP [2.12.6, atomic Construct]
5830 // In the next expressions:
5831 // * x and v (as applicable) are both l-value expressions with scalar type.
5832 // * During the execution of an atomic region, multiple syntactic
5833 // occurrences of x must designate the same storage location.
5834 // * Neither of v and expr (as applicable) may access the storage location
5835 // designated by x.
5836 // * Neither of x and expr (as applicable) may access the storage location
5837 // designated by v.
5838 // * expr is an expression with scalar type.
5839 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5840 // * binop, binop=, ++, and -- are not overloaded operators.
5841 // * The expression x binop expr must be numerically equivalent to x binop
5842 // (expr). This requirement is satisfied if the operators in expr have
5843 // precedence greater than binop, or by using parentheses around expr or
5844 // subexpressions of expr.
5845 // * The expression expr binop x must be numerically equivalent to (expr)
5846 // binop x. This requirement is satisfied if the operators in expr have
5847 // precedence equal to or greater than binop, or by using parentheses around
5848 // expr or subexpressions of expr.
5849 // * For forms that allow multiple occurrences of x, the number of times
5850 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005851 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005852 enum {
5853 NotAnExpression,
5854 NotAnAssignmentOp,
5855 NotAScalarType,
5856 NotAnLValue,
5857 NoError
5858 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005859 SourceLocation ErrorLoc, NoteLoc;
5860 SourceRange ErrorRange, NoteRange;
5861 // If clause is read:
5862 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005863 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5864 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005865 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5866 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5867 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5868 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5869 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5870 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5871 if (!X->isLValue() || !V->isLValue()) {
5872 auto NotLValueExpr = X->isLValue() ? V : X;
5873 ErrorFound = NotAnLValue;
5874 ErrorLoc = AtomicBinOp->getExprLoc();
5875 ErrorRange = AtomicBinOp->getSourceRange();
5876 NoteLoc = NotLValueExpr->getExprLoc();
5877 NoteRange = NotLValueExpr->getSourceRange();
5878 }
5879 } else if (!X->isInstantiationDependent() ||
5880 !V->isInstantiationDependent()) {
5881 auto NotScalarExpr =
5882 (X->isInstantiationDependent() || X->getType()->isScalarType())
5883 ? V
5884 : X;
5885 ErrorFound = NotAScalarType;
5886 ErrorLoc = AtomicBinOp->getExprLoc();
5887 ErrorRange = AtomicBinOp->getSourceRange();
5888 NoteLoc = NotScalarExpr->getExprLoc();
5889 NoteRange = NotScalarExpr->getSourceRange();
5890 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005891 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005892 ErrorFound = NotAnAssignmentOp;
5893 ErrorLoc = AtomicBody->getExprLoc();
5894 ErrorRange = AtomicBody->getSourceRange();
5895 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5896 : AtomicBody->getExprLoc();
5897 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5898 : AtomicBody->getSourceRange();
5899 }
5900 } else {
5901 ErrorFound = NotAnExpression;
5902 NoteLoc = ErrorLoc = Body->getLocStart();
5903 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005904 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005905 if (ErrorFound != NoError) {
5906 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5907 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005908 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5909 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005910 return StmtError();
5911 } else if (CurContext->isDependentContext())
5912 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005913 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005914 enum {
5915 NotAnExpression,
5916 NotAnAssignmentOp,
5917 NotAScalarType,
5918 NotAnLValue,
5919 NoError
5920 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005921 SourceLocation ErrorLoc, NoteLoc;
5922 SourceRange ErrorRange, NoteRange;
5923 // If clause is write:
5924 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005925 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5926 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005927 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5928 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005929 X = AtomicBinOp->getLHS();
5930 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005931 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5932 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5933 if (!X->isLValue()) {
5934 ErrorFound = NotAnLValue;
5935 ErrorLoc = AtomicBinOp->getExprLoc();
5936 ErrorRange = AtomicBinOp->getSourceRange();
5937 NoteLoc = X->getExprLoc();
5938 NoteRange = X->getSourceRange();
5939 }
5940 } else if (!X->isInstantiationDependent() ||
5941 !E->isInstantiationDependent()) {
5942 auto NotScalarExpr =
5943 (X->isInstantiationDependent() || X->getType()->isScalarType())
5944 ? E
5945 : X;
5946 ErrorFound = NotAScalarType;
5947 ErrorLoc = AtomicBinOp->getExprLoc();
5948 ErrorRange = AtomicBinOp->getSourceRange();
5949 NoteLoc = NotScalarExpr->getExprLoc();
5950 NoteRange = NotScalarExpr->getSourceRange();
5951 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005952 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005953 ErrorFound = NotAnAssignmentOp;
5954 ErrorLoc = AtomicBody->getExprLoc();
5955 ErrorRange = AtomicBody->getSourceRange();
5956 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5957 : AtomicBody->getExprLoc();
5958 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5959 : AtomicBody->getSourceRange();
5960 }
5961 } else {
5962 ErrorFound = NotAnExpression;
5963 NoteLoc = ErrorLoc = Body->getLocStart();
5964 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005965 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005966 if (ErrorFound != NoError) {
5967 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5968 << ErrorRange;
5969 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5970 << NoteRange;
5971 return StmtError();
5972 } else if (CurContext->isDependentContext())
5973 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005974 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005975 // If clause is update:
5976 // x++;
5977 // x--;
5978 // ++x;
5979 // --x;
5980 // x binop= expr;
5981 // x = x binop expr;
5982 // x = expr binop x;
5983 OpenMPAtomicUpdateChecker Checker(*this);
5984 if (Checker.checkStatement(
5985 Body, (AtomicKind == OMPC_update)
5986 ? diag::err_omp_atomic_update_not_expression_statement
5987 : diag::err_omp_atomic_not_expression_statement,
5988 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005989 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005990 if (!CurContext->isDependentContext()) {
5991 E = Checker.getExpr();
5992 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005993 UE = Checker.getUpdateExpr();
5994 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005995 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005996 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005997 enum {
5998 NotAnAssignmentOp,
5999 NotACompoundStatement,
6000 NotTwoSubstatements,
6001 NotASpecificExpression,
6002 NoError
6003 } ErrorFound = NoError;
6004 SourceLocation ErrorLoc, NoteLoc;
6005 SourceRange ErrorRange, NoteRange;
6006 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6007 // If clause is a capture:
6008 // v = x++;
6009 // v = x--;
6010 // v = ++x;
6011 // v = --x;
6012 // v = x binop= expr;
6013 // v = x = x binop expr;
6014 // v = x = expr binop x;
6015 auto *AtomicBinOp =
6016 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6017 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6018 V = AtomicBinOp->getLHS();
6019 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6020 OpenMPAtomicUpdateChecker Checker(*this);
6021 if (Checker.checkStatement(
6022 Body, diag::err_omp_atomic_capture_not_expression_statement,
6023 diag::note_omp_atomic_update))
6024 return StmtError();
6025 E = Checker.getExpr();
6026 X = Checker.getX();
6027 UE = Checker.getUpdateExpr();
6028 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6029 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006030 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006031 ErrorLoc = AtomicBody->getExprLoc();
6032 ErrorRange = AtomicBody->getSourceRange();
6033 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6034 : AtomicBody->getExprLoc();
6035 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6036 : AtomicBody->getSourceRange();
6037 ErrorFound = NotAnAssignmentOp;
6038 }
6039 if (ErrorFound != NoError) {
6040 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6041 << ErrorRange;
6042 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6043 return StmtError();
6044 } else if (CurContext->isDependentContext()) {
6045 UE = V = E = X = nullptr;
6046 }
6047 } else {
6048 // If clause is a capture:
6049 // { v = x; x = expr; }
6050 // { v = x; x++; }
6051 // { v = x; x--; }
6052 // { v = x; ++x; }
6053 // { v = x; --x; }
6054 // { v = x; x binop= expr; }
6055 // { v = x; x = x binop expr; }
6056 // { v = x; x = expr binop x; }
6057 // { x++; v = x; }
6058 // { x--; v = x; }
6059 // { ++x; v = x; }
6060 // { --x; v = x; }
6061 // { x binop= expr; v = x; }
6062 // { x = x binop expr; v = x; }
6063 // { x = expr binop x; v = x; }
6064 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6065 // Check that this is { expr1; expr2; }
6066 if (CS->size() == 2) {
6067 auto *First = CS->body_front();
6068 auto *Second = CS->body_back();
6069 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6070 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6071 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6072 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6073 // Need to find what subexpression is 'v' and what is 'x'.
6074 OpenMPAtomicUpdateChecker Checker(*this);
6075 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6076 BinaryOperator *BinOp = nullptr;
6077 if (IsUpdateExprFound) {
6078 BinOp = dyn_cast<BinaryOperator>(First);
6079 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6080 }
6081 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6082 // { v = x; x++; }
6083 // { v = x; x--; }
6084 // { v = x; ++x; }
6085 // { v = x; --x; }
6086 // { v = x; x binop= expr; }
6087 // { v = x; x = x binop expr; }
6088 // { v = x; x = expr binop x; }
6089 // Check that the first expression has form v = x.
6090 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6091 llvm::FoldingSetNodeID XId, PossibleXId;
6092 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6093 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6094 IsUpdateExprFound = XId == PossibleXId;
6095 if (IsUpdateExprFound) {
6096 V = BinOp->getLHS();
6097 X = Checker.getX();
6098 E = Checker.getExpr();
6099 UE = Checker.getUpdateExpr();
6100 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006101 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006102 }
6103 }
6104 if (!IsUpdateExprFound) {
6105 IsUpdateExprFound = !Checker.checkStatement(First);
6106 BinOp = nullptr;
6107 if (IsUpdateExprFound) {
6108 BinOp = dyn_cast<BinaryOperator>(Second);
6109 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6110 }
6111 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6112 // { x++; v = x; }
6113 // { x--; v = x; }
6114 // { ++x; v = x; }
6115 // { --x; v = x; }
6116 // { x binop= expr; v = x; }
6117 // { x = x binop expr; v = x; }
6118 // { x = expr binop x; v = x; }
6119 // Check that the second expression has form v = x.
6120 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6121 llvm::FoldingSetNodeID XId, PossibleXId;
6122 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6123 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6124 IsUpdateExprFound = XId == PossibleXId;
6125 if (IsUpdateExprFound) {
6126 V = BinOp->getLHS();
6127 X = Checker.getX();
6128 E = Checker.getExpr();
6129 UE = Checker.getUpdateExpr();
6130 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006131 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006132 }
6133 }
6134 }
6135 if (!IsUpdateExprFound) {
6136 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006137 auto *FirstExpr = dyn_cast<Expr>(First);
6138 auto *SecondExpr = dyn_cast<Expr>(Second);
6139 if (!FirstExpr || !SecondExpr ||
6140 !(FirstExpr->isInstantiationDependent() ||
6141 SecondExpr->isInstantiationDependent())) {
6142 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6143 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006144 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006145 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6146 : First->getLocStart();
6147 NoteRange = ErrorRange = FirstBinOp
6148 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006149 : SourceRange(ErrorLoc, ErrorLoc);
6150 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006151 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6152 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6153 ErrorFound = NotAnAssignmentOp;
6154 NoteLoc = ErrorLoc = SecondBinOp
6155 ? SecondBinOp->getOperatorLoc()
6156 : Second->getLocStart();
6157 NoteRange = ErrorRange =
6158 SecondBinOp ? SecondBinOp->getSourceRange()
6159 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006160 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006161 auto *PossibleXRHSInFirst =
6162 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6163 auto *PossibleXLHSInSecond =
6164 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6165 llvm::FoldingSetNodeID X1Id, X2Id;
6166 PossibleXRHSInFirst->Profile(X1Id, Context,
6167 /*Canonical=*/true);
6168 PossibleXLHSInSecond->Profile(X2Id, Context,
6169 /*Canonical=*/true);
6170 IsUpdateExprFound = X1Id == X2Id;
6171 if (IsUpdateExprFound) {
6172 V = FirstBinOp->getLHS();
6173 X = SecondBinOp->getLHS();
6174 E = SecondBinOp->getRHS();
6175 UE = nullptr;
6176 IsXLHSInRHSPart = false;
6177 IsPostfixUpdate = true;
6178 } else {
6179 ErrorFound = NotASpecificExpression;
6180 ErrorLoc = FirstBinOp->getExprLoc();
6181 ErrorRange = FirstBinOp->getSourceRange();
6182 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6183 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6184 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006185 }
6186 }
6187 }
6188 }
6189 } else {
6190 NoteLoc = ErrorLoc = Body->getLocStart();
6191 NoteRange = ErrorRange =
6192 SourceRange(Body->getLocStart(), Body->getLocStart());
6193 ErrorFound = NotTwoSubstatements;
6194 }
6195 } else {
6196 NoteLoc = ErrorLoc = Body->getLocStart();
6197 NoteRange = ErrorRange =
6198 SourceRange(Body->getLocStart(), Body->getLocStart());
6199 ErrorFound = NotACompoundStatement;
6200 }
6201 if (ErrorFound != NoError) {
6202 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6203 << ErrorRange;
6204 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6205 return StmtError();
6206 } else if (CurContext->isDependentContext()) {
6207 UE = V = E = X = nullptr;
6208 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006209 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006210 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006211
6212 getCurFunction()->setHasBranchProtectedScope();
6213
Alexey Bataev62cec442014-11-18 10:14:22 +00006214 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006215 X, V, E, UE, IsXLHSInRHSPart,
6216 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006217}
6218
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006219StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6220 Stmt *AStmt,
6221 SourceLocation StartLoc,
6222 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006223 if (!AStmt)
6224 return StmtError();
6225
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006226 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6227 // 1.2.2 OpenMP Language Terminology
6228 // Structured block - An executable statement with a single entry at the
6229 // top and a single exit at the bottom.
6230 // The point of exit cannot be a branch out of the structured block.
6231 // longjmp() and throw() must not violate the entry/exit criteria.
6232 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006233
Alexey Bataev13314bf2014-10-09 04:18:56 +00006234 // OpenMP [2.16, Nesting of Regions]
6235 // If specified, a teams construct must be contained within a target
6236 // construct. That target construct must contain no statements or directives
6237 // outside of the teams construct.
6238 if (DSAStack->hasInnerTeamsRegion()) {
6239 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6240 bool OMPTeamsFound = true;
6241 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6242 auto I = CS->body_begin();
6243 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006244 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006245 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6246 OMPTeamsFound = false;
6247 break;
6248 }
6249 ++I;
6250 }
6251 assert(I != CS->body_end() && "Not found statement");
6252 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006253 } else {
6254 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6255 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006256 }
6257 if (!OMPTeamsFound) {
6258 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6259 Diag(DSAStack->getInnerTeamsRegionLoc(),
6260 diag::note_omp_nested_teams_construct_here);
6261 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6262 << isa<OMPExecutableDirective>(S);
6263 return StmtError();
6264 }
6265 }
6266
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006267 getCurFunction()->setHasBranchProtectedScope();
6268
6269 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6270}
6271
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006272StmtResult
6273Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6274 Stmt *AStmt, SourceLocation StartLoc,
6275 SourceLocation EndLoc) {
6276 if (!AStmt)
6277 return StmtError();
6278
6279 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6280 // 1.2.2 OpenMP Language Terminology
6281 // Structured block - An executable statement with a single entry at the
6282 // top and a single exit at the bottom.
6283 // The point of exit cannot be a branch out of the structured block.
6284 // longjmp() and throw() must not violate the entry/exit criteria.
6285 CS->getCapturedDecl()->setNothrow();
6286
6287 getCurFunction()->setHasBranchProtectedScope();
6288
6289 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6290 AStmt);
6291}
6292
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006293StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6294 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6295 SourceLocation EndLoc,
6296 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6297 if (!AStmt)
6298 return StmtError();
6299
6300 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6301 // 1.2.2 OpenMP Language Terminology
6302 // Structured block - An executable statement with a single entry at the
6303 // top and a single exit at the bottom.
6304 // The point of exit cannot be a branch out of the structured block.
6305 // longjmp() and throw() must not violate the entry/exit criteria.
6306 CS->getCapturedDecl()->setNothrow();
6307
6308 OMPLoopDirective::HelperExprs B;
6309 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6310 // define the nested loops number.
6311 unsigned NestedLoopCount =
6312 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6313 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6314 VarsWithImplicitDSA, B);
6315 if (NestedLoopCount == 0)
6316 return StmtError();
6317
6318 assert((CurContext->isDependentContext() || B.builtAll()) &&
6319 "omp target parallel for loop exprs were not built");
6320
6321 if (!CurContext->isDependentContext()) {
6322 // Finalize the clauses that need pre-built expressions for CodeGen.
6323 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006324 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006325 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006326 B.NumIterations, *this, CurScope,
6327 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006328 return StmtError();
6329 }
6330 }
6331
6332 getCurFunction()->setHasBranchProtectedScope();
6333 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6334 NestedLoopCount, Clauses, AStmt,
6335 B, DSAStack->isCancelRegion());
6336}
6337
Alexey Bataev95b64a92017-05-30 16:00:04 +00006338/// Check for existence of a map clause in the list of clauses.
6339static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6340 const OpenMPClauseKind K) {
6341 return llvm::any_of(
6342 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6343}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006344
Alexey Bataev95b64a92017-05-30 16:00:04 +00006345template <typename... Params>
6346static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6347 const Params... ClauseTypes) {
6348 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006349}
6350
Michael Wong65f367f2015-07-21 13:44:28 +00006351StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6352 Stmt *AStmt,
6353 SourceLocation StartLoc,
6354 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006355 if (!AStmt)
6356 return StmtError();
6357
6358 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6359
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006360 // OpenMP [2.10.1, Restrictions, p. 97]
6361 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006362 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6363 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6364 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006365 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006366 return StmtError();
6367 }
6368
Michael Wong65f367f2015-07-21 13:44:28 +00006369 getCurFunction()->setHasBranchProtectedScope();
6370
6371 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6372 AStmt);
6373}
6374
Samuel Antaodf67fc42016-01-19 19:15:56 +00006375StmtResult
6376Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6377 SourceLocation StartLoc,
6378 SourceLocation EndLoc) {
6379 // OpenMP [2.10.2, Restrictions, p. 99]
6380 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006381 if (!hasClauses(Clauses, OMPC_map)) {
6382 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6383 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006384 return StmtError();
6385 }
6386
6387 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6388 Clauses);
6389}
6390
Samuel Antao72590762016-01-19 20:04:50 +00006391StmtResult
6392Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6393 SourceLocation StartLoc,
6394 SourceLocation EndLoc) {
6395 // OpenMP [2.10.3, Restrictions, p. 102]
6396 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006397 if (!hasClauses(Clauses, OMPC_map)) {
6398 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6399 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006400 return StmtError();
6401 }
6402
6403 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6404}
6405
Samuel Antao686c70c2016-05-26 17:30:50 +00006406StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6407 SourceLocation StartLoc,
6408 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006409 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006410 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6411 return StmtError();
6412 }
6413 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6414}
6415
Alexey Bataev13314bf2014-10-09 04:18:56 +00006416StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6417 Stmt *AStmt, SourceLocation StartLoc,
6418 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006419 if (!AStmt)
6420 return StmtError();
6421
Alexey Bataev13314bf2014-10-09 04:18:56 +00006422 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6423 // 1.2.2 OpenMP Language Terminology
6424 // Structured block - An executable statement with a single entry at the
6425 // top and a single exit at the bottom.
6426 // The point of exit cannot be a branch out of the structured block.
6427 // longjmp() and throw() must not violate the entry/exit criteria.
6428 CS->getCapturedDecl()->setNothrow();
6429
6430 getCurFunction()->setHasBranchProtectedScope();
6431
6432 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6433}
6434
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006435StmtResult
6436Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6437 SourceLocation EndLoc,
6438 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006439 if (DSAStack->isParentNowaitRegion()) {
6440 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6441 return StmtError();
6442 }
6443 if (DSAStack->isParentOrderedRegion()) {
6444 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6445 return StmtError();
6446 }
6447 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6448 CancelRegion);
6449}
6450
Alexey Bataev87933c72015-09-18 08:07:34 +00006451StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6452 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006453 SourceLocation EndLoc,
6454 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006455 if (DSAStack->isParentNowaitRegion()) {
6456 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6457 return StmtError();
6458 }
6459 if (DSAStack->isParentOrderedRegion()) {
6460 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6461 return StmtError();
6462 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006463 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006464 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6465 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006466}
6467
Alexey Bataev382967a2015-12-08 12:06:20 +00006468static bool checkGrainsizeNumTasksClauses(Sema &S,
6469 ArrayRef<OMPClause *> Clauses) {
6470 OMPClause *PrevClause = nullptr;
6471 bool ErrorFound = false;
6472 for (auto *C : Clauses) {
6473 if (C->getClauseKind() == OMPC_grainsize ||
6474 C->getClauseKind() == OMPC_num_tasks) {
6475 if (!PrevClause)
6476 PrevClause = C;
6477 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6478 S.Diag(C->getLocStart(),
6479 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6480 << getOpenMPClauseName(C->getClauseKind())
6481 << getOpenMPClauseName(PrevClause->getClauseKind());
6482 S.Diag(PrevClause->getLocStart(),
6483 diag::note_omp_previous_grainsize_num_tasks)
6484 << getOpenMPClauseName(PrevClause->getClauseKind());
6485 ErrorFound = true;
6486 }
6487 }
6488 }
6489 return ErrorFound;
6490}
6491
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006492static bool checkReductionClauseWithNogroup(Sema &S,
6493 ArrayRef<OMPClause *> Clauses) {
6494 OMPClause *ReductionClause = nullptr;
6495 OMPClause *NogroupClause = nullptr;
6496 for (auto *C : Clauses) {
6497 if (C->getClauseKind() == OMPC_reduction) {
6498 ReductionClause = C;
6499 if (NogroupClause)
6500 break;
6501 continue;
6502 }
6503 if (C->getClauseKind() == OMPC_nogroup) {
6504 NogroupClause = C;
6505 if (ReductionClause)
6506 break;
6507 continue;
6508 }
6509 }
6510 if (ReductionClause && NogroupClause) {
6511 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6512 << SourceRange(NogroupClause->getLocStart(),
6513 NogroupClause->getLocEnd());
6514 return true;
6515 }
6516 return false;
6517}
6518
Alexey Bataev49f6e782015-12-01 04:18:41 +00006519StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6520 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6521 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006522 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006523 if (!AStmt)
6524 return StmtError();
6525
6526 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6527 OMPLoopDirective::HelperExprs B;
6528 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6529 // define the nested loops number.
6530 unsigned NestedLoopCount =
6531 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006532 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006533 VarsWithImplicitDSA, B);
6534 if (NestedLoopCount == 0)
6535 return StmtError();
6536
6537 assert((CurContext->isDependentContext() || B.builtAll()) &&
6538 "omp for loop exprs were not built");
6539
Alexey Bataev382967a2015-12-08 12:06:20 +00006540 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6541 // The grainsize clause and num_tasks clause are mutually exclusive and may
6542 // not appear on the same taskloop directive.
6543 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6544 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006545 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6546 // If a reduction clause is present on the taskloop directive, the nogroup
6547 // clause must not be specified.
6548 if (checkReductionClauseWithNogroup(*this, Clauses))
6549 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006550
Alexey Bataev49f6e782015-12-01 04:18:41 +00006551 getCurFunction()->setHasBranchProtectedScope();
6552 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6553 NestedLoopCount, Clauses, AStmt, B);
6554}
6555
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006556StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6557 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6558 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006559 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006560 if (!AStmt)
6561 return StmtError();
6562
6563 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6564 OMPLoopDirective::HelperExprs B;
6565 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6566 // define the nested loops number.
6567 unsigned NestedLoopCount =
6568 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6569 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6570 VarsWithImplicitDSA, B);
6571 if (NestedLoopCount == 0)
6572 return StmtError();
6573
6574 assert((CurContext->isDependentContext() || B.builtAll()) &&
6575 "omp for loop exprs were not built");
6576
Alexey Bataev5a3af132016-03-29 08:58:54 +00006577 if (!CurContext->isDependentContext()) {
6578 // Finalize the clauses that need pre-built expressions for CodeGen.
6579 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006580 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006581 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006582 B.NumIterations, *this, CurScope,
6583 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006584 return StmtError();
6585 }
6586 }
6587
Alexey Bataev382967a2015-12-08 12:06:20 +00006588 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6589 // The grainsize clause and num_tasks clause are mutually exclusive and may
6590 // not appear on the same taskloop directive.
6591 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6592 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006593 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6594 // If a reduction clause is present on the taskloop directive, the nogroup
6595 // clause must not be specified.
6596 if (checkReductionClauseWithNogroup(*this, Clauses))
6597 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006598
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006599 getCurFunction()->setHasBranchProtectedScope();
6600 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6601 NestedLoopCount, Clauses, AStmt, B);
6602}
6603
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006604StmtResult Sema::ActOnOpenMPDistributeDirective(
6605 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6606 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006607 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006608 if (!AStmt)
6609 return StmtError();
6610
6611 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6612 OMPLoopDirective::HelperExprs B;
6613 // In presence of clause 'collapse' with number of loops, it will
6614 // define the nested loops number.
6615 unsigned NestedLoopCount =
6616 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6617 nullptr /*ordered not a clause on distribute*/, AStmt,
6618 *this, *DSAStack, VarsWithImplicitDSA, B);
6619 if (NestedLoopCount == 0)
6620 return StmtError();
6621
6622 assert((CurContext->isDependentContext() || B.builtAll()) &&
6623 "omp for loop exprs were not built");
6624
6625 getCurFunction()->setHasBranchProtectedScope();
6626 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6627 NestedLoopCount, Clauses, AStmt, B);
6628}
6629
Carlo Bertolli9925f152016-06-27 14:55:37 +00006630StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6631 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6632 SourceLocation EndLoc,
6633 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6634 if (!AStmt)
6635 return StmtError();
6636
6637 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6638 // 1.2.2 OpenMP Language Terminology
6639 // Structured block - An executable statement with a single entry at the
6640 // top and a single exit at the bottom.
6641 // The point of exit cannot be a branch out of the structured block.
6642 // longjmp() and throw() must not violate the entry/exit criteria.
6643 CS->getCapturedDecl()->setNothrow();
6644
6645 OMPLoopDirective::HelperExprs B;
6646 // In presence of clause 'collapse' with number of loops, it will
6647 // define the nested loops number.
6648 unsigned NestedLoopCount = CheckOpenMPLoop(
6649 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6650 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6651 VarsWithImplicitDSA, B);
6652 if (NestedLoopCount == 0)
6653 return StmtError();
6654
6655 assert((CurContext->isDependentContext() || B.builtAll()) &&
6656 "omp for loop exprs were not built");
6657
6658 getCurFunction()->setHasBranchProtectedScope();
6659 return OMPDistributeParallelForDirective::Create(
6660 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6661}
6662
Kelvin Li4a39add2016-07-05 05:00:15 +00006663StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6664 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6665 SourceLocation EndLoc,
6666 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6667 if (!AStmt)
6668 return StmtError();
6669
6670 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6671 // 1.2.2 OpenMP Language Terminology
6672 // Structured block - An executable statement with a single entry at the
6673 // top and a single exit at the bottom.
6674 // The point of exit cannot be a branch out of the structured block.
6675 // longjmp() and throw() must not violate the entry/exit criteria.
6676 CS->getCapturedDecl()->setNothrow();
6677
6678 OMPLoopDirective::HelperExprs B;
6679 // In presence of clause 'collapse' with number of loops, it will
6680 // define the nested loops number.
6681 unsigned NestedLoopCount = CheckOpenMPLoop(
6682 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6683 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6684 VarsWithImplicitDSA, B);
6685 if (NestedLoopCount == 0)
6686 return StmtError();
6687
6688 assert((CurContext->isDependentContext() || B.builtAll()) &&
6689 "omp for loop exprs were not built");
6690
Kelvin Lic5609492016-07-15 04:39:07 +00006691 if (checkSimdlenSafelenSpecified(*this, Clauses))
6692 return StmtError();
6693
Kelvin Li4a39add2016-07-05 05:00:15 +00006694 getCurFunction()->setHasBranchProtectedScope();
6695 return OMPDistributeParallelForSimdDirective::Create(
6696 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6697}
6698
Kelvin Li787f3fc2016-07-06 04:45:38 +00006699StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6700 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6701 SourceLocation EndLoc,
6702 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6703 if (!AStmt)
6704 return StmtError();
6705
6706 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6707 // 1.2.2 OpenMP Language Terminology
6708 // Structured block - An executable statement with a single entry at the
6709 // top and a single exit at the bottom.
6710 // The point of exit cannot be a branch out of the structured block.
6711 // longjmp() and throw() must not violate the entry/exit criteria.
6712 CS->getCapturedDecl()->setNothrow();
6713
6714 OMPLoopDirective::HelperExprs B;
6715 // In presence of clause 'collapse' with number of loops, it will
6716 // define the nested loops number.
6717 unsigned NestedLoopCount =
6718 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6719 nullptr /*ordered not a clause on distribute*/, AStmt,
6720 *this, *DSAStack, VarsWithImplicitDSA, B);
6721 if (NestedLoopCount == 0)
6722 return StmtError();
6723
6724 assert((CurContext->isDependentContext() || B.builtAll()) &&
6725 "omp for loop exprs were not built");
6726
Kelvin Lic5609492016-07-15 04:39:07 +00006727 if (checkSimdlenSafelenSpecified(*this, Clauses))
6728 return StmtError();
6729
Kelvin Li787f3fc2016-07-06 04:45:38 +00006730 getCurFunction()->setHasBranchProtectedScope();
6731 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6732 NestedLoopCount, Clauses, AStmt, B);
6733}
6734
Kelvin Lia579b912016-07-14 02:54:56 +00006735StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6736 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6737 SourceLocation EndLoc,
6738 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6739 if (!AStmt)
6740 return StmtError();
6741
6742 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6743 // 1.2.2 OpenMP Language Terminology
6744 // Structured block - An executable statement with a single entry at the
6745 // top and a single exit at the bottom.
6746 // The point of exit cannot be a branch out of the structured block.
6747 // longjmp() and throw() must not violate the entry/exit criteria.
6748 CS->getCapturedDecl()->setNothrow();
6749
6750 OMPLoopDirective::HelperExprs B;
6751 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6752 // define the nested loops number.
6753 unsigned NestedLoopCount = CheckOpenMPLoop(
6754 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6755 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6756 VarsWithImplicitDSA, B);
6757 if (NestedLoopCount == 0)
6758 return StmtError();
6759
6760 assert((CurContext->isDependentContext() || B.builtAll()) &&
6761 "omp target parallel for simd loop exprs were not built");
6762
6763 if (!CurContext->isDependentContext()) {
6764 // Finalize the clauses that need pre-built expressions for CodeGen.
6765 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006766 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006767 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6768 B.NumIterations, *this, CurScope,
6769 DSAStack))
6770 return StmtError();
6771 }
6772 }
Kelvin Lic5609492016-07-15 04:39:07 +00006773 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006774 return StmtError();
6775
6776 getCurFunction()->setHasBranchProtectedScope();
6777 return OMPTargetParallelForSimdDirective::Create(
6778 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6779}
6780
Kelvin Li986330c2016-07-20 22:57:10 +00006781StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6782 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6783 SourceLocation EndLoc,
6784 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6785 if (!AStmt)
6786 return StmtError();
6787
6788 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6789 // 1.2.2 OpenMP Language Terminology
6790 // Structured block - An executable statement with a single entry at the
6791 // top and a single exit at the bottom.
6792 // The point of exit cannot be a branch out of the structured block.
6793 // longjmp() and throw() must not violate the entry/exit criteria.
6794 CS->getCapturedDecl()->setNothrow();
6795
6796 OMPLoopDirective::HelperExprs B;
6797 // In presence of clause 'collapse' with number of loops, it will define the
6798 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006799 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006800 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6801 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6802 VarsWithImplicitDSA, B);
6803 if (NestedLoopCount == 0)
6804 return StmtError();
6805
6806 assert((CurContext->isDependentContext() || B.builtAll()) &&
6807 "omp target simd loop exprs were not built");
6808
6809 if (!CurContext->isDependentContext()) {
6810 // Finalize the clauses that need pre-built expressions for CodeGen.
6811 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006812 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006813 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6814 B.NumIterations, *this, CurScope,
6815 DSAStack))
6816 return StmtError();
6817 }
6818 }
6819
6820 if (checkSimdlenSafelenSpecified(*this, Clauses))
6821 return StmtError();
6822
6823 getCurFunction()->setHasBranchProtectedScope();
6824 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6825 NestedLoopCount, Clauses, AStmt, B);
6826}
6827
Kelvin Li02532872016-08-05 14:37:37 +00006828StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6829 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6830 SourceLocation EndLoc,
6831 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6832 if (!AStmt)
6833 return StmtError();
6834
6835 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6836 // 1.2.2 OpenMP Language Terminology
6837 // Structured block - An executable statement with a single entry at the
6838 // top and a single exit at the bottom.
6839 // The point of exit cannot be a branch out of the structured block.
6840 // longjmp() and throw() must not violate the entry/exit criteria.
6841 CS->getCapturedDecl()->setNothrow();
6842
6843 OMPLoopDirective::HelperExprs B;
6844 // In presence of clause 'collapse' with number of loops, it will
6845 // define the nested loops number.
6846 unsigned NestedLoopCount =
6847 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6848 nullptr /*ordered not a clause on distribute*/, AStmt,
6849 *this, *DSAStack, VarsWithImplicitDSA, B);
6850 if (NestedLoopCount == 0)
6851 return StmtError();
6852
6853 assert((CurContext->isDependentContext() || B.builtAll()) &&
6854 "omp teams distribute loop exprs were not built");
6855
6856 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006857 return OMPTeamsDistributeDirective::Create(
6858 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006859}
6860
Kelvin Li4e325f72016-10-25 12:50:55 +00006861StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6862 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6863 SourceLocation EndLoc,
6864 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6865 if (!AStmt)
6866 return StmtError();
6867
6868 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6869 // 1.2.2 OpenMP Language Terminology
6870 // Structured block - An executable statement with a single entry at the
6871 // top and a single exit at the bottom.
6872 // The point of exit cannot be a branch out of the structured block.
6873 // longjmp() and throw() must not violate the entry/exit criteria.
6874 CS->getCapturedDecl()->setNothrow();
6875
6876 OMPLoopDirective::HelperExprs B;
6877 // In presence of clause 'collapse' with number of loops, it will
6878 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006879 unsigned NestedLoopCount = CheckOpenMPLoop(
6880 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6881 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6882 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006883
6884 if (NestedLoopCount == 0)
6885 return StmtError();
6886
6887 assert((CurContext->isDependentContext() || B.builtAll()) &&
6888 "omp teams distribute simd loop exprs were not built");
6889
6890 if (!CurContext->isDependentContext()) {
6891 // Finalize the clauses that need pre-built expressions for CodeGen.
6892 for (auto C : Clauses) {
6893 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6894 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6895 B.NumIterations, *this, CurScope,
6896 DSAStack))
6897 return StmtError();
6898 }
6899 }
6900
6901 if (checkSimdlenSafelenSpecified(*this, Clauses))
6902 return StmtError();
6903
6904 getCurFunction()->setHasBranchProtectedScope();
6905 return OMPTeamsDistributeSimdDirective::Create(
6906 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6907}
6908
Kelvin Li579e41c2016-11-30 23:51:03 +00006909StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6910 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6911 SourceLocation EndLoc,
6912 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6913 if (!AStmt)
6914 return StmtError();
6915
6916 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6917 // 1.2.2 OpenMP Language Terminology
6918 // Structured block - An executable statement with a single entry at the
6919 // top and a single exit at the bottom.
6920 // The point of exit cannot be a branch out of the structured block.
6921 // longjmp() and throw() must not violate the entry/exit criteria.
6922 CS->getCapturedDecl()->setNothrow();
6923
6924 OMPLoopDirective::HelperExprs B;
6925 // In presence of clause 'collapse' with number of loops, it will
6926 // define the nested loops number.
6927 auto NestedLoopCount = CheckOpenMPLoop(
6928 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6929 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6930 VarsWithImplicitDSA, B);
6931
6932 if (NestedLoopCount == 0)
6933 return StmtError();
6934
6935 assert((CurContext->isDependentContext() || B.builtAll()) &&
6936 "omp for loop exprs were not built");
6937
6938 if (!CurContext->isDependentContext()) {
6939 // Finalize the clauses that need pre-built expressions for CodeGen.
6940 for (auto C : Clauses) {
6941 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6942 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6943 B.NumIterations, *this, CurScope,
6944 DSAStack))
6945 return StmtError();
6946 }
6947 }
6948
6949 if (checkSimdlenSafelenSpecified(*this, Clauses))
6950 return StmtError();
6951
6952 getCurFunction()->setHasBranchProtectedScope();
6953 return OMPTeamsDistributeParallelForSimdDirective::Create(
6954 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6955}
6956
Kelvin Li7ade93f2016-12-09 03:24:30 +00006957StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6958 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6959 SourceLocation EndLoc,
6960 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6961 if (!AStmt)
6962 return StmtError();
6963
6964 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6965 // 1.2.2 OpenMP Language Terminology
6966 // Structured block - An executable statement with a single entry at the
6967 // top and a single exit at the bottom.
6968 // The point of exit cannot be a branch out of the structured block.
6969 // longjmp() and throw() must not violate the entry/exit criteria.
6970 CS->getCapturedDecl()->setNothrow();
6971
6972 OMPLoopDirective::HelperExprs B;
6973 // In presence of clause 'collapse' with number of loops, it will
6974 // define the nested loops number.
6975 unsigned NestedLoopCount = CheckOpenMPLoop(
6976 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6977 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6978 VarsWithImplicitDSA, B);
6979
6980 if (NestedLoopCount == 0)
6981 return StmtError();
6982
6983 assert((CurContext->isDependentContext() || B.builtAll()) &&
6984 "omp for loop exprs were not built");
6985
6986 if (!CurContext->isDependentContext()) {
6987 // Finalize the clauses that need pre-built expressions for CodeGen.
6988 for (auto C : Clauses) {
6989 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6990 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6991 B.NumIterations, *this, CurScope,
6992 DSAStack))
6993 return StmtError();
6994 }
6995 }
6996
6997 getCurFunction()->setHasBranchProtectedScope();
6998 return OMPTeamsDistributeParallelForDirective::Create(
6999 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7000}
7001
Kelvin Libf594a52016-12-17 05:48:59 +00007002StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7003 Stmt *AStmt,
7004 SourceLocation StartLoc,
7005 SourceLocation EndLoc) {
7006 if (!AStmt)
7007 return StmtError();
7008
7009 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7010 // 1.2.2 OpenMP Language Terminology
7011 // Structured block - An executable statement with a single entry at the
7012 // top and a single exit at the bottom.
7013 // The point of exit cannot be a branch out of the structured block.
7014 // longjmp() and throw() must not violate the entry/exit criteria.
7015 CS->getCapturedDecl()->setNothrow();
7016
7017 getCurFunction()->setHasBranchProtectedScope();
7018
7019 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7020 AStmt);
7021}
7022
Kelvin Li83c451e2016-12-25 04:52:54 +00007023StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7024 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7025 SourceLocation EndLoc,
7026 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7027 if (!AStmt)
7028 return StmtError();
7029
7030 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7031 // 1.2.2 OpenMP Language Terminology
7032 // Structured block - An executable statement with a single entry at the
7033 // top and a single exit at the bottom.
7034 // The point of exit cannot be a branch out of the structured block.
7035 // longjmp() and throw() must not violate the entry/exit criteria.
7036 CS->getCapturedDecl()->setNothrow();
7037
7038 OMPLoopDirective::HelperExprs B;
7039 // In presence of clause 'collapse' with number of loops, it will
7040 // define the nested loops number.
7041 auto NestedLoopCount = CheckOpenMPLoop(
7042 OMPD_target_teams_distribute,
7043 getCollapseNumberExpr(Clauses),
7044 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7045 VarsWithImplicitDSA, B);
7046 if (NestedLoopCount == 0)
7047 return StmtError();
7048
7049 assert((CurContext->isDependentContext() || B.builtAll()) &&
7050 "omp target teams distribute loop exprs were not built");
7051
7052 getCurFunction()->setHasBranchProtectedScope();
7053 return OMPTargetTeamsDistributeDirective::Create(
7054 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7055}
7056
Kelvin Li80e8f562016-12-29 22:16:30 +00007057StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7058 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7059 SourceLocation EndLoc,
7060 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7061 if (!AStmt)
7062 return StmtError();
7063
7064 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7065 // 1.2.2 OpenMP Language Terminology
7066 // Structured block - An executable statement with a single entry at the
7067 // top and a single exit at the bottom.
7068 // The point of exit cannot be a branch out of the structured block.
7069 // longjmp() and throw() must not violate the entry/exit criteria.
7070 CS->getCapturedDecl()->setNothrow();
7071
7072 OMPLoopDirective::HelperExprs B;
7073 // In presence of clause 'collapse' with number of loops, it will
7074 // define the nested loops number.
7075 auto NestedLoopCount = CheckOpenMPLoop(
7076 OMPD_target_teams_distribute_parallel_for,
7077 getCollapseNumberExpr(Clauses),
7078 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7079 VarsWithImplicitDSA, B);
7080 if (NestedLoopCount == 0)
7081 return StmtError();
7082
7083 assert((CurContext->isDependentContext() || B.builtAll()) &&
7084 "omp target teams distribute parallel for loop exprs were not built");
7085
7086 if (!CurContext->isDependentContext()) {
7087 // Finalize the clauses that need pre-built expressions for CodeGen.
7088 for (auto C : Clauses) {
7089 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7090 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7091 B.NumIterations, *this, CurScope,
7092 DSAStack))
7093 return StmtError();
7094 }
7095 }
7096
7097 getCurFunction()->setHasBranchProtectedScope();
7098 return OMPTargetTeamsDistributeParallelForDirective::Create(
7099 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7100}
7101
Kelvin Li1851df52017-01-03 05:23:48 +00007102StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7103 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7104 SourceLocation EndLoc,
7105 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7106 if (!AStmt)
7107 return StmtError();
7108
7109 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7110 // 1.2.2 OpenMP Language Terminology
7111 // Structured block - An executable statement with a single entry at the
7112 // top and a single exit at the bottom.
7113 // The point of exit cannot be a branch out of the structured block.
7114 // longjmp() and throw() must not violate the entry/exit criteria.
7115 CS->getCapturedDecl()->setNothrow();
7116
7117 OMPLoopDirective::HelperExprs B;
7118 // In presence of clause 'collapse' with number of loops, it will
7119 // define the nested loops number.
7120 auto NestedLoopCount = CheckOpenMPLoop(
7121 OMPD_target_teams_distribute_parallel_for_simd,
7122 getCollapseNumberExpr(Clauses),
7123 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7124 VarsWithImplicitDSA, B);
7125 if (NestedLoopCount == 0)
7126 return StmtError();
7127
7128 assert((CurContext->isDependentContext() || B.builtAll()) &&
7129 "omp target teams distribute parallel for simd loop exprs were not "
7130 "built");
7131
7132 if (!CurContext->isDependentContext()) {
7133 // Finalize the clauses that need pre-built expressions for CodeGen.
7134 for (auto C : Clauses) {
7135 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7136 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7137 B.NumIterations, *this, CurScope,
7138 DSAStack))
7139 return StmtError();
7140 }
7141 }
7142
7143 getCurFunction()->setHasBranchProtectedScope();
7144 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7145 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7146}
7147
Kelvin Lida681182017-01-10 18:08:18 +00007148StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7149 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7150 SourceLocation EndLoc,
7151 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7152 if (!AStmt)
7153 return StmtError();
7154
7155 auto *CS = cast<CapturedStmt>(AStmt);
7156 // 1.2.2 OpenMP Language Terminology
7157 // Structured block - An executable statement with a single entry at the
7158 // top and a single exit at the bottom.
7159 // The point of exit cannot be a branch out of the structured block.
7160 // longjmp() and throw() must not violate the entry/exit criteria.
7161 CS->getCapturedDecl()->setNothrow();
7162
7163 OMPLoopDirective::HelperExprs B;
7164 // In presence of clause 'collapse' with number of loops, it will
7165 // define the nested loops number.
7166 auto NestedLoopCount = CheckOpenMPLoop(
7167 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7168 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7169 VarsWithImplicitDSA, B);
7170 if (NestedLoopCount == 0)
7171 return StmtError();
7172
7173 assert((CurContext->isDependentContext() || B.builtAll()) &&
7174 "omp target teams distribute simd loop exprs were not built");
7175
7176 getCurFunction()->setHasBranchProtectedScope();
7177 return OMPTargetTeamsDistributeSimdDirective::Create(
7178 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7179}
7180
Alexey Bataeved09d242014-05-28 05:53:51 +00007181OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007182 SourceLocation StartLoc,
7183 SourceLocation LParenLoc,
7184 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007185 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007186 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007187 case OMPC_final:
7188 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7189 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007190 case OMPC_num_threads:
7191 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7192 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007193 case OMPC_safelen:
7194 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7195 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007196 case OMPC_simdlen:
7197 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7198 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007199 case OMPC_collapse:
7200 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7201 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007202 case OMPC_ordered:
7203 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7204 break;
Michael Wonge710d542015-08-07 16:16:36 +00007205 case OMPC_device:
7206 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7207 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007208 case OMPC_num_teams:
7209 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7210 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007211 case OMPC_thread_limit:
7212 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7213 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007214 case OMPC_priority:
7215 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7216 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007217 case OMPC_grainsize:
7218 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7219 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007220 case OMPC_num_tasks:
7221 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7222 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007223 case OMPC_hint:
7224 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7225 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007226 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007227 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007228 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007229 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007230 case OMPC_private:
7231 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007232 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007233 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007234 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007235 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007236 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007237 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007238 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007239 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007240 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007241 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007242 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007243 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007244 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007245 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007246 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007247 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007248 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007249 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007250 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007251 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007252 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007253 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007254 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007255 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007256 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007257 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007258 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007259 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007260 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007261 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007262 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007263 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007264 llvm_unreachable("Clause is not allowed.");
7265 }
7266 return Res;
7267}
7268
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007269// An OpenMP directive such as 'target parallel' has two captured regions:
7270// for the 'target' and 'parallel' respectively. This function returns
7271// the region in which to capture expressions associated with a clause.
7272// A return value of OMPD_unknown signifies that the expression should not
7273// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007274static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7275 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7276 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007277 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7278
7279 switch (CKind) {
7280 case OMPC_if:
7281 switch (DKind) {
7282 case OMPD_target_parallel:
7283 // If this clause applies to the nested 'parallel' region, capture within
7284 // the 'target' region, otherwise do not capture.
7285 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7286 CaptureRegion = OMPD_target;
7287 break;
7288 case OMPD_cancel:
7289 case OMPD_parallel:
7290 case OMPD_parallel_sections:
7291 case OMPD_parallel_for:
7292 case OMPD_parallel_for_simd:
7293 case OMPD_target:
7294 case OMPD_target_simd:
7295 case OMPD_target_parallel_for:
7296 case OMPD_target_parallel_for_simd:
7297 case OMPD_target_teams:
7298 case OMPD_target_teams_distribute:
7299 case OMPD_target_teams_distribute_simd:
7300 case OMPD_target_teams_distribute_parallel_for:
7301 case OMPD_target_teams_distribute_parallel_for_simd:
7302 case OMPD_teams_distribute_parallel_for:
7303 case OMPD_teams_distribute_parallel_for_simd:
7304 case OMPD_distribute_parallel_for:
7305 case OMPD_distribute_parallel_for_simd:
7306 case OMPD_task:
7307 case OMPD_taskloop:
7308 case OMPD_taskloop_simd:
7309 case OMPD_target_data:
7310 case OMPD_target_enter_data:
7311 case OMPD_target_exit_data:
7312 case OMPD_target_update:
7313 // Do not capture if-clause expressions.
7314 break;
7315 case OMPD_threadprivate:
7316 case OMPD_taskyield:
7317 case OMPD_barrier:
7318 case OMPD_taskwait:
7319 case OMPD_cancellation_point:
7320 case OMPD_flush:
7321 case OMPD_declare_reduction:
7322 case OMPD_declare_simd:
7323 case OMPD_declare_target:
7324 case OMPD_end_declare_target:
7325 case OMPD_teams:
7326 case OMPD_simd:
7327 case OMPD_for:
7328 case OMPD_for_simd:
7329 case OMPD_sections:
7330 case OMPD_section:
7331 case OMPD_single:
7332 case OMPD_master:
7333 case OMPD_critical:
7334 case OMPD_taskgroup:
7335 case OMPD_distribute:
7336 case OMPD_ordered:
7337 case OMPD_atomic:
7338 case OMPD_distribute_simd:
7339 case OMPD_teams_distribute:
7340 case OMPD_teams_distribute_simd:
7341 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7342 case OMPD_unknown:
7343 llvm_unreachable("Unknown OpenMP directive");
7344 }
7345 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007346 case OMPC_num_threads:
7347 switch (DKind) {
7348 case OMPD_target_parallel:
7349 CaptureRegion = OMPD_target;
7350 break;
7351 case OMPD_cancel:
7352 case OMPD_parallel:
7353 case OMPD_parallel_sections:
7354 case OMPD_parallel_for:
7355 case OMPD_parallel_for_simd:
7356 case OMPD_target:
7357 case OMPD_target_simd:
7358 case OMPD_target_parallel_for:
7359 case OMPD_target_parallel_for_simd:
7360 case OMPD_target_teams:
7361 case OMPD_target_teams_distribute:
7362 case OMPD_target_teams_distribute_simd:
7363 case OMPD_target_teams_distribute_parallel_for:
7364 case OMPD_target_teams_distribute_parallel_for_simd:
7365 case OMPD_teams_distribute_parallel_for:
7366 case OMPD_teams_distribute_parallel_for_simd:
7367 case OMPD_distribute_parallel_for:
7368 case OMPD_distribute_parallel_for_simd:
7369 case OMPD_task:
7370 case OMPD_taskloop:
7371 case OMPD_taskloop_simd:
7372 case OMPD_target_data:
7373 case OMPD_target_enter_data:
7374 case OMPD_target_exit_data:
7375 case OMPD_target_update:
7376 // Do not capture num_threads-clause expressions.
7377 break;
7378 case OMPD_threadprivate:
7379 case OMPD_taskyield:
7380 case OMPD_barrier:
7381 case OMPD_taskwait:
7382 case OMPD_cancellation_point:
7383 case OMPD_flush:
7384 case OMPD_declare_reduction:
7385 case OMPD_declare_simd:
7386 case OMPD_declare_target:
7387 case OMPD_end_declare_target:
7388 case OMPD_teams:
7389 case OMPD_simd:
7390 case OMPD_for:
7391 case OMPD_for_simd:
7392 case OMPD_sections:
7393 case OMPD_section:
7394 case OMPD_single:
7395 case OMPD_master:
7396 case OMPD_critical:
7397 case OMPD_taskgroup:
7398 case OMPD_distribute:
7399 case OMPD_ordered:
7400 case OMPD_atomic:
7401 case OMPD_distribute_simd:
7402 case OMPD_teams_distribute:
7403 case OMPD_teams_distribute_simd:
7404 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7405 case OMPD_unknown:
7406 llvm_unreachable("Unknown OpenMP directive");
7407 }
7408 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007409 case OMPC_num_teams:
7410 switch (DKind) {
7411 case OMPD_target_teams:
7412 CaptureRegion = OMPD_target;
7413 break;
7414 case OMPD_cancel:
7415 case OMPD_parallel:
7416 case OMPD_parallel_sections:
7417 case OMPD_parallel_for:
7418 case OMPD_parallel_for_simd:
7419 case OMPD_target:
7420 case OMPD_target_simd:
7421 case OMPD_target_parallel:
7422 case OMPD_target_parallel_for:
7423 case OMPD_target_parallel_for_simd:
7424 case OMPD_target_teams_distribute:
7425 case OMPD_target_teams_distribute_simd:
7426 case OMPD_target_teams_distribute_parallel_for:
7427 case OMPD_target_teams_distribute_parallel_for_simd:
7428 case OMPD_teams_distribute_parallel_for:
7429 case OMPD_teams_distribute_parallel_for_simd:
7430 case OMPD_distribute_parallel_for:
7431 case OMPD_distribute_parallel_for_simd:
7432 case OMPD_task:
7433 case OMPD_taskloop:
7434 case OMPD_taskloop_simd:
7435 case OMPD_target_data:
7436 case OMPD_target_enter_data:
7437 case OMPD_target_exit_data:
7438 case OMPD_target_update:
7439 case OMPD_teams:
7440 case OMPD_teams_distribute:
7441 case OMPD_teams_distribute_simd:
7442 // Do not capture num_teams-clause expressions.
7443 break;
7444 case OMPD_threadprivate:
7445 case OMPD_taskyield:
7446 case OMPD_barrier:
7447 case OMPD_taskwait:
7448 case OMPD_cancellation_point:
7449 case OMPD_flush:
7450 case OMPD_declare_reduction:
7451 case OMPD_declare_simd:
7452 case OMPD_declare_target:
7453 case OMPD_end_declare_target:
7454 case OMPD_simd:
7455 case OMPD_for:
7456 case OMPD_for_simd:
7457 case OMPD_sections:
7458 case OMPD_section:
7459 case OMPD_single:
7460 case OMPD_master:
7461 case OMPD_critical:
7462 case OMPD_taskgroup:
7463 case OMPD_distribute:
7464 case OMPD_ordered:
7465 case OMPD_atomic:
7466 case OMPD_distribute_simd:
7467 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7468 case OMPD_unknown:
7469 llvm_unreachable("Unknown OpenMP directive");
7470 }
7471 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007472 case OMPC_thread_limit:
7473 switch (DKind) {
7474 case OMPD_target_teams:
7475 CaptureRegion = OMPD_target;
7476 break;
7477 case OMPD_cancel:
7478 case OMPD_parallel:
7479 case OMPD_parallel_sections:
7480 case OMPD_parallel_for:
7481 case OMPD_parallel_for_simd:
7482 case OMPD_target:
7483 case OMPD_target_simd:
7484 case OMPD_target_parallel:
7485 case OMPD_target_parallel_for:
7486 case OMPD_target_parallel_for_simd:
7487 case OMPD_target_teams_distribute:
7488 case OMPD_target_teams_distribute_simd:
7489 case OMPD_target_teams_distribute_parallel_for:
7490 case OMPD_target_teams_distribute_parallel_for_simd:
7491 case OMPD_teams_distribute_parallel_for:
7492 case OMPD_teams_distribute_parallel_for_simd:
7493 case OMPD_distribute_parallel_for:
7494 case OMPD_distribute_parallel_for_simd:
7495 case OMPD_task:
7496 case OMPD_taskloop:
7497 case OMPD_taskloop_simd:
7498 case OMPD_target_data:
7499 case OMPD_target_enter_data:
7500 case OMPD_target_exit_data:
7501 case OMPD_target_update:
7502 case OMPD_teams:
7503 case OMPD_teams_distribute:
7504 case OMPD_teams_distribute_simd:
7505 // Do not capture thread_limit-clause expressions.
7506 break;
7507 case OMPD_threadprivate:
7508 case OMPD_taskyield:
7509 case OMPD_barrier:
7510 case OMPD_taskwait:
7511 case OMPD_cancellation_point:
7512 case OMPD_flush:
7513 case OMPD_declare_reduction:
7514 case OMPD_declare_simd:
7515 case OMPD_declare_target:
7516 case OMPD_end_declare_target:
7517 case OMPD_simd:
7518 case OMPD_for:
7519 case OMPD_for_simd:
7520 case OMPD_sections:
7521 case OMPD_section:
7522 case OMPD_single:
7523 case OMPD_master:
7524 case OMPD_critical:
7525 case OMPD_taskgroup:
7526 case OMPD_distribute:
7527 case OMPD_ordered:
7528 case OMPD_atomic:
7529 case OMPD_distribute_simd:
7530 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7531 case OMPD_unknown:
7532 llvm_unreachable("Unknown OpenMP directive");
7533 }
7534 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007535 case OMPC_schedule:
7536 case OMPC_dist_schedule:
7537 case OMPC_firstprivate:
7538 case OMPC_lastprivate:
7539 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007540 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007541 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007542 case OMPC_linear:
7543 case OMPC_default:
7544 case OMPC_proc_bind:
7545 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007546 case OMPC_safelen:
7547 case OMPC_simdlen:
7548 case OMPC_collapse:
7549 case OMPC_private:
7550 case OMPC_shared:
7551 case OMPC_aligned:
7552 case OMPC_copyin:
7553 case OMPC_copyprivate:
7554 case OMPC_ordered:
7555 case OMPC_nowait:
7556 case OMPC_untied:
7557 case OMPC_mergeable:
7558 case OMPC_threadprivate:
7559 case OMPC_flush:
7560 case OMPC_read:
7561 case OMPC_write:
7562 case OMPC_update:
7563 case OMPC_capture:
7564 case OMPC_seq_cst:
7565 case OMPC_depend:
7566 case OMPC_device:
7567 case OMPC_threads:
7568 case OMPC_simd:
7569 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007570 case OMPC_priority:
7571 case OMPC_grainsize:
7572 case OMPC_nogroup:
7573 case OMPC_num_tasks:
7574 case OMPC_hint:
7575 case OMPC_defaultmap:
7576 case OMPC_unknown:
7577 case OMPC_uniform:
7578 case OMPC_to:
7579 case OMPC_from:
7580 case OMPC_use_device_ptr:
7581 case OMPC_is_device_ptr:
7582 llvm_unreachable("Unexpected OpenMP clause.");
7583 }
7584 return CaptureRegion;
7585}
7586
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007587OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7588 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007589 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007590 SourceLocation NameModifierLoc,
7591 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007592 SourceLocation EndLoc) {
7593 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007594 Stmt *HelperValStmt = nullptr;
7595 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007596 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7597 !Condition->isInstantiationDependent() &&
7598 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007599 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007600 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007601 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007602
Richard Smith03a4aa32016-06-23 19:02:52 +00007603 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007604
7605 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7606 CaptureRegion =
7607 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7608 if (CaptureRegion != OMPD_unknown) {
7609 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7610 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7611 HelperValStmt = buildPreInits(Context, Captures);
7612 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007613 }
7614
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007615 return new (Context)
7616 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7617 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007618}
7619
Alexey Bataev3778b602014-07-17 07:32:53 +00007620OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7621 SourceLocation StartLoc,
7622 SourceLocation LParenLoc,
7623 SourceLocation EndLoc) {
7624 Expr *ValExpr = Condition;
7625 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7626 !Condition->isInstantiationDependent() &&
7627 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007628 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007629 if (Val.isInvalid())
7630 return nullptr;
7631
Richard Smith03a4aa32016-06-23 19:02:52 +00007632 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007633 }
7634
7635 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7636}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007637ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7638 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007639 if (!Op)
7640 return ExprError();
7641
7642 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7643 public:
7644 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007645 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007646 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7647 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007648 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7649 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007650 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7651 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007652 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7653 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007654 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7655 QualType T,
7656 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007657 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7658 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007659 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7660 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007661 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007662 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007663 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007664 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7665 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007666 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7667 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007668 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7669 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007670 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007671 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007672 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007673 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7674 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007675 llvm_unreachable("conversion functions are permitted");
7676 }
7677 } ConvertDiagnoser;
7678 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7679}
7680
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007681static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007682 OpenMPClauseKind CKind,
7683 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007684 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7685 !ValExpr->isInstantiationDependent()) {
7686 SourceLocation Loc = ValExpr->getExprLoc();
7687 ExprResult Value =
7688 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7689 if (Value.isInvalid())
7690 return false;
7691
7692 ValExpr = Value.get();
7693 // The expression must evaluate to a non-negative integer value.
7694 llvm::APSInt Result;
7695 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007696 Result.isSigned() &&
7697 !((!StrictlyPositive && Result.isNonNegative()) ||
7698 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007699 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007700 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7701 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007702 return false;
7703 }
7704 }
7705 return true;
7706}
7707
Alexey Bataev568a8332014-03-06 06:15:19 +00007708OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7709 SourceLocation StartLoc,
7710 SourceLocation LParenLoc,
7711 SourceLocation EndLoc) {
7712 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007713 Stmt *HelperValStmt = nullptr;
7714 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007715
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007716 // OpenMP [2.5, Restrictions]
7717 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007718 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7719 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007720 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007721
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007722 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7723 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7724 if (CaptureRegion != OMPD_unknown) {
7725 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7726 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7727 HelperValStmt = buildPreInits(Context, Captures);
7728 }
7729
7730 return new (Context) OMPNumThreadsClause(
7731 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007732}
7733
Alexey Bataev62c87d22014-03-21 04:51:18 +00007734ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007735 OpenMPClauseKind CKind,
7736 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007737 if (!E)
7738 return ExprError();
7739 if (E->isValueDependent() || E->isTypeDependent() ||
7740 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007741 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007742 llvm::APSInt Result;
7743 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7744 if (ICE.isInvalid())
7745 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007746 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7747 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007748 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007749 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7750 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007751 return ExprError();
7752 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007753 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7754 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7755 << E->getSourceRange();
7756 return ExprError();
7757 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007758 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7759 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007760 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007761 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007762 return ICE;
7763}
7764
7765OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7766 SourceLocation LParenLoc,
7767 SourceLocation EndLoc) {
7768 // OpenMP [2.8.1, simd construct, Description]
7769 // The parameter of the safelen clause must be a constant
7770 // positive integer expression.
7771 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7772 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007773 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007774 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007775 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007776}
7777
Alexey Bataev66b15b52015-08-21 11:14:16 +00007778OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7779 SourceLocation LParenLoc,
7780 SourceLocation EndLoc) {
7781 // OpenMP [2.8.1, simd construct, Description]
7782 // The parameter of the simdlen clause must be a constant
7783 // positive integer expression.
7784 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7785 if (Simdlen.isInvalid())
7786 return nullptr;
7787 return new (Context)
7788 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7789}
7790
Alexander Musman64d33f12014-06-04 07:53:32 +00007791OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7792 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007793 SourceLocation LParenLoc,
7794 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007795 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007796 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007797 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007798 // The parameter of the collapse clause must be a constant
7799 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007800 ExprResult NumForLoopsResult =
7801 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7802 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007803 return nullptr;
7804 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007805 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007806}
7807
Alexey Bataev10e775f2015-07-30 11:36:16 +00007808OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7809 SourceLocation EndLoc,
7810 SourceLocation LParenLoc,
7811 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007812 // OpenMP [2.7.1, loop construct, Description]
7813 // OpenMP [2.8.1, simd construct, Description]
7814 // OpenMP [2.9.6, distribute construct, Description]
7815 // The parameter of the ordered clause must be a constant
7816 // positive integer expression if any.
7817 if (NumForLoops && LParenLoc.isValid()) {
7818 ExprResult NumForLoopsResult =
7819 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7820 if (NumForLoopsResult.isInvalid())
7821 return nullptr;
7822 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007823 } else
7824 NumForLoops = nullptr;
7825 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007826 return new (Context)
7827 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7828}
7829
Alexey Bataeved09d242014-05-28 05:53:51 +00007830OMPClause *Sema::ActOnOpenMPSimpleClause(
7831 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7832 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007833 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007834 switch (Kind) {
7835 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007836 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007837 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7838 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007839 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007840 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007841 Res = ActOnOpenMPProcBindClause(
7842 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7843 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007844 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007845 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007846 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007847 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007848 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007849 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007850 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007851 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007852 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007853 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007854 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007855 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007856 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007857 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007858 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007859 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007860 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007861 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007862 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007863 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007864 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007865 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007866 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007867 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007868 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007869 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007870 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007871 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007872 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007873 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007874 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007875 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007876 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007877 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007878 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007879 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007880 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007881 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007882 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007883 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007884 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007885 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007886 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007887 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007888 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007889 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007890 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007891 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007892 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007893 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007894 llvm_unreachable("Clause is not allowed.");
7895 }
7896 return Res;
7897}
7898
Alexey Bataev6402bca2015-12-28 07:25:51 +00007899static std::string
7900getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7901 ArrayRef<unsigned> Exclude = llvm::None) {
7902 std::string Values;
7903 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7904 unsigned Skipped = Exclude.size();
7905 auto S = Exclude.begin(), E = Exclude.end();
7906 for (unsigned i = First; i < Last; ++i) {
7907 if (std::find(S, E, i) != E) {
7908 --Skipped;
7909 continue;
7910 }
7911 Values += "'";
7912 Values += getOpenMPSimpleClauseTypeName(K, i);
7913 Values += "'";
7914 if (i == Bound - Skipped)
7915 Values += " or ";
7916 else if (i != Bound + 1 - Skipped)
7917 Values += ", ";
7918 }
7919 return Values;
7920}
7921
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007922OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7923 SourceLocation KindKwLoc,
7924 SourceLocation StartLoc,
7925 SourceLocation LParenLoc,
7926 SourceLocation EndLoc) {
7927 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007928 static_assert(OMPC_DEFAULT_unknown > 0,
7929 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007930 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007931 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7932 /*Last=*/OMPC_DEFAULT_unknown)
7933 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007934 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007935 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007936 switch (Kind) {
7937 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007938 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007939 break;
7940 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007941 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007942 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007943 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007944 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007945 break;
7946 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007947 return new (Context)
7948 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007949}
7950
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007951OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7952 SourceLocation KindKwLoc,
7953 SourceLocation StartLoc,
7954 SourceLocation LParenLoc,
7955 SourceLocation EndLoc) {
7956 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007957 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007958 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7959 /*Last=*/OMPC_PROC_BIND_unknown)
7960 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007961 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007962 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007963 return new (Context)
7964 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007965}
7966
Alexey Bataev56dafe82014-06-20 07:16:17 +00007967OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007968 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007969 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007970 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007971 SourceLocation EndLoc) {
7972 OMPClause *Res = nullptr;
7973 switch (Kind) {
7974 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007975 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7976 assert(Argument.size() == NumberOfElements &&
7977 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007978 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007979 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7980 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7981 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7982 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7983 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007984 break;
7985 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007986 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7987 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7988 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7989 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007990 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007991 case OMPC_dist_schedule:
7992 Res = ActOnOpenMPDistScheduleClause(
7993 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7994 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7995 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007996 case OMPC_defaultmap:
7997 enum { Modifier, DefaultmapKind };
7998 Res = ActOnOpenMPDefaultmapClause(
7999 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8000 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008001 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8002 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008003 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008004 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008005 case OMPC_num_threads:
8006 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008007 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008008 case OMPC_collapse:
8009 case OMPC_default:
8010 case OMPC_proc_bind:
8011 case OMPC_private:
8012 case OMPC_firstprivate:
8013 case OMPC_lastprivate:
8014 case OMPC_shared:
8015 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008016 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008017 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008018 case OMPC_linear:
8019 case OMPC_aligned:
8020 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008021 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008022 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008023 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008024 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008025 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008026 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008027 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008028 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008029 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008030 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008031 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008032 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008033 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008034 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008035 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008036 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008037 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008038 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008039 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008040 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008041 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008042 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008043 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008044 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008045 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008046 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008047 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008048 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008049 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008050 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008051 llvm_unreachable("Clause is not allowed.");
8052 }
8053 return Res;
8054}
8055
Alexey Bataev6402bca2015-12-28 07:25:51 +00008056static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8057 OpenMPScheduleClauseModifier M2,
8058 SourceLocation M1Loc, SourceLocation M2Loc) {
8059 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8060 SmallVector<unsigned, 2> Excluded;
8061 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8062 Excluded.push_back(M2);
8063 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8064 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8065 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8066 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8067 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8068 << getListOfPossibleValues(OMPC_schedule,
8069 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8070 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8071 Excluded)
8072 << getOpenMPClauseName(OMPC_schedule);
8073 return true;
8074 }
8075 return false;
8076}
8077
Alexey Bataev56dafe82014-06-20 07:16:17 +00008078OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008079 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008080 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008081 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8082 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8083 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8084 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8085 return nullptr;
8086 // OpenMP, 2.7.1, Loop Construct, Restrictions
8087 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8088 // but not both.
8089 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8090 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8091 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8092 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8093 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8094 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8095 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8096 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8097 return nullptr;
8098 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008099 if (Kind == OMPC_SCHEDULE_unknown) {
8100 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008101 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8102 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8103 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8104 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8105 Exclude);
8106 } else {
8107 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8108 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008109 }
8110 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8111 << Values << getOpenMPClauseName(OMPC_schedule);
8112 return nullptr;
8113 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008114 // OpenMP, 2.7.1, Loop Construct, Restrictions
8115 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8116 // schedule(guided).
8117 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8118 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8119 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8120 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8121 diag::err_omp_schedule_nonmonotonic_static);
8122 return nullptr;
8123 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008124 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008125 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008126 if (ChunkSize) {
8127 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8128 !ChunkSize->isInstantiationDependent() &&
8129 !ChunkSize->containsUnexpandedParameterPack()) {
8130 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8131 ExprResult Val =
8132 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8133 if (Val.isInvalid())
8134 return nullptr;
8135
8136 ValExpr = Val.get();
8137
8138 // OpenMP [2.7.1, Restrictions]
8139 // chunk_size must be a loop invariant integer expression with a positive
8140 // value.
8141 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008142 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8143 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8144 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008145 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008146 return nullptr;
8147 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008148 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
8149 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00008150 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8151 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8152 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008153 }
8154 }
8155 }
8156
Alexey Bataev6402bca2015-12-28 07:25:51 +00008157 return new (Context)
8158 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008159 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008160}
8161
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008162OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8163 SourceLocation StartLoc,
8164 SourceLocation EndLoc) {
8165 OMPClause *Res = nullptr;
8166 switch (Kind) {
8167 case OMPC_ordered:
8168 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8169 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008170 case OMPC_nowait:
8171 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8172 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008173 case OMPC_untied:
8174 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8175 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008176 case OMPC_mergeable:
8177 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8178 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008179 case OMPC_read:
8180 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8181 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008182 case OMPC_write:
8183 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8184 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008185 case OMPC_update:
8186 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8187 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008188 case OMPC_capture:
8189 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8190 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008191 case OMPC_seq_cst:
8192 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8193 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008194 case OMPC_threads:
8195 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8196 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008197 case OMPC_simd:
8198 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8199 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008200 case OMPC_nogroup:
8201 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8202 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008203 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008204 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008205 case OMPC_num_threads:
8206 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008207 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008208 case OMPC_collapse:
8209 case OMPC_schedule:
8210 case OMPC_private:
8211 case OMPC_firstprivate:
8212 case OMPC_lastprivate:
8213 case OMPC_shared:
8214 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008215 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008216 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008217 case OMPC_linear:
8218 case OMPC_aligned:
8219 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008220 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008221 case OMPC_default:
8222 case OMPC_proc_bind:
8223 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008224 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008225 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008226 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008227 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008228 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008229 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008230 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008231 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008232 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008233 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008234 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008235 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008236 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008237 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008238 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008239 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008240 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008241 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008242 llvm_unreachable("Clause is not allowed.");
8243 }
8244 return Res;
8245}
8246
Alexey Bataev236070f2014-06-20 11:19:47 +00008247OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8248 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008249 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008250 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8251}
8252
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008253OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8254 SourceLocation EndLoc) {
8255 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8256}
8257
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008258OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8259 SourceLocation EndLoc) {
8260 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8261}
8262
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008263OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8264 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008265 return new (Context) OMPReadClause(StartLoc, EndLoc);
8266}
8267
Alexey Bataevdea47612014-07-23 07:46:59 +00008268OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8269 SourceLocation EndLoc) {
8270 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8271}
8272
Alexey Bataev67a4f222014-07-23 10:25:33 +00008273OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8274 SourceLocation EndLoc) {
8275 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8276}
8277
Alexey Bataev459dec02014-07-24 06:46:57 +00008278OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8279 SourceLocation EndLoc) {
8280 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8281}
8282
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008283OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8284 SourceLocation EndLoc) {
8285 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8286}
8287
Alexey Bataev346265e2015-09-25 10:37:12 +00008288OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8289 SourceLocation EndLoc) {
8290 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8291}
8292
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008293OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8294 SourceLocation EndLoc) {
8295 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8296}
8297
Alexey Bataevb825de12015-12-07 10:51:44 +00008298OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8299 SourceLocation EndLoc) {
8300 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8301}
8302
Alexey Bataevc5e02582014-06-16 07:08:35 +00008303OMPClause *Sema::ActOnOpenMPVarListClause(
8304 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8305 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8306 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008307 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008308 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8309 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8310 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008311 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008312 switch (Kind) {
8313 case OMPC_private:
8314 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8315 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008316 case OMPC_firstprivate:
8317 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8318 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008319 case OMPC_lastprivate:
8320 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8321 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008322 case OMPC_shared:
8323 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8324 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008325 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008326 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8327 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008328 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008329 case OMPC_task_reduction:
8330 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8331 EndLoc, ReductionIdScopeSpec,
8332 ReductionId);
8333 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008334 case OMPC_in_reduction:
8335 Res =
8336 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8337 EndLoc, ReductionIdScopeSpec, ReductionId);
8338 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008339 case OMPC_linear:
8340 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008341 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008342 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008343 case OMPC_aligned:
8344 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8345 ColonLoc, EndLoc);
8346 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008347 case OMPC_copyin:
8348 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8349 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008350 case OMPC_copyprivate:
8351 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8352 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008353 case OMPC_flush:
8354 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8355 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008356 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008357 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008358 StartLoc, LParenLoc, EndLoc);
8359 break;
8360 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008361 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8362 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8363 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008364 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008365 case OMPC_to:
8366 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8367 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008368 case OMPC_from:
8369 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8370 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008371 case OMPC_use_device_ptr:
8372 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8373 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008374 case OMPC_is_device_ptr:
8375 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8376 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008377 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008378 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008379 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008380 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008381 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008382 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008383 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008384 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008385 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008386 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008387 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008388 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008389 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008390 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008391 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008392 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008393 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008394 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008395 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008396 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008397 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008398 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008399 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008400 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008401 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008402 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008403 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008404 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008405 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008406 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008407 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008408 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008409 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008410 llvm_unreachable("Clause is not allowed.");
8411 }
8412 return Res;
8413}
8414
Alexey Bataev90c228f2016-02-08 09:29:13 +00008415ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008416 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008417 ExprResult Res = BuildDeclRefExpr(
8418 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8419 if (!Res.isUsable())
8420 return ExprError();
8421 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8422 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8423 if (!Res.isUsable())
8424 return ExprError();
8425 }
8426 if (VK != VK_LValue && Res.get()->isGLValue()) {
8427 Res = DefaultLvalueConversion(Res.get());
8428 if (!Res.isUsable())
8429 return ExprError();
8430 }
8431 return Res;
8432}
8433
Alexey Bataev60da77e2016-02-29 05:54:20 +00008434static std::pair<ValueDecl *, bool>
8435getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8436 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008437 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8438 RefExpr->containsUnexpandedParameterPack())
8439 return std::make_pair(nullptr, true);
8440
Alexey Bataevd985eda2016-02-10 11:29:16 +00008441 // OpenMP [3.1, C/C++]
8442 // A list item is a variable name.
8443 // OpenMP [2.9.3.3, Restrictions, p.1]
8444 // A variable that is part of another variable (as an array or
8445 // structure element) cannot appear in a private clause.
8446 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008447 enum {
8448 NoArrayExpr = -1,
8449 ArraySubscript = 0,
8450 OMPArraySection = 1
8451 } IsArrayExpr = NoArrayExpr;
8452 if (AllowArraySection) {
8453 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8454 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8455 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8456 Base = TempASE->getBase()->IgnoreParenImpCasts();
8457 RefExpr = Base;
8458 IsArrayExpr = ArraySubscript;
8459 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8460 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8461 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8462 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8463 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8464 Base = TempASE->getBase()->IgnoreParenImpCasts();
8465 RefExpr = Base;
8466 IsArrayExpr = OMPArraySection;
8467 }
8468 }
8469 ELoc = RefExpr->getExprLoc();
8470 ERange = RefExpr->getSourceRange();
8471 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008472 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8473 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8474 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8475 (S.getCurrentThisType().isNull() || !ME ||
8476 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8477 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008478 if (IsArrayExpr != NoArrayExpr)
8479 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8480 << ERange;
8481 else {
8482 S.Diag(ELoc,
8483 AllowArraySection
8484 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8485 : diag::err_omp_expected_var_name_member_expr)
8486 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8487 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008488 return std::make_pair(nullptr, false);
8489 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008490 return std::make_pair(
8491 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008492}
8493
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008494OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8495 SourceLocation StartLoc,
8496 SourceLocation LParenLoc,
8497 SourceLocation EndLoc) {
8498 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008499 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008500 for (auto &RefExpr : VarList) {
8501 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008502 SourceLocation ELoc;
8503 SourceRange ERange;
8504 Expr *SimpleRefExpr = RefExpr;
8505 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008506 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008507 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008508 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008509 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008510 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008511 ValueDecl *D = Res.first;
8512 if (!D)
8513 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008514
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008515 QualType Type = D->getType();
8516 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008517
8518 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8519 // A variable that appears in a private clause must not have an incomplete
8520 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008521 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008522 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008523 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008524
Alexey Bataev758e55e2013-09-06 18:03:48 +00008525 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8526 // in a Construct]
8527 // Variables with the predetermined data-sharing attributes may not be
8528 // listed in data-sharing attributes clauses, except for the cases
8529 // listed below. For these exceptions only, listing a predetermined
8530 // variable in a data-sharing attribute clause is allowed and overrides
8531 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008532 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008533 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008534 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8535 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008536 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008537 continue;
8538 }
8539
Kelvin Libf594a52016-12-17 05:48:59 +00008540 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008541 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008542 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008543 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008544 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8545 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008546 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008547 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008548 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008549 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008550 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008551 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008552 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008553 continue;
8554 }
8555
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008556 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8557 // A list item cannot appear in both a map clause and a data-sharing
8558 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008559 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008560 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008561 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008562 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008563 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008564 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008565 CurrDir == OMPD_target_parallel_for_simd ||
8566 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008567 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008568 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008569 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008570 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8571 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8572 ConflictKind = WhereFoundClauseKind;
8573 return true;
8574 })) {
8575 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008576 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008577 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008578 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008579 ReportOriginalDSA(*this, DSAStack, D, DVar);
8580 continue;
8581 }
8582 }
8583
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008584 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8585 // A variable of class type (or array thereof) that appears in a private
8586 // clause requires an accessible, unambiguous default constructor for the
8587 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008588 // Generate helper private variable and initialize it with the default
8589 // value. The address of the original variable is replaced by the address of
8590 // the new private variable in CodeGen. This new variable is not added to
8591 // IdResolver, so the code in the OpenMP region uses original variable for
8592 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008593 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008594 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8595 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008596 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008597 if (VDPrivate->isInvalidDecl())
8598 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008599 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008600 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008601
Alexey Bataev90c228f2016-02-08 09:29:13 +00008602 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008603 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008604 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008605 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008606 Vars.push_back((VD || CurContext->isDependentContext())
8607 ? RefExpr->IgnoreParens()
8608 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008609 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008610 }
8611
Alexey Bataeved09d242014-05-28 05:53:51 +00008612 if (Vars.empty())
8613 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008614
Alexey Bataev03b340a2014-10-21 03:16:40 +00008615 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8616 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008617}
8618
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008619namespace {
8620class DiagsUninitializedSeveretyRAII {
8621private:
8622 DiagnosticsEngine &Diags;
8623 SourceLocation SavedLoc;
8624 bool IsIgnored;
8625
8626public:
8627 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8628 bool IsIgnored)
8629 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8630 if (!IsIgnored) {
8631 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8632 /*Map*/ diag::Severity::Ignored, Loc);
8633 }
8634 }
8635 ~DiagsUninitializedSeveretyRAII() {
8636 if (!IsIgnored)
8637 Diags.popMappings(SavedLoc);
8638 }
8639};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008640}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008641
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008642OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8643 SourceLocation StartLoc,
8644 SourceLocation LParenLoc,
8645 SourceLocation EndLoc) {
8646 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008647 SmallVector<Expr *, 8> PrivateCopies;
8648 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008649 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008650 bool IsImplicitClause =
8651 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8652 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8653
Alexey Bataeved09d242014-05-28 05:53:51 +00008654 for (auto &RefExpr : VarList) {
8655 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008656 SourceLocation ELoc;
8657 SourceRange ERange;
8658 Expr *SimpleRefExpr = RefExpr;
8659 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008660 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008661 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008662 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008663 PrivateCopies.push_back(nullptr);
8664 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008665 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008666 ValueDecl *D = Res.first;
8667 if (!D)
8668 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008669
Alexey Bataev60da77e2016-02-29 05:54:20 +00008670 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008671 QualType Type = D->getType();
8672 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008673
8674 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8675 // A variable that appears in a private clause must not have an incomplete
8676 // type or a reference type.
8677 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008678 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008679 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008680 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008681
8682 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8683 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008684 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008685 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008686 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008687
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008688 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008689 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008690 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008691 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008692 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008693 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008694 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008695 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8696 // A list item that specifies a given variable may not appear in more
8697 // than one clause on the same directive, except that a variable may be
8698 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008699 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8700 // A list item may appear in a firstprivate or lastprivate clause but not
8701 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008702 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008703 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8704 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008705 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008706 << getOpenMPClauseName(DVar.CKind)
8707 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008708 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008709 continue;
8710 }
8711
8712 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8713 // in a Construct]
8714 // Variables with the predetermined data-sharing attributes may not be
8715 // listed in data-sharing attributes clauses, except for the cases
8716 // listed below. For these exceptions only, listing a predetermined
8717 // variable in a data-sharing attribute clause is allowed and overrides
8718 // the variable's predetermined data-sharing attributes.
8719 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8720 // in a Construct, C/C++, p.2]
8721 // Variables with const-qualified type having no mutable member may be
8722 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008723 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008724 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8725 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008726 << getOpenMPClauseName(DVar.CKind)
8727 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008728 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008729 continue;
8730 }
8731
8732 // OpenMP [2.9.3.4, Restrictions, p.2]
8733 // A list item that is private within a parallel region must not appear
8734 // in a firstprivate clause on a worksharing construct if any of the
8735 // worksharing regions arising from the worksharing construct ever bind
8736 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008737 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8738 // A list item that is private within a teams region must not appear in a
8739 // firstprivate clause on a distribute construct if any of the distribute
8740 // regions arising from the distribute construct ever bind to any of the
8741 // teams regions arising from the teams construct.
8742 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8743 // A list item that appears in a reduction clause of a teams construct
8744 // must not appear in a firstprivate clause on a distribute construct if
8745 // any of the distribute regions arising from the distribute construct
8746 // ever bind to any of the teams regions arising from the teams construct.
8747 if ((isOpenMPWorksharingDirective(CurrDir) ||
8748 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008749 !isOpenMPParallelDirective(CurrDir) &&
8750 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008751 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008752 if (DVar.CKind != OMPC_shared &&
8753 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008754 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008755 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008756 Diag(ELoc, diag::err_omp_required_access)
8757 << getOpenMPClauseName(OMPC_firstprivate)
8758 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008759 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008760 continue;
8761 }
8762 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008763 // OpenMP [2.9.3.4, Restrictions, p.3]
8764 // A list item that appears in a reduction clause of a parallel construct
8765 // must not appear in a firstprivate clause on a worksharing or task
8766 // construct if any of the worksharing or task regions arising from the
8767 // worksharing or task construct ever bind to any of the parallel regions
8768 // arising from the parallel construct.
8769 // OpenMP [2.9.3.4, Restrictions, p.4]
8770 // A list item that appears in a reduction clause in worksharing
8771 // construct must not appear in a firstprivate clause in a task construct
8772 // encountered during execution of any of the worksharing regions arising
8773 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008774 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008775 DVar = DSAStack->hasInnermostDSA(
8776 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8777 [](OpenMPDirectiveKind K) -> bool {
8778 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008779 isOpenMPWorksharingDirective(K) ||
8780 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008781 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008782 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008783 if (DVar.CKind == OMPC_reduction &&
8784 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008785 isOpenMPWorksharingDirective(DVar.DKind) ||
8786 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008787 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8788 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008789 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008790 continue;
8791 }
8792 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008793
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008794 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8795 // A list item cannot appear in both a map clause and a data-sharing
8796 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008797 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008798 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008799 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008800 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008801 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008802 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008803 CurrDir == OMPD_target_parallel_for_simd ||
8804 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008805 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008806 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008807 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008808 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8809 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8810 ConflictKind = WhereFoundClauseKind;
8811 return true;
8812 })) {
8813 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008814 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008815 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008816 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8817 ReportOriginalDSA(*this, DSAStack, D, DVar);
8818 continue;
8819 }
8820 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008821 }
8822
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008823 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008824 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008825 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008826 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8827 << getOpenMPClauseName(OMPC_firstprivate) << Type
8828 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8829 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008830 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008831 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008832 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008833 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008834 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008835 continue;
8836 }
8837
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008838 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008839 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8840 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008841 // Generate helper private variable and initialize it with the value of the
8842 // original variable. The address of the original variable is replaced by
8843 // the address of the new private variable in the CodeGen. This new variable
8844 // is not added to IdResolver, so the code in the OpenMP region uses
8845 // original variable for proper diagnostics and variable capturing.
8846 Expr *VDInitRefExpr = nullptr;
8847 // For arrays generate initializer for single element and replace it by the
8848 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008849 if (Type->isArrayType()) {
8850 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008851 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008852 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008853 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008854 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008855 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008856 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008857 InitializedEntity Entity =
8858 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008859 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8860
8861 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8862 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8863 if (Result.isInvalid())
8864 VDPrivate->setInvalidDecl();
8865 else
8866 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008867 // Remove temp variable declaration.
8868 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008869 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008870 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8871 ".firstprivate.temp");
8872 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8873 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008874 AddInitializerToDecl(VDPrivate,
8875 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008876 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008877 }
8878 if (VDPrivate->isInvalidDecl()) {
8879 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008880 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008881 diag::note_omp_task_predetermined_firstprivate_here);
8882 }
8883 continue;
8884 }
8885 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008886 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008887 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8888 RefExpr->getExprLoc());
8889 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008890 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008891 if (TopDVar.CKind == OMPC_lastprivate)
8892 Ref = TopDVar.PrivateCopy;
8893 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008894 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008895 if (!IsOpenMPCapturedDecl(D))
8896 ExprCaptures.push_back(Ref->getDecl());
8897 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008898 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008899 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008900 Vars.push_back((VD || CurContext->isDependentContext())
8901 ? RefExpr->IgnoreParens()
8902 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008903 PrivateCopies.push_back(VDPrivateRefExpr);
8904 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008905 }
8906
Alexey Bataeved09d242014-05-28 05:53:51 +00008907 if (Vars.empty())
8908 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008909
8910 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008911 Vars, PrivateCopies, Inits,
8912 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008913}
8914
Alexander Musman1bb328c2014-06-04 13:06:39 +00008915OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8916 SourceLocation StartLoc,
8917 SourceLocation LParenLoc,
8918 SourceLocation EndLoc) {
8919 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008920 SmallVector<Expr *, 8> SrcExprs;
8921 SmallVector<Expr *, 8> DstExprs;
8922 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008923 SmallVector<Decl *, 4> ExprCaptures;
8924 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008925 for (auto &RefExpr : VarList) {
8926 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008927 SourceLocation ELoc;
8928 SourceRange ERange;
8929 Expr *SimpleRefExpr = RefExpr;
8930 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008931 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008932 // It will be analyzed later.
8933 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008934 SrcExprs.push_back(nullptr);
8935 DstExprs.push_back(nullptr);
8936 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008937 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008938 ValueDecl *D = Res.first;
8939 if (!D)
8940 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008941
Alexey Bataev74caaf22016-02-20 04:09:36 +00008942 QualType Type = D->getType();
8943 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008944
8945 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8946 // A variable that appears in a lastprivate clause must not have an
8947 // incomplete type or a reference type.
8948 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008949 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008950 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008951 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008952
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008953 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008954 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8955 // in a Construct]
8956 // Variables with the predetermined data-sharing attributes may not be
8957 // listed in data-sharing attributes clauses, except for the cases
8958 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008959 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8960 // A list item may appear in a firstprivate or lastprivate clause but not
8961 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008962 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008963 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008964 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00008965 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8966 Diag(ELoc, diag::err_omp_wrong_dsa)
8967 << getOpenMPClauseName(DVar.CKind)
8968 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008969 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008970 continue;
8971 }
8972
Alexey Bataevf29276e2014-06-18 04:14:57 +00008973 // OpenMP [2.14.3.5, Restrictions, p.2]
8974 // A list item that is private within a parallel region, or that appears in
8975 // the reduction clause of a parallel construct, must not appear in a
8976 // lastprivate clause on a worksharing construct if any of the corresponding
8977 // worksharing regions ever binds to any of the corresponding parallel
8978 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008979 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008980 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008981 !isOpenMPParallelDirective(CurrDir) &&
8982 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008983 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008984 if (DVar.CKind != OMPC_shared) {
8985 Diag(ELoc, diag::err_omp_required_access)
8986 << getOpenMPClauseName(OMPC_lastprivate)
8987 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008988 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008989 continue;
8990 }
8991 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008992
Alexander Musman1bb328c2014-06-04 13:06:39 +00008993 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008994 // A variable of class type (or array thereof) that appears in a
8995 // lastprivate clause requires an accessible, unambiguous default
8996 // constructor for the class type, unless the list item is also specified
8997 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008998 // A variable of class type (or array thereof) that appears in a
8999 // lastprivate clause requires an accessible, unambiguous copy assignment
9000 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009001 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009002 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009003 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009004 D->hasAttrs() ? &D->getAttrs() : nullptr);
9005 auto *PseudoSrcExpr =
9006 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009007 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009008 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009009 D->hasAttrs() ? &D->getAttrs() : nullptr);
9010 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009011 // For arrays generate assignment operation for single element and replace
9012 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009013 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009014 PseudoDstExpr, PseudoSrcExpr);
9015 if (AssignmentOp.isInvalid())
9016 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009017 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009018 /*DiscardedValue=*/true);
9019 if (AssignmentOp.isInvalid())
9020 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009021
Alexey Bataev74caaf22016-02-20 04:09:36 +00009022 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009023 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009024 if (TopDVar.CKind == OMPC_firstprivate)
9025 Ref = TopDVar.PrivateCopy;
9026 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009027 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009028 if (!IsOpenMPCapturedDecl(D))
9029 ExprCaptures.push_back(Ref->getDecl());
9030 }
9031 if (TopDVar.CKind == OMPC_firstprivate ||
9032 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009033 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009034 ExprResult RefRes = DefaultLvalueConversion(Ref);
9035 if (!RefRes.isUsable())
9036 continue;
9037 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009038 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9039 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009040 if (!PostUpdateRes.isUsable())
9041 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009042 ExprPostUpdates.push_back(
9043 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009044 }
9045 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009046 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009047 Vars.push_back((VD || CurContext->isDependentContext())
9048 ? RefExpr->IgnoreParens()
9049 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009050 SrcExprs.push_back(PseudoSrcExpr);
9051 DstExprs.push_back(PseudoDstExpr);
9052 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009053 }
9054
9055 if (Vars.empty())
9056 return nullptr;
9057
9058 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009059 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009060 buildPreInits(Context, ExprCaptures),
9061 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009062}
9063
Alexey Bataev758e55e2013-09-06 18:03:48 +00009064OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9065 SourceLocation StartLoc,
9066 SourceLocation LParenLoc,
9067 SourceLocation EndLoc) {
9068 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009069 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009070 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009071 SourceLocation ELoc;
9072 SourceRange ERange;
9073 Expr *SimpleRefExpr = RefExpr;
9074 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009075 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009076 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009077 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009078 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009079 ValueDecl *D = Res.first;
9080 if (!D)
9081 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009082
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009083 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009084 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9085 // in a Construct]
9086 // Variables with the predetermined data-sharing attributes may not be
9087 // listed in data-sharing attributes clauses, except for the cases
9088 // listed below. For these exceptions only, listing a predetermined
9089 // variable in a data-sharing attribute clause is allowed and overrides
9090 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009091 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009092 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9093 DVar.RefExpr) {
9094 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9095 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009096 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009097 continue;
9098 }
9099
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009100 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009101 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009102 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009103 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009104 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9105 ? RefExpr->IgnoreParens()
9106 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009107 }
9108
Alexey Bataeved09d242014-05-28 05:53:51 +00009109 if (Vars.empty())
9110 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009111
9112 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9113}
9114
Alexey Bataevc5e02582014-06-16 07:08:35 +00009115namespace {
9116class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9117 DSAStackTy *Stack;
9118
9119public:
9120 bool VisitDeclRefExpr(DeclRefExpr *E) {
9121 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009122 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009123 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9124 return false;
9125 if (DVar.CKind != OMPC_unknown)
9126 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009127 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9128 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009129 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009130 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009131 return true;
9132 return false;
9133 }
9134 return false;
9135 }
9136 bool VisitStmt(Stmt *S) {
9137 for (auto Child : S->children()) {
9138 if (Child && Visit(Child))
9139 return true;
9140 }
9141 return false;
9142 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009143 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009144};
Alexey Bataev23b69422014-06-18 07:08:49 +00009145} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009146
Alexey Bataev60da77e2016-02-29 05:54:20 +00009147namespace {
9148// Transform MemberExpression for specified FieldDecl of current class to
9149// DeclRefExpr to specified OMPCapturedExprDecl.
9150class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9151 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9152 ValueDecl *Field;
9153 DeclRefExpr *CapturedExpr;
9154
9155public:
9156 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9157 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9158
9159 ExprResult TransformMemberExpr(MemberExpr *E) {
9160 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9161 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009162 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009163 return CapturedExpr;
9164 }
9165 return BaseTransform::TransformMemberExpr(E);
9166 }
9167 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9168};
9169} // namespace
9170
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009171template <typename T>
9172static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9173 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9174 for (auto &Set : Lookups) {
9175 for (auto *D : Set) {
9176 if (auto Res = Gen(cast<ValueDecl>(D)))
9177 return Res;
9178 }
9179 }
9180 return T();
9181}
9182
9183static ExprResult
9184buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9185 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9186 const DeclarationNameInfo &ReductionId, QualType Ty,
9187 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9188 if (ReductionIdScopeSpec.isInvalid())
9189 return ExprError();
9190 SmallVector<UnresolvedSet<8>, 4> Lookups;
9191 if (S) {
9192 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9193 Lookup.suppressDiagnostics();
9194 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9195 auto *D = Lookup.getRepresentativeDecl();
9196 do {
9197 S = S->getParent();
9198 } while (S && !S->isDeclScope(D));
9199 if (S)
9200 S = S->getParent();
9201 Lookups.push_back(UnresolvedSet<8>());
9202 Lookups.back().append(Lookup.begin(), Lookup.end());
9203 Lookup.clear();
9204 }
9205 } else if (auto *ULE =
9206 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9207 Lookups.push_back(UnresolvedSet<8>());
9208 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009209 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009210 if (D == PrevD)
9211 Lookups.push_back(UnresolvedSet<8>());
9212 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9213 Lookups.back().addDecl(DRD);
9214 PrevD = D;
9215 }
9216 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009217 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9218 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009219 Ty->containsUnexpandedParameterPack() ||
9220 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9221 return !D->isInvalidDecl() &&
9222 (D->getType()->isDependentType() ||
9223 D->getType()->isInstantiationDependentType() ||
9224 D->getType()->containsUnexpandedParameterPack());
9225 })) {
9226 UnresolvedSet<8> ResSet;
9227 for (auto &Set : Lookups) {
9228 ResSet.append(Set.begin(), Set.end());
9229 // The last item marks the end of all declarations at the specified scope.
9230 ResSet.addDecl(Set[Set.size() - 1]);
9231 }
9232 return UnresolvedLookupExpr::Create(
9233 SemaRef.Context, /*NamingClass=*/nullptr,
9234 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9235 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9236 }
9237 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9238 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9239 if (!D->isInvalidDecl() &&
9240 SemaRef.Context.hasSameType(D->getType(), Ty))
9241 return D;
9242 return nullptr;
9243 }))
9244 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9245 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9246 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9247 if (!D->isInvalidDecl() &&
9248 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9249 !Ty.isMoreQualifiedThan(D->getType()))
9250 return D;
9251 return nullptr;
9252 })) {
9253 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9254 /*DetectVirtual=*/false);
9255 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9256 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9257 VD->getType().getUnqualifiedType()))) {
9258 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9259 /*DiagID=*/0) !=
9260 Sema::AR_inaccessible) {
9261 SemaRef.BuildBasePathArray(Paths, BasePath);
9262 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9263 }
9264 }
9265 }
9266 }
9267 if (ReductionIdScopeSpec.isSet()) {
9268 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9269 return ExprError();
9270 }
9271 return ExprEmpty();
9272}
9273
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009274namespace {
9275/// Data for the reduction-based clauses.
9276struct ReductionData {
9277 /// List of original reduction items.
9278 SmallVector<Expr *, 8> Vars;
9279 /// List of private copies of the reduction items.
9280 SmallVector<Expr *, 8> Privates;
9281 /// LHS expressions for the reduction_op expressions.
9282 SmallVector<Expr *, 8> LHSs;
9283 /// RHS expressions for the reduction_op expressions.
9284 SmallVector<Expr *, 8> RHSs;
9285 /// Reduction operation expression.
9286 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009287 /// Taskgroup descriptors for the corresponding reduction items in
9288 /// in_reduction clauses.
9289 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009290 /// List of captures for clause.
9291 SmallVector<Decl *, 4> ExprCaptures;
9292 /// List of postupdate expressions.
9293 SmallVector<Expr *, 4> ExprPostUpdates;
9294 ReductionData() = delete;
9295 /// Reserves required memory for the reduction data.
9296 ReductionData(unsigned Size) {
9297 Vars.reserve(Size);
9298 Privates.reserve(Size);
9299 LHSs.reserve(Size);
9300 RHSs.reserve(Size);
9301 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009302 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009303 ExprCaptures.reserve(Size);
9304 ExprPostUpdates.reserve(Size);
9305 }
9306 /// Stores reduction item and reduction operation only (required for dependent
9307 /// reduction item).
9308 void push(Expr *Item, Expr *ReductionOp) {
9309 Vars.emplace_back(Item);
9310 Privates.emplace_back(nullptr);
9311 LHSs.emplace_back(nullptr);
9312 RHSs.emplace_back(nullptr);
9313 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009314 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009315 }
9316 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009317 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9318 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009319 Vars.emplace_back(Item);
9320 Privates.emplace_back(Private);
9321 LHSs.emplace_back(LHS);
9322 RHSs.emplace_back(RHS);
9323 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009324 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009325 }
9326};
9327} // namespace
9328
9329static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009330 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9331 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9332 SourceLocation ColonLoc, SourceLocation EndLoc,
9333 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009334 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009335 auto DN = ReductionId.getName();
9336 auto OOK = DN.getCXXOverloadedOperator();
9337 BinaryOperatorKind BOK = BO_Comma;
9338
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009339 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009340 // OpenMP [2.14.3.6, reduction clause]
9341 // C
9342 // reduction-identifier is either an identifier or one of the following
9343 // operators: +, -, *, &, |, ^, && and ||
9344 // C++
9345 // reduction-identifier is either an id-expression or one of the following
9346 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009347 switch (OOK) {
9348 case OO_Plus:
9349 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009350 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009351 break;
9352 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009353 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009354 break;
9355 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009356 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009357 break;
9358 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009359 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009360 break;
9361 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009362 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009363 break;
9364 case OO_AmpAmp:
9365 BOK = BO_LAnd;
9366 break;
9367 case OO_PipePipe:
9368 BOK = BO_LOr;
9369 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009370 case OO_New:
9371 case OO_Delete:
9372 case OO_Array_New:
9373 case OO_Array_Delete:
9374 case OO_Slash:
9375 case OO_Percent:
9376 case OO_Tilde:
9377 case OO_Exclaim:
9378 case OO_Equal:
9379 case OO_Less:
9380 case OO_Greater:
9381 case OO_LessEqual:
9382 case OO_GreaterEqual:
9383 case OO_PlusEqual:
9384 case OO_MinusEqual:
9385 case OO_StarEqual:
9386 case OO_SlashEqual:
9387 case OO_PercentEqual:
9388 case OO_CaretEqual:
9389 case OO_AmpEqual:
9390 case OO_PipeEqual:
9391 case OO_LessLess:
9392 case OO_GreaterGreater:
9393 case OO_LessLessEqual:
9394 case OO_GreaterGreaterEqual:
9395 case OO_EqualEqual:
9396 case OO_ExclaimEqual:
9397 case OO_PlusPlus:
9398 case OO_MinusMinus:
9399 case OO_Comma:
9400 case OO_ArrowStar:
9401 case OO_Arrow:
9402 case OO_Call:
9403 case OO_Subscript:
9404 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009405 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009406 case NUM_OVERLOADED_OPERATORS:
9407 llvm_unreachable("Unexpected reduction identifier");
9408 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009409 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009410 if (II->isStr("max"))
9411 BOK = BO_GT;
9412 else if (II->isStr("min"))
9413 BOK = BO_LT;
9414 }
9415 break;
9416 }
9417 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009418 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009419 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009420 else
9421 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009422 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009423
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009424 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9425 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009426 for (auto RefExpr : VarList) {
9427 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009428 // OpenMP [2.1, C/C++]
9429 // A list item is a variable or array section, subject to the restrictions
9430 // specified in Section 2.4 on page 42 and in each of the sections
9431 // describing clauses and directives for which a list appears.
9432 // OpenMP [2.14.3.3, Restrictions, p.1]
9433 // A variable that is part of another variable (as an array or
9434 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009435 if (!FirstIter && IR != ER)
9436 ++IR;
9437 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009438 SourceLocation ELoc;
9439 SourceRange ERange;
9440 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009441 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009442 /*AllowArraySection=*/true);
9443 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009444 // Try to find 'declare reduction' corresponding construct before using
9445 // builtin/overloaded operators.
9446 QualType Type = Context.DependentTy;
9447 CXXCastPath BasePath;
9448 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009449 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009450 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009451 Expr *ReductionOp = nullptr;
9452 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009453 (DeclareReductionRef.isUnset() ||
9454 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009455 ReductionOp = DeclareReductionRef.get();
9456 // It will be analyzed later.
9457 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009458 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009459 ValueDecl *D = Res.first;
9460 if (!D)
9461 continue;
9462
Alexey Bataev88202be2017-07-27 13:20:36 +00009463 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009464 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009465 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9466 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9467 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009468 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009469 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009470 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9471 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9472 Type = ATy->getElementType();
9473 else
9474 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009475 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009476 } else
9477 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9478 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009479
Alexey Bataevc5e02582014-06-16 07:08:35 +00009480 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9481 // A variable that appears in a private clause must not have an incomplete
9482 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009483 if (S.RequireCompleteType(ELoc, Type,
9484 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009485 continue;
9486 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009487 // A list item that appears in a reduction clause must not be
9488 // const-qualified.
9489 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009490 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009491 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009492 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9493 VarDecl::DeclarationOnly;
9494 S.Diag(D->getLocation(),
9495 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009496 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009497 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009498 continue;
9499 }
9500 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9501 // If a list-item is a reference type then it must bind to the same object
9502 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009503 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009504 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009505 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009506 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009507 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009508 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9509 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009510 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009511 continue;
9512 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009513 }
9514 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009515
Alexey Bataevc5e02582014-06-16 07:08:35 +00009516 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9517 // in a Construct]
9518 // Variables with the predetermined data-sharing attributes may not be
9519 // listed in data-sharing attributes clauses, except for the cases
9520 // listed below. For these exceptions only, listing a predetermined
9521 // variable in a data-sharing attribute clause is allowed and overrides
9522 // the variable's predetermined data-sharing attributes.
9523 // OpenMP [2.14.3.6, Restrictions, p.3]
9524 // Any number of reduction clauses can be specified on the directive,
9525 // but a list item can appear only once in the reduction clauses for that
9526 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009527 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009528 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009529 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009530 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009531 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009532 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009533 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009534 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009535 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009536 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009537 << getOpenMPClauseName(DVar.CKind)
9538 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009539 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009540 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009541 }
9542
9543 // OpenMP [2.14.3.6, Restrictions, p.1]
9544 // A list item that appears in a reduction clause of a worksharing
9545 // construct must be shared in the parallel regions to which any of the
9546 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009547 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009548 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009549 !isOpenMPParallelDirective(CurrDir) &&
9550 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009551 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009552 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009553 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009554 << getOpenMPClauseName(OMPC_reduction)
9555 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009556 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009557 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009558 }
9559 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009560
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009561 // Try to find 'declare reduction' corresponding construct before using
9562 // builtin/overloaded operators.
9563 CXXCastPath BasePath;
9564 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009565 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009566 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9567 if (DeclareReductionRef.isInvalid())
9568 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009569 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009570 (DeclareReductionRef.isUnset() ||
9571 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009572 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009573 continue;
9574 }
9575 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9576 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009577 S.Diag(ReductionId.getLocStart(),
9578 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009579 << Type << ReductionIdRange;
9580 continue;
9581 }
9582
9583 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9584 // The type of a list item that appears in a reduction clause must be valid
9585 // for the reduction-identifier. For a max or min reduction in C, the type
9586 // of the list item must be an allowed arithmetic data type: char, int,
9587 // float, double, or _Bool, possibly modified with long, short, signed, or
9588 // unsigned. For a max or min reduction in C++, the type of the list item
9589 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9590 // double, or bool, possibly modified with long, short, signed, or unsigned.
9591 if (DeclareReductionRef.isUnset()) {
9592 if ((BOK == BO_GT || BOK == BO_LT) &&
9593 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009594 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9595 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009596 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009597 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009598 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9599 VarDecl::DeclarationOnly;
9600 S.Diag(D->getLocation(),
9601 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009602 << D;
9603 }
9604 continue;
9605 }
9606 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009607 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009608 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9609 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009610 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009611 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9612 VarDecl::DeclarationOnly;
9613 S.Diag(D->getLocation(),
9614 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009615 << D;
9616 }
9617 continue;
9618 }
9619 }
9620
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009621 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009622 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009623 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009624 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009625 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009626 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009627 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009628 (!ASE &&
9629 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009630 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009631 // Create pseudo array type for private copy. The size for this array will
9632 // be generated during codegen.
9633 // For array subscripts or single variables Private Ty is the same as Type
9634 // (type of the variable or single array element).
9635 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009636 Type,
9637 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(),
9638 VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009639 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009640 } else if (!ASE && !OASE &&
9641 Context.getAsArrayType(D->getType().getNonReferenceType()))
9642 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009643 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009644 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009645 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009646 // Add initializer for private variable.
9647 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009648 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9649 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009650 if (DeclareReductionRef.isUsable()) {
9651 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9652 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9653 if (DRD->getInitializer()) {
9654 Init = DRDRef;
9655 RHSVD->setInit(DRDRef);
9656 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009657 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009658 } else {
9659 switch (BOK) {
9660 case BO_Add:
9661 case BO_Xor:
9662 case BO_Or:
9663 case BO_LOr:
9664 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9665 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009666 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009667 break;
9668 case BO_Mul:
9669 case BO_LAnd:
9670 if (Type->isScalarType() || Type->isAnyComplexType()) {
9671 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009672 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009673 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009674 break;
9675 case BO_And: {
9676 // '&' reduction op - initializer is '~0'.
9677 QualType OrigType = Type;
9678 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9679 Type = ComplexTy->getElementType();
9680 if (Type->isRealFloatingType()) {
9681 llvm::APFloat InitValue =
9682 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9683 /*isIEEE=*/true);
9684 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9685 Type, ELoc);
9686 } else if (Type->isScalarType()) {
9687 auto Size = Context.getTypeSize(Type);
9688 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9689 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9690 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9691 }
9692 if (Init && OrigType->isAnyComplexType()) {
9693 // Init = 0xFFFF + 0xFFFFi;
9694 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009695 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009696 }
9697 Type = OrigType;
9698 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009699 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009700 case BO_LT:
9701 case BO_GT: {
9702 // 'min' reduction op - initializer is 'Largest representable number in
9703 // the reduction list item type'.
9704 // 'max' reduction op - initializer is 'Least representable number in
9705 // the reduction list item type'.
9706 if (Type->isIntegerType() || Type->isPointerType()) {
9707 bool IsSigned = Type->hasSignedIntegerRepresentation();
9708 auto Size = Context.getTypeSize(Type);
9709 QualType IntTy =
9710 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9711 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009712 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9713 : llvm::APInt::getMinValue(Size)
9714 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9715 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009716 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9717 if (Type->isPointerType()) {
9718 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009719 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009720 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9721 SourceLocation(), Init);
9722 if (CastExpr.isInvalid())
9723 continue;
9724 Init = CastExpr.get();
9725 }
9726 } else if (Type->isRealFloatingType()) {
9727 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9728 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9729 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9730 Type, ELoc);
9731 }
9732 break;
9733 }
9734 case BO_PtrMemD:
9735 case BO_PtrMemI:
9736 case BO_MulAssign:
9737 case BO_Div:
9738 case BO_Rem:
9739 case BO_Sub:
9740 case BO_Shl:
9741 case BO_Shr:
9742 case BO_LE:
9743 case BO_GE:
9744 case BO_EQ:
9745 case BO_NE:
9746 case BO_AndAssign:
9747 case BO_XorAssign:
9748 case BO_OrAssign:
9749 case BO_Assign:
9750 case BO_AddAssign:
9751 case BO_SubAssign:
9752 case BO_DivAssign:
9753 case BO_RemAssign:
9754 case BO_ShlAssign:
9755 case BO_ShrAssign:
9756 case BO_Comma:
9757 llvm_unreachable("Unexpected reduction operation");
9758 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009759 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009760 if (Init && DeclareReductionRef.isUnset())
9761 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9762 else if (!Init)
9763 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009764 if (RHSVD->isInvalidDecl())
9765 continue;
9766 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009767 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9768 << Type << ReductionIdRange;
9769 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9770 VarDecl::DeclarationOnly;
9771 S.Diag(D->getLocation(),
9772 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009773 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009774 continue;
9775 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009776 // Store initializer for single element in private copy. Will be used during
9777 // codegen.
9778 PrivateVD->setInit(RHSVD->getInit());
9779 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009780 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009781 ExprResult ReductionOp;
9782 if (DeclareReductionRef.isUsable()) {
9783 QualType RedTy = DeclareReductionRef.get()->getType();
9784 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009785 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9786 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009787 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009788 LHS = S.DefaultLvalueConversion(LHS.get());
9789 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009790 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9791 CK_UncheckedDerivedToBase, LHS.get(),
9792 &BasePath, LHS.get()->getValueKind());
9793 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9794 CK_UncheckedDerivedToBase, RHS.get(),
9795 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009796 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009797 FunctionProtoType::ExtProtoInfo EPI;
9798 QualType Params[] = {PtrRedTy, PtrRedTy};
9799 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9800 auto *OVE = new (Context) OpaqueValueExpr(
9801 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009802 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009803 Expr *Args[] = {LHS.get(), RHS.get()};
9804 ReductionOp = new (Context)
9805 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9806 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009807 ReductionOp = S.BuildBinOp(
9808 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009809 if (ReductionOp.isUsable()) {
9810 if (BOK != BO_LT && BOK != BO_GT) {
9811 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009812 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9813 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009814 } else {
9815 auto *ConditionalOp = new (Context) ConditionalOperator(
9816 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9817 RHSDRE, Type, VK_LValue, OK_Ordinary);
9818 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009819 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9820 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009821 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009822 if (ReductionOp.isUsable())
9823 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009824 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009825 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009826 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009827 }
9828
Alexey Bataevfa312f32017-07-21 18:48:21 +00009829 // OpenMP [2.15.4.6, Restrictions, p.2]
9830 // A list item that appears in an in_reduction clause of a task construct
9831 // must appear in a task_reduction clause of a construct associated with a
9832 // taskgroup region that includes the participating task in its taskgroup
9833 // set. The construct associated with the innermost region that meets this
9834 // condition must specify the same reduction-identifier as the in_reduction
9835 // clause.
9836 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00009837 SourceRange ParentSR;
9838 BinaryOperatorKind ParentBOK;
9839 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +00009840 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +00009841 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +00009842 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
9843 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009844 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +00009845 Stack->getTopMostTaskgroupReductionData(
9846 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009847 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
9848 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
9849 if (!IsParentBOK && !IsParentReductionOp) {
9850 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
9851 continue;
9852 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00009853 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
9854 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
9855 IsParentReductionOp) {
9856 bool EmitError = true;
9857 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
9858 llvm::FoldingSetNodeID RedId, ParentRedId;
9859 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
9860 DeclareReductionRef.get()->Profile(RedId, Context,
9861 /*Canonical=*/true);
9862 EmitError = RedId != ParentRedId;
9863 }
9864 if (EmitError) {
9865 S.Diag(ReductionId.getLocStart(),
9866 diag::err_omp_reduction_identifier_mismatch)
9867 << ReductionIdRange << RefExpr->getSourceRange();
9868 S.Diag(ParentSR.getBegin(),
9869 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +00009870 << ParentSR
9871 << (IsParentBOK ? ParentBOKDSA.RefExpr
9872 : ParentReductionOpDSA.RefExpr)
9873 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +00009874 continue;
9875 }
9876 }
Alexey Bataev88202be2017-07-27 13:20:36 +00009877 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
9878 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +00009879 }
9880
Alexey Bataev60da77e2016-02-29 05:54:20 +00009881 DeclRefExpr *Ref = nullptr;
9882 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009883 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009884 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009885 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009886 VarsExpr =
9887 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9888 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009889 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009890 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009891 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009892 if (!S.IsOpenMPCapturedDecl(D)) {
9893 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009894 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009895 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009896 if (!RefRes.isUsable())
9897 continue;
9898 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009899 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9900 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009901 if (!PostUpdateRes.isUsable())
9902 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009903 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
9904 Stack->getCurrentDirective() == OMPD_taskgroup) {
9905 S.Diag(RefExpr->getExprLoc(),
9906 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009907 << RefExpr->getSourceRange();
9908 continue;
9909 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009910 RD.ExprPostUpdates.emplace_back(
9911 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009912 }
9913 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009914 }
Alexey Bataev169d96a2017-07-18 20:17:46 +00009915 // All reduction items are still marked as reduction (to do not increase
9916 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009917 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009918 if (CurrDir == OMPD_taskgroup) {
9919 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +00009920 Stack->addTaskgroupReductionData(D, ReductionIdRange,
9921 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +00009922 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +00009923 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009924 }
Alexey Bataev88202be2017-07-27 13:20:36 +00009925 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
9926 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009927 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009928 return RD.Vars.empty();
9929}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009930
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009931OMPClause *Sema::ActOnOpenMPReductionClause(
9932 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9933 SourceLocation ColonLoc, SourceLocation EndLoc,
9934 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9935 ArrayRef<Expr *> UnresolvedReductions) {
9936 ReductionData RD(VarList.size());
9937
Alexey Bataev169d96a2017-07-18 20:17:46 +00009938 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
9939 StartLoc, LParenLoc, ColonLoc, EndLoc,
9940 ReductionIdScopeSpec, ReductionId,
9941 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009942 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009943
Alexey Bataevc5e02582014-06-16 07:08:35 +00009944 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009945 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9946 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9947 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9948 buildPreInits(Context, RD.ExprCaptures),
9949 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009950}
9951
Alexey Bataev169d96a2017-07-18 20:17:46 +00009952OMPClause *Sema::ActOnOpenMPTaskReductionClause(
9953 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9954 SourceLocation ColonLoc, SourceLocation EndLoc,
9955 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9956 ArrayRef<Expr *> UnresolvedReductions) {
9957 ReductionData RD(VarList.size());
9958
9959 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
9960 VarList, StartLoc, LParenLoc, ColonLoc,
9961 EndLoc, ReductionIdScopeSpec, ReductionId,
9962 UnresolvedReductions, RD))
9963 return nullptr;
9964
9965 return OMPTaskReductionClause::Create(
9966 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9967 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9968 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9969 buildPreInits(Context, RD.ExprCaptures),
9970 buildPostUpdate(*this, RD.ExprPostUpdates));
9971}
9972
Alexey Bataevfa312f32017-07-21 18:48:21 +00009973OMPClause *Sema::ActOnOpenMPInReductionClause(
9974 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9975 SourceLocation ColonLoc, SourceLocation EndLoc,
9976 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9977 ArrayRef<Expr *> UnresolvedReductions) {
9978 ReductionData RD(VarList.size());
9979
9980 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
9981 StartLoc, LParenLoc, ColonLoc, EndLoc,
9982 ReductionIdScopeSpec, ReductionId,
9983 UnresolvedReductions, RD))
9984 return nullptr;
9985
9986 return OMPInReductionClause::Create(
9987 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9988 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +00009989 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +00009990 buildPreInits(Context, RD.ExprCaptures),
9991 buildPostUpdate(*this, RD.ExprPostUpdates));
9992}
9993
Alexey Bataevecba70f2016-04-12 11:02:11 +00009994bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9995 SourceLocation LinLoc) {
9996 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9997 LinKind == OMPC_LINEAR_unknown) {
9998 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9999 return true;
10000 }
10001 return false;
10002}
10003
10004bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10005 OpenMPLinearClauseKind LinKind,
10006 QualType Type) {
10007 auto *VD = dyn_cast_or_null<VarDecl>(D);
10008 // A variable must not have an incomplete type or a reference type.
10009 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10010 return true;
10011 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10012 !Type->isReferenceType()) {
10013 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10014 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10015 return true;
10016 }
10017 Type = Type.getNonReferenceType();
10018
10019 // A list item must not be const-qualified.
10020 if (Type.isConstant(Context)) {
10021 Diag(ELoc, diag::err_omp_const_variable)
10022 << getOpenMPClauseName(OMPC_linear);
10023 if (D) {
10024 bool IsDecl =
10025 !VD ||
10026 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10027 Diag(D->getLocation(),
10028 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10029 << D;
10030 }
10031 return true;
10032 }
10033
10034 // A list item must be of integral or pointer type.
10035 Type = Type.getUnqualifiedType().getCanonicalType();
10036 const auto *Ty = Type.getTypePtrOrNull();
10037 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10038 !Ty->isPointerType())) {
10039 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10040 if (D) {
10041 bool IsDecl =
10042 !VD ||
10043 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10044 Diag(D->getLocation(),
10045 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10046 << D;
10047 }
10048 return true;
10049 }
10050 return false;
10051}
10052
Alexey Bataev182227b2015-08-20 10:54:39 +000010053OMPClause *Sema::ActOnOpenMPLinearClause(
10054 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10055 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10056 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010057 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010058 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010059 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010060 SmallVector<Decl *, 4> ExprCaptures;
10061 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010062 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010063 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010064 for (auto &RefExpr : VarList) {
10065 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010066 SourceLocation ELoc;
10067 SourceRange ERange;
10068 Expr *SimpleRefExpr = RefExpr;
10069 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10070 /*AllowArraySection=*/false);
10071 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010072 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010073 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010074 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010075 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010076 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010077 ValueDecl *D = Res.first;
10078 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010079 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010080
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010081 QualType Type = D->getType();
10082 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010083
10084 // OpenMP [2.14.3.7, linear clause]
10085 // A list-item cannot appear in more than one linear clause.
10086 // A list-item that appears in a linear clause cannot appear in any
10087 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010088 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010089 if (DVar.RefExpr) {
10090 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10091 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010092 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010093 continue;
10094 }
10095
Alexey Bataevecba70f2016-04-12 11:02:11 +000010096 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010097 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010098 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010099
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010100 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010101 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10102 D->hasAttrs() ? &D->getAttrs() : nullptr);
10103 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010104 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010105 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010106 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010107 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010108 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010109 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10110 if (!IsOpenMPCapturedDecl(D)) {
10111 ExprCaptures.push_back(Ref->getDecl());
10112 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10113 ExprResult RefRes = DefaultLvalueConversion(Ref);
10114 if (!RefRes.isUsable())
10115 continue;
10116 ExprResult PostUpdateRes =
10117 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10118 SimpleRefExpr, RefRes.get());
10119 if (!PostUpdateRes.isUsable())
10120 continue;
10121 ExprPostUpdates.push_back(
10122 IgnoredValueConversions(PostUpdateRes.get()).get());
10123 }
10124 }
10125 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010126 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010127 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010128 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010129 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010130 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010131 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010132 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10133
10134 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010135 Vars.push_back((VD || CurContext->isDependentContext())
10136 ? RefExpr->IgnoreParens()
10137 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010138 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010139 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010140 }
10141
10142 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010143 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010144
10145 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010146 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010147 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10148 !Step->isInstantiationDependent() &&
10149 !Step->containsUnexpandedParameterPack()) {
10150 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010151 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010152 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010153 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010154 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010155
Alexander Musman3276a272015-03-21 10:12:56 +000010156 // Build var to save the step value.
10157 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010158 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010159 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010160 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010161 ExprResult CalcStep =
10162 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010163 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010164
Alexander Musman8dba6642014-04-22 13:09:42 +000010165 // Warn about zero linear step (it would be probably better specified as
10166 // making corresponding variables 'const').
10167 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010168 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10169 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010170 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10171 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010172 if (!IsConstant && CalcStep.isUsable()) {
10173 // Calculate the step beforehand instead of doing this on each iteration.
10174 // (This is not used if the number of iterations may be kfold-ed).
10175 CalcStepExpr = CalcStep.get();
10176 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010177 }
10178
Alexey Bataev182227b2015-08-20 10:54:39 +000010179 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10180 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010181 StepExpr, CalcStepExpr,
10182 buildPreInits(Context, ExprCaptures),
10183 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010184}
10185
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010186static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10187 Expr *NumIterations, Sema &SemaRef,
10188 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010189 // Walk the vars and build update/final expressions for the CodeGen.
10190 SmallVector<Expr *, 8> Updates;
10191 SmallVector<Expr *, 8> Finals;
10192 Expr *Step = Clause.getStep();
10193 Expr *CalcStep = Clause.getCalcStep();
10194 // OpenMP [2.14.3.7, linear clause]
10195 // If linear-step is not specified it is assumed to be 1.
10196 if (Step == nullptr)
10197 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010198 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010199 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010200 }
Alexander Musman3276a272015-03-21 10:12:56 +000010201 bool HasErrors = false;
10202 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010203 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010204 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010205 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010206 SourceLocation ELoc;
10207 SourceRange ERange;
10208 Expr *SimpleRefExpr = RefExpr;
10209 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10210 /*AllowArraySection=*/false);
10211 ValueDecl *D = Res.first;
10212 if (Res.second || !D) {
10213 Updates.push_back(nullptr);
10214 Finals.push_back(nullptr);
10215 HasErrors = true;
10216 continue;
10217 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010218 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010219 Expr *InitExpr = *CurInit;
10220
10221 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010222 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010223 Expr *CapturedRef;
10224 if (LinKind == OMPC_LINEAR_uval)
10225 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10226 else
10227 CapturedRef =
10228 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10229 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10230 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010231
10232 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010233 ExprResult Update;
10234 if (!Info.first) {
10235 Update =
10236 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10237 InitExpr, IV, Step, /* Subtract */ false);
10238 } else
10239 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010240 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10241 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010242
10243 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010244 ExprResult Final;
10245 if (!Info.first) {
10246 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10247 InitExpr, NumIterations, Step,
10248 /* Subtract */ false);
10249 } else
10250 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010251 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10252 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010253
Alexander Musman3276a272015-03-21 10:12:56 +000010254 if (!Update.isUsable() || !Final.isUsable()) {
10255 Updates.push_back(nullptr);
10256 Finals.push_back(nullptr);
10257 HasErrors = true;
10258 } else {
10259 Updates.push_back(Update.get());
10260 Finals.push_back(Final.get());
10261 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010262 ++CurInit;
10263 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010264 }
10265 Clause.setUpdates(Updates);
10266 Clause.setFinals(Finals);
10267 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010268}
10269
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010270OMPClause *Sema::ActOnOpenMPAlignedClause(
10271 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10272 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10273
10274 SmallVector<Expr *, 8> Vars;
10275 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010276 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10277 SourceLocation ELoc;
10278 SourceRange ERange;
10279 Expr *SimpleRefExpr = RefExpr;
10280 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10281 /*AllowArraySection=*/false);
10282 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010283 // It will be analyzed later.
10284 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010285 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010286 ValueDecl *D = Res.first;
10287 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010288 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010289
Alexey Bataev1efd1662016-03-29 10:59:56 +000010290 QualType QType = D->getType();
10291 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010292
10293 // OpenMP [2.8.1, simd construct, Restrictions]
10294 // The type of list items appearing in the aligned clause must be
10295 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010296 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010297 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010298 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010299 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010300 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010301 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010302 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010303 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010304 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010305 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010306 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010307 continue;
10308 }
10309
10310 // OpenMP [2.8.1, simd construct, Restrictions]
10311 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010312 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010313 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010314 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10315 << getOpenMPClauseName(OMPC_aligned);
10316 continue;
10317 }
10318
Alexey Bataev1efd1662016-03-29 10:59:56 +000010319 DeclRefExpr *Ref = nullptr;
10320 if (!VD && IsOpenMPCapturedDecl(D))
10321 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10322 Vars.push_back(DefaultFunctionArrayConversion(
10323 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10324 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010325 }
10326
10327 // OpenMP [2.8.1, simd construct, Description]
10328 // The parameter of the aligned clause, alignment, must be a constant
10329 // positive integer expression.
10330 // If no optional parameter is specified, implementation-defined default
10331 // alignments for SIMD instructions on the target platforms are assumed.
10332 if (Alignment != nullptr) {
10333 ExprResult AlignResult =
10334 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10335 if (AlignResult.isInvalid())
10336 return nullptr;
10337 Alignment = AlignResult.get();
10338 }
10339 if (Vars.empty())
10340 return nullptr;
10341
10342 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10343 EndLoc, Vars, Alignment);
10344}
10345
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010346OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10347 SourceLocation StartLoc,
10348 SourceLocation LParenLoc,
10349 SourceLocation EndLoc) {
10350 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010351 SmallVector<Expr *, 8> SrcExprs;
10352 SmallVector<Expr *, 8> DstExprs;
10353 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010354 for (auto &RefExpr : VarList) {
10355 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10356 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010357 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010358 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010359 SrcExprs.push_back(nullptr);
10360 DstExprs.push_back(nullptr);
10361 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010362 continue;
10363 }
10364
Alexey Bataeved09d242014-05-28 05:53:51 +000010365 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010366 // OpenMP [2.1, C/C++]
10367 // A list item is a variable name.
10368 // OpenMP [2.14.4.1, Restrictions, p.1]
10369 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010370 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010371 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010372 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10373 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010374 continue;
10375 }
10376
10377 Decl *D = DE->getDecl();
10378 VarDecl *VD = cast<VarDecl>(D);
10379
10380 QualType Type = VD->getType();
10381 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10382 // It will be analyzed later.
10383 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010384 SrcExprs.push_back(nullptr);
10385 DstExprs.push_back(nullptr);
10386 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010387 continue;
10388 }
10389
10390 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10391 // A list item that appears in a copyin clause must be threadprivate.
10392 if (!DSAStack->isThreadPrivate(VD)) {
10393 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010394 << getOpenMPClauseName(OMPC_copyin)
10395 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010396 continue;
10397 }
10398
10399 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10400 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010401 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010402 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010403 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010404 auto *SrcVD =
10405 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10406 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010407 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010408 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10409 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010410 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10411 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010412 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010413 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010414 // For arrays generate assignment operation for single element and replace
10415 // it by the original array element in CodeGen.
10416 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10417 PseudoDstExpr, PseudoSrcExpr);
10418 if (AssignmentOp.isInvalid())
10419 continue;
10420 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10421 /*DiscardedValue=*/true);
10422 if (AssignmentOp.isInvalid())
10423 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010424
10425 DSAStack->addDSA(VD, DE, OMPC_copyin);
10426 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010427 SrcExprs.push_back(PseudoSrcExpr);
10428 DstExprs.push_back(PseudoDstExpr);
10429 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010430 }
10431
Alexey Bataeved09d242014-05-28 05:53:51 +000010432 if (Vars.empty())
10433 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010434
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010435 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10436 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010437}
10438
Alexey Bataevbae9a792014-06-27 10:37:06 +000010439OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10440 SourceLocation StartLoc,
10441 SourceLocation LParenLoc,
10442 SourceLocation EndLoc) {
10443 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010444 SmallVector<Expr *, 8> SrcExprs;
10445 SmallVector<Expr *, 8> DstExprs;
10446 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010447 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010448 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10449 SourceLocation ELoc;
10450 SourceRange ERange;
10451 Expr *SimpleRefExpr = RefExpr;
10452 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10453 /*AllowArraySection=*/false);
10454 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010455 // It will be analyzed later.
10456 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010457 SrcExprs.push_back(nullptr);
10458 DstExprs.push_back(nullptr);
10459 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010460 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010461 ValueDecl *D = Res.first;
10462 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010463 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010464
Alexey Bataeve122da12016-03-17 10:50:17 +000010465 QualType Type = D->getType();
10466 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010467
10468 // OpenMP [2.14.4.2, Restrictions, p.2]
10469 // A list item that appears in a copyprivate clause may not appear in a
10470 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010471 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10472 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010473 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10474 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010475 Diag(ELoc, diag::err_omp_wrong_dsa)
10476 << getOpenMPClauseName(DVar.CKind)
10477 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010478 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010479 continue;
10480 }
10481
10482 // OpenMP [2.11.4.2, Restrictions, p.1]
10483 // All list items that appear in a copyprivate clause must be either
10484 // threadprivate or private in the enclosing context.
10485 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010486 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010487 if (DVar.CKind == OMPC_shared) {
10488 Diag(ELoc, diag::err_omp_required_access)
10489 << getOpenMPClauseName(OMPC_copyprivate)
10490 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010491 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010492 continue;
10493 }
10494 }
10495 }
10496
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010497 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010498 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010499 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010500 << getOpenMPClauseName(OMPC_copyprivate) << Type
10501 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010502 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010503 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010504 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010505 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010506 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010507 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010508 continue;
10509 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010510
Alexey Bataevbae9a792014-06-27 10:37:06 +000010511 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10512 // A variable of class type (or array thereof) that appears in a
10513 // copyin clause requires an accessible, unambiguous copy assignment
10514 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010515 Type = Context.getBaseElementType(Type.getNonReferenceType())
10516 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010517 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010518 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10519 D->hasAttrs() ? &D->getAttrs() : nullptr);
10520 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010521 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010522 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10523 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010524 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010525 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010526 PseudoDstExpr, PseudoSrcExpr);
10527 if (AssignmentOp.isInvalid())
10528 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010529 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010530 /*DiscardedValue=*/true);
10531 if (AssignmentOp.isInvalid())
10532 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010533
10534 // No need to mark vars as copyprivate, they are already threadprivate or
10535 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010536 assert(VD || IsOpenMPCapturedDecl(D));
10537 Vars.push_back(
10538 VD ? RefExpr->IgnoreParens()
10539 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010540 SrcExprs.push_back(PseudoSrcExpr);
10541 DstExprs.push_back(PseudoDstExpr);
10542 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010543 }
10544
10545 if (Vars.empty())
10546 return nullptr;
10547
Alexey Bataeva63048e2015-03-23 06:18:07 +000010548 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10549 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010550}
10551
Alexey Bataev6125da92014-07-21 11:26:11 +000010552OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10553 SourceLocation StartLoc,
10554 SourceLocation LParenLoc,
10555 SourceLocation EndLoc) {
10556 if (VarList.empty())
10557 return nullptr;
10558
10559 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10560}
Alexey Bataevdea47612014-07-23 07:46:59 +000010561
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010562OMPClause *
10563Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10564 SourceLocation DepLoc, SourceLocation ColonLoc,
10565 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10566 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010567 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010568 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010569 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010570 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010571 return nullptr;
10572 }
10573 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010574 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10575 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010576 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010577 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010578 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10579 /*Last=*/OMPC_DEPEND_unknown, Except)
10580 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010581 return nullptr;
10582 }
10583 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010584 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010585 llvm::APSInt DepCounter(/*BitWidth=*/32);
10586 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10587 if (DepKind == OMPC_DEPEND_sink) {
10588 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10589 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10590 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010591 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010592 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010593 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10594 DSAStack->getParentOrderedRegionParam()) {
10595 for (auto &RefExpr : VarList) {
10596 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010597 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010598 // It will be analyzed later.
10599 Vars.push_back(RefExpr);
10600 continue;
10601 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010602
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010603 SourceLocation ELoc = RefExpr->getExprLoc();
10604 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10605 if (DepKind == OMPC_DEPEND_sink) {
10606 if (DepCounter >= TotalDepCount) {
10607 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10608 continue;
10609 }
10610 ++DepCounter;
10611 // OpenMP [2.13.9, Summary]
10612 // depend(dependence-type : vec), where dependence-type is:
10613 // 'sink' and where vec is the iteration vector, which has the form:
10614 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10615 // where n is the value specified by the ordered clause in the loop
10616 // directive, xi denotes the loop iteration variable of the i-th nested
10617 // loop associated with the loop directive, and di is a constant
10618 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010619 if (CurContext->isDependentContext()) {
10620 // It will be analyzed later.
10621 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010622 continue;
10623 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010624 SimpleExpr = SimpleExpr->IgnoreImplicit();
10625 OverloadedOperatorKind OOK = OO_None;
10626 SourceLocation OOLoc;
10627 Expr *LHS = SimpleExpr;
10628 Expr *RHS = nullptr;
10629 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10630 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10631 OOLoc = BO->getOperatorLoc();
10632 LHS = BO->getLHS()->IgnoreParenImpCasts();
10633 RHS = BO->getRHS()->IgnoreParenImpCasts();
10634 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10635 OOK = OCE->getOperator();
10636 OOLoc = OCE->getOperatorLoc();
10637 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10638 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10639 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10640 OOK = MCE->getMethodDecl()
10641 ->getNameInfo()
10642 .getName()
10643 .getCXXOverloadedOperator();
10644 OOLoc = MCE->getCallee()->getExprLoc();
10645 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10646 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10647 }
10648 SourceLocation ELoc;
10649 SourceRange ERange;
10650 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10651 /*AllowArraySection=*/false);
10652 if (Res.second) {
10653 // It will be analyzed later.
10654 Vars.push_back(RefExpr);
10655 }
10656 ValueDecl *D = Res.first;
10657 if (!D)
10658 continue;
10659
10660 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10661 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10662 continue;
10663 }
10664 if (RHS) {
10665 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10666 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10667 if (RHSRes.isInvalid())
10668 continue;
10669 }
10670 if (!CurContext->isDependentContext() &&
10671 DSAStack->getParentOrderedRegionParam() &&
10672 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000010673 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
10674 DepCounter.getZExtValue());
10675 if (VD) {
10676 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10677 << 1 << VD;
10678 } else {
10679 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
10680 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010681 continue;
10682 }
10683 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010684 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010685 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010686 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010687 (ASE &&
10688 !ASE->getBase()
10689 ->getType()
10690 .getNonReferenceType()
10691 ->isPointerType() &&
10692 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000010693 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10694 << RefExpr->getSourceRange();
10695 continue;
10696 }
10697 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
10698 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
10699 ExprResult Res = CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf,
10700 RefExpr->IgnoreParenImpCasts());
10701 getDiagnostics().setSuppressAllDiagnostics(Suppress);
10702 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
10703 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10704 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010705 continue;
10706 }
10707 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010708 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10709 }
10710
10711 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10712 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000010713 DSAStack->getParentOrderedRegionParam() &&
10714 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
10715 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010716 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10717 }
10718 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10719 Vars.empty())
10720 return nullptr;
10721 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010722 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10723 DepKind, DepLoc, ColonLoc, Vars);
10724 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10725 DSAStack->addDoacrossDependClause(C, OpsOffs);
10726 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010727}
Michael Wonge710d542015-08-07 16:16:36 +000010728
10729OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10730 SourceLocation LParenLoc,
10731 SourceLocation EndLoc) {
10732 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000010733 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000010734
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010735 // OpenMP [2.9.1, Restrictions]
10736 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010737 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10738 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010739 return nullptr;
10740
Alexey Bataev931e19b2017-10-02 16:32:39 +000010741 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10742 if (isOpenMPTargetExecutionDirective(DKind) &&
10743 !CurContext->isDependentContext()) {
10744 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10745 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10746 HelperValStmt = buildPreInits(Context, Captures);
10747 }
10748
10749 return new (Context)
10750 OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000010751}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010752
Kelvin Li0bff7af2015-11-23 05:32:03 +000010753static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10754 DSAStackTy *Stack, QualType QTy) {
10755 NamedDecl *ND;
10756 if (QTy->isIncompleteType(&ND)) {
10757 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10758 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010759 }
10760 return true;
10761}
10762
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010763/// \brief Return true if it can be proven that the provided array expression
10764/// (array section or array subscript) does NOT specify the whole size of the
10765/// array whose base type is \a BaseQTy.
10766static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10767 const Expr *E,
10768 QualType BaseQTy) {
10769 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10770
10771 // If this is an array subscript, it refers to the whole size if the size of
10772 // the dimension is constant and equals 1. Also, an array section assumes the
10773 // format of an array subscript if no colon is used.
10774 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10775 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10776 return ATy->getSize().getSExtValue() != 1;
10777 // Size can't be evaluated statically.
10778 return false;
10779 }
10780
10781 assert(OASE && "Expecting array section if not an array subscript.");
10782 auto *LowerBound = OASE->getLowerBound();
10783 auto *Length = OASE->getLength();
10784
10785 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010786 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010787 if (LowerBound) {
10788 llvm::APSInt ConstLowerBound;
10789 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10790 return false; // Can't get the integer value as a constant.
10791 if (ConstLowerBound.getSExtValue())
10792 return true;
10793 }
10794
10795 // If we don't have a length we covering the whole dimension.
10796 if (!Length)
10797 return false;
10798
10799 // If the base is a pointer, we don't have a way to get the size of the
10800 // pointee.
10801 if (BaseQTy->isPointerType())
10802 return false;
10803
10804 // We can only check if the length is the same as the size of the dimension
10805 // if we have a constant array.
10806 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10807 if (!CATy)
10808 return false;
10809
10810 llvm::APSInt ConstLength;
10811 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10812 return false; // Can't get the integer value as a constant.
10813
10814 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10815}
10816
10817// Return true if it can be proven that the provided array expression (array
10818// section or array subscript) does NOT specify a single element of the array
10819// whose base type is \a BaseQTy.
10820static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010821 const Expr *E,
10822 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010823 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10824
10825 // An array subscript always refer to a single element. Also, an array section
10826 // assumes the format of an array subscript if no colon is used.
10827 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10828 return false;
10829
10830 assert(OASE && "Expecting array section if not an array subscript.");
10831 auto *Length = OASE->getLength();
10832
10833 // If we don't have a length we have to check if the array has unitary size
10834 // for this dimension. Also, we should always expect a length if the base type
10835 // is pointer.
10836 if (!Length) {
10837 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10838 return ATy->getSize().getSExtValue() != 1;
10839 // We cannot assume anything.
10840 return false;
10841 }
10842
10843 // Check if the length evaluates to 1.
10844 llvm::APSInt ConstLength;
10845 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10846 return false; // Can't get the integer value as a constant.
10847
10848 return ConstLength.getSExtValue() != 1;
10849}
10850
Samuel Antao661c0902016-05-26 17:39:58 +000010851// Return the expression of the base of the mappable expression or null if it
10852// cannot be determined and do all the necessary checks to see if the expression
10853// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010854// components of the expression.
10855static Expr *CheckMapClauseExpressionBase(
10856 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010857 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10858 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010859 SourceLocation ELoc = E->getExprLoc();
10860 SourceRange ERange = E->getSourceRange();
10861
10862 // The base of elements of list in a map clause have to be either:
10863 // - a reference to variable or field.
10864 // - a member expression.
10865 // - an array expression.
10866 //
10867 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10868 // reference to 'r'.
10869 //
10870 // If we have:
10871 //
10872 // struct SS {
10873 // Bla S;
10874 // foo() {
10875 // #pragma omp target map (S.Arr[:12]);
10876 // }
10877 // }
10878 //
10879 // We want to retrieve the member expression 'this->S';
10880
10881 Expr *RelevantExpr = nullptr;
10882
Samuel Antao5de996e2016-01-22 20:21:36 +000010883 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10884 // If a list item is an array section, it must specify contiguous storage.
10885 //
10886 // For this restriction it is sufficient that we make sure only references
10887 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010888 // exist except in the rightmost expression (unless they cover the whole
10889 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010890 //
10891 // r.ArrS[3:5].Arr[6:7]
10892 //
10893 // r.ArrS[3:5].x
10894 //
10895 // but these would be valid:
10896 // r.ArrS[3].Arr[6:7]
10897 //
10898 // r.ArrS[3].x
10899
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010900 bool AllowUnitySizeArraySection = true;
10901 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010902
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010903 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010904 E = E->IgnoreParenImpCasts();
10905
10906 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10907 if (!isa<VarDecl>(CurE->getDecl()))
10908 break;
10909
10910 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010911
10912 // If we got a reference to a declaration, we should not expect any array
10913 // section before that.
10914 AllowUnitySizeArraySection = false;
10915 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010916
10917 // Record the component.
10918 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10919 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010920 continue;
10921 }
10922
10923 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10924 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10925
10926 if (isa<CXXThisExpr>(BaseE))
10927 // We found a base expression: this->Val.
10928 RelevantExpr = CurE;
10929 else
10930 E = BaseE;
10931
10932 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10933 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10934 << CurE->getSourceRange();
10935 break;
10936 }
10937
10938 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10939
10940 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10941 // A bit-field cannot appear in a map clause.
10942 //
10943 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010944 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10945 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010946 break;
10947 }
10948
10949 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10950 // If the type of a list item is a reference to a type T then the type
10951 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010952 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010953
10954 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10955 // A list item cannot be a variable that is a member of a structure with
10956 // a union type.
10957 //
10958 if (auto *RT = CurType->getAs<RecordType>())
10959 if (RT->isUnionType()) {
10960 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10961 << CurE->getSourceRange();
10962 break;
10963 }
10964
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010965 // If we got a member expression, we should not expect any array section
10966 // before that:
10967 //
10968 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10969 // If a list item is an element of a structure, only the rightmost symbol
10970 // of the variable reference can be an array section.
10971 //
10972 AllowUnitySizeArraySection = false;
10973 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010974
10975 // Record the component.
10976 CurComponents.push_back(
10977 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010978 continue;
10979 }
10980
10981 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10982 E = CurE->getBase()->IgnoreParenImpCasts();
10983
10984 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10985 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10986 << 0 << CurE->getSourceRange();
10987 break;
10988 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010989
10990 // If we got an array subscript that express the whole dimension we
10991 // can have any array expressions before. If it only expressing part of
10992 // the dimension, we can only have unitary-size array expressions.
10993 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10994 E->getType()))
10995 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010996
10997 // Record the component - we don't have any declaration associated.
10998 CurComponents.push_back(
10999 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011000 continue;
11001 }
11002
11003 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011004 E = CurE->getBase()->IgnoreParenImpCasts();
11005
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011006 auto CurType =
11007 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11008
Samuel Antao5de996e2016-01-22 20:21:36 +000011009 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11010 // If the type of a list item is a reference to a type T then the type
11011 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011012 if (CurType->isReferenceType())
11013 CurType = CurType->getPointeeType();
11014
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011015 bool IsPointer = CurType->isAnyPointerType();
11016
11017 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011018 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11019 << 0 << CurE->getSourceRange();
11020 break;
11021 }
11022
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011023 bool NotWhole =
11024 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11025 bool NotUnity =
11026 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11027
Samuel Antaodab51bb2016-07-18 23:22:11 +000011028 if (AllowWholeSizeArraySection) {
11029 // Any array section is currently allowed. Allowing a whole size array
11030 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011031 //
11032 // If this array section refers to the whole dimension we can still
11033 // accept other array sections before this one, except if the base is a
11034 // pointer. Otherwise, only unitary sections are accepted.
11035 if (NotWhole || IsPointer)
11036 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011037 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011038 // A unity or whole array section is not allowed and that is not
11039 // compatible with the properties of the current array section.
11040 SemaRef.Diag(
11041 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11042 << CurE->getSourceRange();
11043 break;
11044 }
Samuel Antao90927002016-04-26 14:54:23 +000011045
11046 // Record the component - we don't have any declaration associated.
11047 CurComponents.push_back(
11048 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000011049 continue;
11050 }
11051
11052 // If nothing else worked, this is not a valid map clause expression.
11053 SemaRef.Diag(ELoc,
11054 diag::err_omp_expected_named_var_member_or_array_expression)
11055 << ERange;
11056 break;
11057 }
11058
11059 return RelevantExpr;
11060}
11061
11062// Return true if expression E associated with value VD has conflicts with other
11063// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011064static bool CheckMapConflicts(
11065 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11066 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011067 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11068 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011069 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011070 SourceLocation ELoc = E->getExprLoc();
11071 SourceRange ERange = E->getSourceRange();
11072
11073 // In order to easily check the conflicts we need to match each component of
11074 // the expression under test with the components of the expressions that are
11075 // already in the stack.
11076
Samuel Antao5de996e2016-01-22 20:21:36 +000011077 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011078 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011079 "Map clause expression with unexpected base!");
11080
11081 // Variables to help detecting enclosing problems in data environment nests.
11082 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011083 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011084
Samuel Antao90927002016-04-26 14:54:23 +000011085 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11086 VD, CurrentRegionOnly,
11087 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011088 StackComponents,
11089 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011090
Samuel Antao5de996e2016-01-22 20:21:36 +000011091 assert(!StackComponents.empty() &&
11092 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011093 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011094 "Map clause expression with unexpected base!");
11095
Samuel Antao90927002016-04-26 14:54:23 +000011096 // The whole expression in the stack.
11097 auto *RE = StackComponents.front().getAssociatedExpression();
11098
Samuel Antao5de996e2016-01-22 20:21:36 +000011099 // Expressions must start from the same base. Here we detect at which
11100 // point both expressions diverge from each other and see if we can
11101 // detect if the memory referred to both expressions is contiguous and
11102 // do not overlap.
11103 auto CI = CurComponents.rbegin();
11104 auto CE = CurComponents.rend();
11105 auto SI = StackComponents.rbegin();
11106 auto SE = StackComponents.rend();
11107 for (; CI != CE && SI != SE; ++CI, ++SI) {
11108
11109 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11110 // At most one list item can be an array item derived from a given
11111 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011112 if (CurrentRegionOnly &&
11113 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11114 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11115 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11116 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11117 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011118 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011119 << CI->getAssociatedExpression()->getSourceRange();
11120 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11121 diag::note_used_here)
11122 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011123 return true;
11124 }
11125
11126 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011127 if (CI->getAssociatedExpression()->getStmtClass() !=
11128 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011129 break;
11130
11131 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011132 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011133 break;
11134 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011135 // Check if the extra components of the expressions in the enclosing
11136 // data environment are redundant for the current base declaration.
11137 // If they are, the maps completely overlap, which is legal.
11138 for (; SI != SE; ++SI) {
11139 QualType Type;
11140 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011141 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011142 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011143 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11144 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011145 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11146 Type =
11147 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11148 }
11149 if (Type.isNull() || Type->isAnyPointerType() ||
11150 CheckArrayExpressionDoesNotReferToWholeSize(
11151 SemaRef, SI->getAssociatedExpression(), Type))
11152 break;
11153 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011154
11155 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11156 // List items of map clauses in the same construct must not share
11157 // original storage.
11158 //
11159 // If the expressions are exactly the same or one is a subset of the
11160 // other, it means they are sharing storage.
11161 if (CI == CE && SI == SE) {
11162 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011163 if (CKind == OMPC_map)
11164 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11165 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011166 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011167 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11168 << ERange;
11169 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011170 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11171 << RE->getSourceRange();
11172 return true;
11173 } else {
11174 // If we find the same expression in the enclosing data environment,
11175 // that is legal.
11176 IsEnclosedByDataEnvironmentExpr = true;
11177 return false;
11178 }
11179 }
11180
Samuel Antao90927002016-04-26 14:54:23 +000011181 QualType DerivedType =
11182 std::prev(CI)->getAssociatedDeclaration()->getType();
11183 SourceLocation DerivedLoc =
11184 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011185
11186 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11187 // If the type of a list item is a reference to a type T then the type
11188 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011189 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011190
11191 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11192 // A variable for which the type is pointer and an array section
11193 // derived from that variable must not appear as list items of map
11194 // clauses of the same construct.
11195 //
11196 // Also, cover one of the cases in:
11197 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11198 // If any part of the original storage of a list item has corresponding
11199 // storage in the device data environment, all of the original storage
11200 // must have corresponding storage in the device data environment.
11201 //
11202 if (DerivedType->isAnyPointerType()) {
11203 if (CI == CE || SI == SE) {
11204 SemaRef.Diag(
11205 DerivedLoc,
11206 diag::err_omp_pointer_mapped_along_with_derived_section)
11207 << DerivedLoc;
11208 } else {
11209 assert(CI != CE && SI != SE);
11210 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11211 << DerivedLoc;
11212 }
11213 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11214 << RE->getSourceRange();
11215 return true;
11216 }
11217
11218 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11219 // List items of map clauses in the same construct must not share
11220 // original storage.
11221 //
11222 // An expression is a subset of the other.
11223 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011224 if (CKind == OMPC_map)
11225 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11226 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011227 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011228 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11229 << ERange;
11230 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011231 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11232 << RE->getSourceRange();
11233 return true;
11234 }
11235
11236 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011237 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011238 if (!CurrentRegionOnly && SI != SE)
11239 EnclosingExpr = RE;
11240
11241 // The current expression is a subset of the expression in the data
11242 // environment.
11243 IsEnclosedByDataEnvironmentExpr |=
11244 (!CurrentRegionOnly && CI != CE && SI == SE);
11245
11246 return false;
11247 });
11248
11249 if (CurrentRegionOnly)
11250 return FoundError;
11251
11252 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11253 // If any part of the original storage of a list item has corresponding
11254 // storage in the device data environment, all of the original storage must
11255 // have corresponding storage in the device data environment.
11256 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11257 // If a list item is an element of a structure, and a different element of
11258 // the structure has a corresponding list item in the device data environment
11259 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011260 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011261 // data environment prior to the task encountering the construct.
11262 //
11263 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11264 SemaRef.Diag(ELoc,
11265 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11266 << ERange;
11267 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11268 << EnclosingExpr->getSourceRange();
11269 return true;
11270 }
11271
11272 return FoundError;
11273}
11274
Samuel Antao661c0902016-05-26 17:39:58 +000011275namespace {
11276// Utility struct that gathers all the related lists associated with a mappable
11277// expression.
11278struct MappableVarListInfo final {
11279 // The list of expressions.
11280 ArrayRef<Expr *> VarList;
11281 // The list of processed expressions.
11282 SmallVector<Expr *, 16> ProcessedVarList;
11283 // The mappble components for each expression.
11284 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11285 // The base declaration of the variable.
11286 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11287
11288 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11289 // We have a list of components and base declarations for each entry in the
11290 // variable list.
11291 VarComponents.reserve(VarList.size());
11292 VarBaseDeclarations.reserve(VarList.size());
11293 }
11294};
11295}
11296
11297// Check the validity of the provided variable list for the provided clause kind
11298// \a CKind. In the check process the valid expressions, and mappable expression
11299// components and variables are extracted and used to fill \a Vars,
11300// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11301// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11302static void
11303checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11304 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11305 SourceLocation StartLoc,
11306 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11307 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011308 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11309 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011310 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011311
Samuel Antao90927002016-04-26 14:54:23 +000011312 // Keep track of the mappable components and base declarations in this clause.
11313 // Each entry in the list is going to have a list of components associated. We
11314 // record each set of the components so that we can build the clause later on.
11315 // In the end we should have the same amount of declarations and component
11316 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011317
Samuel Antao661c0902016-05-26 17:39:58 +000011318 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011319 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011320 SourceLocation ELoc = RE->getExprLoc();
11321
Kelvin Li0bff7af2015-11-23 05:32:03 +000011322 auto *VE = RE->IgnoreParenLValueCasts();
11323
11324 if (VE->isValueDependent() || VE->isTypeDependent() ||
11325 VE->isInstantiationDependent() ||
11326 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011327 // We can only analyze this information once the missing information is
11328 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011329 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011330 continue;
11331 }
11332
11333 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011334
Samuel Antao5de996e2016-01-22 20:21:36 +000011335 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011336 SemaRef.Diag(ELoc,
11337 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011338 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011339 continue;
11340 }
11341
Samuel Antao90927002016-04-26 14:54:23 +000011342 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11343 ValueDecl *CurDeclaration = nullptr;
11344
11345 // Obtain the array or member expression bases if required. Also, fill the
11346 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011347 auto *BE =
11348 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011349 if (!BE)
11350 continue;
11351
Samuel Antao90927002016-04-26 14:54:23 +000011352 assert(!CurComponents.empty() &&
11353 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011354
Samuel Antao90927002016-04-26 14:54:23 +000011355 // For the following checks, we rely on the base declaration which is
11356 // expected to be associated with the last component. The declaration is
11357 // expected to be a variable or a field (if 'this' is being mapped).
11358 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11359 assert(CurDeclaration && "Null decl on map clause.");
11360 assert(
11361 CurDeclaration->isCanonicalDecl() &&
11362 "Expecting components to have associated only canonical declarations.");
11363
11364 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11365 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011366
11367 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011368 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011369
11370 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011371 // threadprivate variables cannot appear in a map clause.
11372 // OpenMP 4.5 [2.10.5, target update Construct]
11373 // threadprivate variables cannot appear in a from clause.
11374 if (VD && DSAS->isThreadPrivate(VD)) {
11375 auto DVar = DSAS->getTopDSA(VD, false);
11376 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11377 << getOpenMPClauseName(CKind);
11378 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011379 continue;
11380 }
11381
Samuel Antao5de996e2016-01-22 20:21:36 +000011382 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11383 // A list item cannot appear in both a map clause and a data-sharing
11384 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011385
Samuel Antao5de996e2016-01-22 20:21:36 +000011386 // Check conflicts with other map clause expressions. We check the conflicts
11387 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011388 // environment, because the restrictions are different. We only have to
11389 // check conflicts across regions for the map clauses.
11390 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11391 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011392 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011393 if (CKind == OMPC_map &&
11394 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11395 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011396 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011397
Samuel Antao661c0902016-05-26 17:39:58 +000011398 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011399 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11400 // If the type of a list item is a reference to a type T then the type will
11401 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011402 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011403
Samuel Antao661c0902016-05-26 17:39:58 +000011404 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11405 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011406 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011407 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011408 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11409 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011410 continue;
11411
Samuel Antao661c0902016-05-26 17:39:58 +000011412 if (CKind == OMPC_map) {
11413 // target enter data
11414 // OpenMP [2.10.2, Restrictions, p. 99]
11415 // A map-type must be specified in all map clauses and must be either
11416 // to or alloc.
11417 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11418 if (DKind == OMPD_target_enter_data &&
11419 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11420 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11421 << (IsMapTypeImplicit ? 1 : 0)
11422 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11423 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011424 continue;
11425 }
Samuel Antao661c0902016-05-26 17:39:58 +000011426
11427 // target exit_data
11428 // OpenMP [2.10.3, Restrictions, p. 102]
11429 // A map-type must be specified in all map clauses and must be either
11430 // from, release, or delete.
11431 if (DKind == OMPD_target_exit_data &&
11432 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11433 MapType == OMPC_MAP_delete)) {
11434 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11435 << (IsMapTypeImplicit ? 1 : 0)
11436 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11437 << getOpenMPDirectiveName(DKind);
11438 continue;
11439 }
11440
11441 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11442 // A list item cannot appear in both a map clause and a data-sharing
11443 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011444 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011445 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011446 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011447 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11448 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011449 auto DVar = DSAS->getTopDSA(VD, false);
11450 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011451 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011452 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011453 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011454 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11455 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11456 continue;
11457 }
11458 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011459 }
11460
Samuel Antao90927002016-04-26 14:54:23 +000011461 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011462 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011463
11464 // Store the components in the stack so that they can be used to check
11465 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011466 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11467 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011468
11469 // Save the components and declaration to create the clause. For purposes of
11470 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011471 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011472 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11473 MVLI.VarComponents.back().append(CurComponents.begin(),
11474 CurComponents.end());
11475 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11476 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011477 }
Samuel Antao661c0902016-05-26 17:39:58 +000011478}
11479
11480OMPClause *
11481Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11482 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11483 SourceLocation MapLoc, SourceLocation ColonLoc,
11484 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11485 SourceLocation LParenLoc, SourceLocation EndLoc) {
11486 MappableVarListInfo MVLI(VarList);
11487 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11488 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011489
Samuel Antao5de996e2016-01-22 20:21:36 +000011490 // We need to produce a map clause even if we don't have variables so that
11491 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011492 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11493 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11494 MVLI.VarComponents, MapTypeModifier, MapType,
11495 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011496}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011497
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011498QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11499 TypeResult ParsedType) {
11500 assert(ParsedType.isUsable());
11501
11502 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11503 if (ReductionType.isNull())
11504 return QualType();
11505
11506 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11507 // A type name in a declare reduction directive cannot be a function type, an
11508 // array type, a reference type, or a type qualified with const, volatile or
11509 // restrict.
11510 if (ReductionType.hasQualifiers()) {
11511 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11512 return QualType();
11513 }
11514
11515 if (ReductionType->isFunctionType()) {
11516 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11517 return QualType();
11518 }
11519 if (ReductionType->isReferenceType()) {
11520 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11521 return QualType();
11522 }
11523 if (ReductionType->isArrayType()) {
11524 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11525 return QualType();
11526 }
11527 return ReductionType;
11528}
11529
11530Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11531 Scope *S, DeclContext *DC, DeclarationName Name,
11532 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11533 AccessSpecifier AS, Decl *PrevDeclInScope) {
11534 SmallVector<Decl *, 8> Decls;
11535 Decls.reserve(ReductionTypes.size());
11536
11537 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
11538 ForRedeclaration);
11539 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11540 // A reduction-identifier may not be re-declared in the current scope for the
11541 // same type or for a type that is compatible according to the base language
11542 // rules.
11543 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11544 OMPDeclareReductionDecl *PrevDRD = nullptr;
11545 bool InCompoundScope = true;
11546 if (S != nullptr) {
11547 // Find previous declaration with the same name not referenced in other
11548 // declarations.
11549 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11550 InCompoundScope =
11551 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11552 LookupName(Lookup, S);
11553 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11554 /*AllowInlineNamespace=*/false);
11555 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11556 auto Filter = Lookup.makeFilter();
11557 while (Filter.hasNext()) {
11558 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11559 if (InCompoundScope) {
11560 auto I = UsedAsPrevious.find(PrevDecl);
11561 if (I == UsedAsPrevious.end())
11562 UsedAsPrevious[PrevDecl] = false;
11563 if (auto *D = PrevDecl->getPrevDeclInScope())
11564 UsedAsPrevious[D] = true;
11565 }
11566 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11567 PrevDecl->getLocation();
11568 }
11569 Filter.done();
11570 if (InCompoundScope) {
11571 for (auto &PrevData : UsedAsPrevious) {
11572 if (!PrevData.second) {
11573 PrevDRD = PrevData.first;
11574 break;
11575 }
11576 }
11577 }
11578 } else if (PrevDeclInScope != nullptr) {
11579 auto *PrevDRDInScope = PrevDRD =
11580 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11581 do {
11582 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11583 PrevDRDInScope->getLocation();
11584 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11585 } while (PrevDRDInScope != nullptr);
11586 }
11587 for (auto &TyData : ReductionTypes) {
11588 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11589 bool Invalid = false;
11590 if (I != PreviousRedeclTypes.end()) {
11591 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11592 << TyData.first;
11593 Diag(I->second, diag::note_previous_definition);
11594 Invalid = true;
11595 }
11596 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11597 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11598 Name, TyData.first, PrevDRD);
11599 DC->addDecl(DRD);
11600 DRD->setAccess(AS);
11601 Decls.push_back(DRD);
11602 if (Invalid)
11603 DRD->setInvalidDecl();
11604 else
11605 PrevDRD = DRD;
11606 }
11607
11608 return DeclGroupPtrTy::make(
11609 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11610}
11611
11612void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11613 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11614
11615 // Enter new function scope.
11616 PushFunctionScope();
11617 getCurFunction()->setHasBranchProtectedScope();
11618 getCurFunction()->setHasOMPDeclareReductionCombiner();
11619
11620 if (S != nullptr)
11621 PushDeclContext(S, DRD);
11622 else
11623 CurContext = DRD;
11624
Faisal Valid143a0c2017-04-01 21:30:49 +000011625 PushExpressionEvaluationContext(
11626 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011627
11628 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011629 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11630 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11631 // uses semantics of argument handles by value, but it should be passed by
11632 // reference. C lang does not support references, so pass all parameters as
11633 // pointers.
11634 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011635 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011636 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011637 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11638 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11639 // uses semantics of argument handles by value, but it should be passed by
11640 // reference. C lang does not support references, so pass all parameters as
11641 // pointers.
11642 // Create 'T omp_out;' variable.
11643 auto *OmpOutParm =
11644 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11645 if (S != nullptr) {
11646 PushOnScopeChains(OmpInParm, S);
11647 PushOnScopeChains(OmpOutParm, S);
11648 } else {
11649 DRD->addDecl(OmpInParm);
11650 DRD->addDecl(OmpOutParm);
11651 }
11652}
11653
11654void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11655 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11656 DiscardCleanupsInEvaluationContext();
11657 PopExpressionEvaluationContext();
11658
11659 PopDeclContext();
11660 PopFunctionScopeInfo();
11661
11662 if (Combiner != nullptr)
11663 DRD->setCombiner(Combiner);
11664 else
11665 DRD->setInvalidDecl();
11666}
11667
Alexey Bataev070f43a2017-09-06 14:49:58 +000011668VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011669 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11670
11671 // Enter new function scope.
11672 PushFunctionScope();
11673 getCurFunction()->setHasBranchProtectedScope();
11674
11675 if (S != nullptr)
11676 PushDeclContext(S, DRD);
11677 else
11678 CurContext = DRD;
11679
Faisal Valid143a0c2017-04-01 21:30:49 +000011680 PushExpressionEvaluationContext(
11681 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011682
11683 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011684 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11685 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11686 // uses semantics of argument handles by value, but it should be passed by
11687 // reference. C lang does not support references, so pass all parameters as
11688 // pointers.
11689 // Create 'T omp_priv;' variable.
11690 auto *OmpPrivParm =
11691 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011692 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11693 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11694 // uses semantics of argument handles by value, but it should be passed by
11695 // reference. C lang does not support references, so pass all parameters as
11696 // pointers.
11697 // Create 'T omp_orig;' variable.
11698 auto *OmpOrigParm =
11699 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011700 if (S != nullptr) {
11701 PushOnScopeChains(OmpPrivParm, S);
11702 PushOnScopeChains(OmpOrigParm, S);
11703 } else {
11704 DRD->addDecl(OmpPrivParm);
11705 DRD->addDecl(OmpOrigParm);
11706 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000011707 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011708}
11709
Alexey Bataev070f43a2017-09-06 14:49:58 +000011710void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
11711 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011712 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11713 DiscardCleanupsInEvaluationContext();
11714 PopExpressionEvaluationContext();
11715
11716 PopDeclContext();
11717 PopFunctionScopeInfo();
11718
Alexey Bataev070f43a2017-09-06 14:49:58 +000011719 if (Initializer != nullptr) {
11720 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
11721 } else if (OmpPrivParm->hasInit()) {
11722 DRD->setInitializer(OmpPrivParm->getInit(),
11723 OmpPrivParm->isDirectInit()
11724 ? OMPDeclareReductionDecl::DirectInit
11725 : OMPDeclareReductionDecl::CopyInit);
11726 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011727 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000011728 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011729}
11730
11731Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11732 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11733 for (auto *D : DeclReductions.get()) {
11734 if (IsValid) {
11735 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11736 if (S != nullptr)
11737 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11738 } else
11739 D->setInvalidDecl();
11740 }
11741 return DeclReductions;
11742}
11743
David Majnemer9d168222016-08-05 17:44:54 +000011744OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011745 SourceLocation StartLoc,
11746 SourceLocation LParenLoc,
11747 SourceLocation EndLoc) {
11748 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011749 Stmt *HelperValStmt = nullptr;
11750 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011751
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011752 // OpenMP [teams Constrcut, Restrictions]
11753 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011754 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11755 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011756 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011757
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011758 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11759 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11760 if (CaptureRegion != OMPD_unknown) {
11761 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11762 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11763 HelperValStmt = buildPreInits(Context, Captures);
11764 }
11765
11766 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11767 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011768}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011769
11770OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11771 SourceLocation StartLoc,
11772 SourceLocation LParenLoc,
11773 SourceLocation EndLoc) {
11774 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011775 Stmt *HelperValStmt = nullptr;
11776 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011777
11778 // OpenMP [teams Constrcut, Restrictions]
11779 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011780 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11781 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011782 return nullptr;
11783
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011784 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11785 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11786 if (CaptureRegion != OMPD_unknown) {
11787 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11788 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11789 HelperValStmt = buildPreInits(Context, Captures);
11790 }
11791
11792 return new (Context) OMPThreadLimitClause(
11793 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011794}
Alexey Bataeva0569352015-12-01 10:17:31 +000011795
11796OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11797 SourceLocation StartLoc,
11798 SourceLocation LParenLoc,
11799 SourceLocation EndLoc) {
11800 Expr *ValExpr = Priority;
11801
11802 // OpenMP [2.9.1, task Constrcut]
11803 // The priority-value is a non-negative numerical scalar expression.
11804 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11805 /*StrictlyPositive=*/false))
11806 return nullptr;
11807
11808 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11809}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011810
11811OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11812 SourceLocation StartLoc,
11813 SourceLocation LParenLoc,
11814 SourceLocation EndLoc) {
11815 Expr *ValExpr = Grainsize;
11816
11817 // OpenMP [2.9.2, taskloop Constrcut]
11818 // The parameter of the grainsize clause must be a positive integer
11819 // expression.
11820 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11821 /*StrictlyPositive=*/true))
11822 return nullptr;
11823
11824 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11825}
Alexey Bataev382967a2015-12-08 12:06:20 +000011826
11827OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11828 SourceLocation StartLoc,
11829 SourceLocation LParenLoc,
11830 SourceLocation EndLoc) {
11831 Expr *ValExpr = NumTasks;
11832
11833 // OpenMP [2.9.2, taskloop Constrcut]
11834 // The parameter of the num_tasks clause must be a positive integer
11835 // expression.
11836 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11837 /*StrictlyPositive=*/true))
11838 return nullptr;
11839
11840 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11841}
11842
Alexey Bataev28c75412015-12-15 08:19:24 +000011843OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11844 SourceLocation LParenLoc,
11845 SourceLocation EndLoc) {
11846 // OpenMP [2.13.2, critical construct, Description]
11847 // ... where hint-expression is an integer constant expression that evaluates
11848 // to a valid lock hint.
11849 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11850 if (HintExpr.isInvalid())
11851 return nullptr;
11852 return new (Context)
11853 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11854}
11855
Carlo Bertollib4adf552016-01-15 18:50:31 +000011856OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11857 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11858 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11859 SourceLocation EndLoc) {
11860 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11861 std::string Values;
11862 Values += "'";
11863 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11864 Values += "'";
11865 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11866 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11867 return nullptr;
11868 }
11869 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011870 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011871 if (ChunkSize) {
11872 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11873 !ChunkSize->isInstantiationDependent() &&
11874 !ChunkSize->containsUnexpandedParameterPack()) {
11875 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11876 ExprResult Val =
11877 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11878 if (Val.isInvalid())
11879 return nullptr;
11880
11881 ValExpr = Val.get();
11882
11883 // OpenMP [2.7.1, Restrictions]
11884 // chunk_size must be a loop invariant integer expression with a positive
11885 // value.
11886 llvm::APSInt Result;
11887 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11888 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11889 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11890 << "dist_schedule" << ChunkSize->getSourceRange();
11891 return nullptr;
11892 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011893 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11894 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011895 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11896 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11897 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011898 }
11899 }
11900 }
11901
11902 return new (Context)
11903 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011904 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011905}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011906
11907OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11908 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11909 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11910 SourceLocation KindLoc, SourceLocation EndLoc) {
11911 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011912 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011913 std::string Value;
11914 SourceLocation Loc;
11915 Value += "'";
11916 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11917 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011918 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011919 Loc = MLoc;
11920 } else {
11921 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011922 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011923 Loc = KindLoc;
11924 }
11925 Value += "'";
11926 Diag(Loc, diag::err_omp_unexpected_clause_value)
11927 << Value << getOpenMPClauseName(OMPC_defaultmap);
11928 return nullptr;
11929 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000011930 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011931
11932 return new (Context)
11933 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11934}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011935
11936bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11937 DeclContext *CurLexicalContext = getCurLexicalContext();
11938 if (!CurLexicalContext->isFileContext() &&
11939 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000011940 !CurLexicalContext->isExternCXXContext() &&
11941 !isa<CXXRecordDecl>(CurLexicalContext) &&
11942 !isa<ClassTemplateDecl>(CurLexicalContext) &&
11943 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
11944 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011945 Diag(Loc, diag::err_omp_region_not_file_context);
11946 return false;
11947 }
11948 if (IsInOpenMPDeclareTargetContext) {
11949 Diag(Loc, diag::err_omp_enclosed_declare_target);
11950 return false;
11951 }
11952
11953 IsInOpenMPDeclareTargetContext = true;
11954 return true;
11955}
11956
11957void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11958 assert(IsInOpenMPDeclareTargetContext &&
11959 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11960
11961 IsInOpenMPDeclareTargetContext = false;
11962}
11963
David Majnemer9d168222016-08-05 17:44:54 +000011964void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11965 CXXScopeSpec &ScopeSpec,
11966 const DeclarationNameInfo &Id,
11967 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11968 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011969 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11970 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11971
11972 if (Lookup.isAmbiguous())
11973 return;
11974 Lookup.suppressDiagnostics();
11975
11976 if (!Lookup.isSingleResult()) {
11977 if (TypoCorrection Corrected =
11978 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11979 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11980 CTK_ErrorRecovery)) {
11981 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11982 << Id.getName());
11983 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11984 return;
11985 }
11986
11987 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11988 return;
11989 }
11990
11991 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11992 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11993 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11994 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11995
11996 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11997 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11998 ND->addAttr(A);
11999 if (ASTMutationListener *ML = Context.getASTMutationListener())
12000 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12001 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12002 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12003 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12004 << Id.getName();
12005 }
12006 } else
12007 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12008}
12009
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012010static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12011 Sema &SemaRef, Decl *D) {
12012 if (!D)
12013 return;
12014 Decl *LD = nullptr;
12015 if (isa<TagDecl>(D)) {
12016 LD = cast<TagDecl>(D)->getDefinition();
12017 } else if (isa<VarDecl>(D)) {
12018 LD = cast<VarDecl>(D)->getDefinition();
12019
12020 // If this is an implicit variable that is legal and we do not need to do
12021 // anything.
12022 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012023 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12024 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12025 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012026 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012027 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012028 return;
12029 }
12030
12031 } else if (isa<FunctionDecl>(D)) {
12032 const FunctionDecl *FD = nullptr;
12033 if (cast<FunctionDecl>(D)->hasBody(FD))
12034 LD = const_cast<FunctionDecl *>(FD);
12035
12036 // If the definition is associated with the current declaration in the
12037 // target region (it can be e.g. a lambda) that is legal and we do not need
12038 // to do anything else.
12039 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012040 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12041 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12042 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012043 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012044 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012045 return;
12046 }
12047 }
12048 if (!LD)
12049 LD = D;
12050 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12051 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12052 // Outlined declaration is not declared target.
12053 if (LD->isOutOfLine()) {
12054 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12055 SemaRef.Diag(SL, diag::note_used_here) << SR;
12056 } else {
12057 DeclContext *DC = LD->getDeclContext();
12058 while (DC) {
12059 if (isa<FunctionDecl>(DC) &&
12060 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12061 break;
12062 DC = DC->getParent();
12063 }
12064 if (DC)
12065 return;
12066
12067 // Is not declared in target context.
12068 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12069 SemaRef.Diag(SL, diag::note_used_here) << SR;
12070 }
12071 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012072 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12073 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12074 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012075 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012076 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012077 }
12078}
12079
12080static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12081 Sema &SemaRef, DSAStackTy *Stack,
12082 ValueDecl *VD) {
12083 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12084 return true;
12085 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12086 return false;
12087 return true;
12088}
12089
12090void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12091 if (!D || D->isInvalidDecl())
12092 return;
12093 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12094 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12095 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12096 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12097 if (DSAStack->isThreadPrivate(VD)) {
12098 Diag(SL, diag::err_omp_threadprivate_in_target);
12099 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12100 return;
12101 }
12102 }
12103 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12104 // Problem if any with var declared with incomplete type will be reported
12105 // as normal, so no need to check it here.
12106 if ((E || !VD->getType()->isIncompleteType()) &&
12107 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12108 // Mark decl as declared target to prevent further diagnostic.
12109 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012110 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12111 Context, OMPDeclareTargetDeclAttr::MT_To);
12112 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012113 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012114 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012115 }
12116 return;
12117 }
12118 }
12119 if (!E) {
12120 // Checking declaration inside declare target region.
12121 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12122 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012123 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12124 Context, OMPDeclareTargetDeclAttr::MT_To);
12125 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012126 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012127 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012128 }
12129 return;
12130 }
12131 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12132}
Samuel Antao661c0902016-05-26 17:39:58 +000012133
12134OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12135 SourceLocation StartLoc,
12136 SourceLocation LParenLoc,
12137 SourceLocation EndLoc) {
12138 MappableVarListInfo MVLI(VarList);
12139 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12140 if (MVLI.ProcessedVarList.empty())
12141 return nullptr;
12142
12143 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12144 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12145 MVLI.VarComponents);
12146}
Samuel Antaoec172c62016-05-26 17:49:04 +000012147
12148OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12149 SourceLocation StartLoc,
12150 SourceLocation LParenLoc,
12151 SourceLocation EndLoc) {
12152 MappableVarListInfo MVLI(VarList);
12153 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12154 if (MVLI.ProcessedVarList.empty())
12155 return nullptr;
12156
12157 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12158 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12159 MVLI.VarComponents);
12160}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012161
12162OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12163 SourceLocation StartLoc,
12164 SourceLocation LParenLoc,
12165 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012166 MappableVarListInfo MVLI(VarList);
12167 SmallVector<Expr *, 8> PrivateCopies;
12168 SmallVector<Expr *, 8> Inits;
12169
Carlo Bertolli2404b172016-07-13 15:37:16 +000012170 for (auto &RefExpr : VarList) {
12171 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12172 SourceLocation ELoc;
12173 SourceRange ERange;
12174 Expr *SimpleRefExpr = RefExpr;
12175 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12176 if (Res.second) {
12177 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012178 MVLI.ProcessedVarList.push_back(RefExpr);
12179 PrivateCopies.push_back(nullptr);
12180 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012181 }
12182 ValueDecl *D = Res.first;
12183 if (!D)
12184 continue;
12185
12186 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012187 Type = Type.getNonReferenceType().getUnqualifiedType();
12188
12189 auto *VD = dyn_cast<VarDecl>(D);
12190
12191 // Item should be a pointer or reference to pointer.
12192 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012193 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12194 << 0 << RefExpr->getSourceRange();
12195 continue;
12196 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012197
12198 // Build the private variable and the expression that refers to it.
12199 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12200 D->hasAttrs() ? &D->getAttrs() : nullptr);
12201 if (VDPrivate->isInvalidDecl())
12202 continue;
12203
12204 CurContext->addDecl(VDPrivate);
12205 auto VDPrivateRefExpr = buildDeclRefExpr(
12206 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12207
12208 // Add temporary variable to initialize the private copy of the pointer.
12209 auto *VDInit =
12210 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12211 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12212 RefExpr->getExprLoc());
12213 AddInitializerToDecl(VDPrivate,
12214 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012215 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012216
12217 // If required, build a capture to implement the privatization initialized
12218 // with the current list item value.
12219 DeclRefExpr *Ref = nullptr;
12220 if (!VD)
12221 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12222 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12223 PrivateCopies.push_back(VDPrivateRefExpr);
12224 Inits.push_back(VDInitRefExpr);
12225
12226 // We need to add a data sharing attribute for this variable to make sure it
12227 // is correctly captured. A variable that shows up in a use_device_ptr has
12228 // similar properties of a first private variable.
12229 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12230
12231 // Create a mappable component for the list item. List items in this clause
12232 // only need a component.
12233 MVLI.VarBaseDeclarations.push_back(D);
12234 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12235 MVLI.VarComponents.back().push_back(
12236 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012237 }
12238
Samuel Antaocc10b852016-07-28 14:23:26 +000012239 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012240 return nullptr;
12241
Samuel Antaocc10b852016-07-28 14:23:26 +000012242 return OMPUseDevicePtrClause::Create(
12243 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12244 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012245}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012246
12247OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12248 SourceLocation StartLoc,
12249 SourceLocation LParenLoc,
12250 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012251 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012252 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012253 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012254 SourceLocation ELoc;
12255 SourceRange ERange;
12256 Expr *SimpleRefExpr = RefExpr;
12257 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12258 if (Res.second) {
12259 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012260 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012261 }
12262 ValueDecl *D = Res.first;
12263 if (!D)
12264 continue;
12265
12266 QualType Type = D->getType();
12267 // item should be a pointer or array or reference to pointer or array
12268 if (!Type.getNonReferenceType()->isPointerType() &&
12269 !Type.getNonReferenceType()->isArrayType()) {
12270 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12271 << 0 << RefExpr->getSourceRange();
12272 continue;
12273 }
Samuel Antao6890b092016-07-28 14:25:09 +000012274
12275 // Check if the declaration in the clause does not show up in any data
12276 // sharing attribute.
12277 auto DVar = DSAStack->getTopDSA(D, false);
12278 if (isOpenMPPrivate(DVar.CKind)) {
12279 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12280 << getOpenMPClauseName(DVar.CKind)
12281 << getOpenMPClauseName(OMPC_is_device_ptr)
12282 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12283 ReportOriginalDSA(*this, DSAStack, D, DVar);
12284 continue;
12285 }
12286
12287 Expr *ConflictExpr;
12288 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012289 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012290 [&ConflictExpr](
12291 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12292 OpenMPClauseKind) -> bool {
12293 ConflictExpr = R.front().getAssociatedExpression();
12294 return true;
12295 })) {
12296 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12297 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12298 << ConflictExpr->getSourceRange();
12299 continue;
12300 }
12301
12302 // Store the components in the stack so that they can be used to check
12303 // against other clauses later on.
12304 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12305 DSAStack->addMappableExpressionComponents(
12306 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12307
12308 // Record the expression we've just processed.
12309 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12310
12311 // Create a mappable component for the list item. List items in this clause
12312 // only need a component. We use a null declaration to signal fields in
12313 // 'this'.
12314 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12315 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12316 "Unexpected device pointer expression!");
12317 MVLI.VarBaseDeclarations.push_back(
12318 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12319 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12320 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012321 }
12322
Samuel Antao6890b092016-07-28 14:25:09 +000012323 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012324 return nullptr;
12325
Samuel Antao6890b092016-07-28 14:25:09 +000012326 return OMPIsDevicePtrClause::Create(
12327 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12328 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012329}