blob: a9e94e9890a70a9dfd02351180ddb15a41859efd [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 Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000017#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000018#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/StmtCXX.h"
21#include "clang/AST/StmtOpenMP.h"
22#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "clang/Basic/OpenMPKinds.h"
24#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000025#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000026#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000027#include "clang/Sema/Scope.h"
28#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030using namespace clang;
31
Alexey Bataev758e55e2013-09-06 18:03:48 +000032//===----------------------------------------------------------------------===//
33// Stack of data-sharing attributes for variables
34//===----------------------------------------------------------------------===//
35
36namespace {
37/// \brief Default data sharing attributes, which can be applied to directive.
38enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000039 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
40 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
41 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000042};
Alexey Bataev7ff55242014-06-19 09:13:45 +000043
Alexey Bataevf29276e2014-06-18 04:14:57 +000044template <class T> struct MatchesAny {
Alexey Bataev23b69422014-06-18 07:08:49 +000045 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
Alexey Bataevf29276e2014-06-18 04:14:57 +000046 bool operator()(T Kind) {
47 for (auto KindEl : Arr)
48 if (KindEl == Kind)
49 return true;
50 return false;
51 }
52
53private:
54 ArrayRef<T> Arr;
55};
Alexey Bataev23b69422014-06-18 07:08:49 +000056struct MatchesAlways {
Alexey Bataevf29276e2014-06-18 04:14:57 +000057 MatchesAlways() {}
Alexey Bataev7ff55242014-06-19 09:13:45 +000058 template <class T> bool operator()(T) { return true; }
Alexey Bataevf29276e2014-06-18 04:14:57 +000059};
60
61typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
62typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
Alexey Bataev758e55e2013-09-06 18:03:48 +000063
64/// \brief Stack for tracking declarations used in OpenMP directives and
65/// clauses and their data-sharing attributes.
66class DSAStackTy {
67public:
68 struct DSAVarData {
69 OpenMPDirectiveKind DKind;
70 OpenMPClauseKind CKind;
71 DeclRefExpr *RefExpr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000072 SourceLocation ImplicitDSALoc;
73 DSAVarData()
74 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
75 ImplicitDSALoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000076 };
Alexey Bataeved09d242014-05-28 05:53:51 +000077
Alexey Bataev758e55e2013-09-06 18:03:48 +000078private:
79 struct DSAInfo {
80 OpenMPClauseKind Attributes;
81 DeclRefExpr *RefExpr;
82 };
83 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000084 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000085
86 struct SharingMapTy {
87 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000088 AlignedMapTy AlignedMap;
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000090 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +000091 OpenMPDirectiveKind Directive;
92 DeclarationNameInfo DirectiveName;
93 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation ConstructLoc;
Alexey Bataev9fb6e642014-07-22 06:45:04 +000095 bool OrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +000096 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +000097 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 Scope *CurScope, SourceLocation Loc)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000099 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000100 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev13314bf2014-10-09 04:18:56 +0000101 ConstructLoc(Loc), OrderedRegion(false), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000102 SharingMapTy()
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000103 : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000104 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev13314bf2014-10-09 04:18:56 +0000105 ConstructLoc(), OrderedRegion(false), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000106 };
107
108 typedef SmallVector<SharingMapTy, 64> StackTy;
109
110 /// \brief Stack of used declaration and their data-sharing attributes.
111 StackTy Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000112 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000113
114 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
115
116 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000117
118 /// \brief Checks if the variable is a local for OpenMP region.
119 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000120
Alexey Bataev758e55e2013-09-06 18:03:48 +0000121public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000122 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000123
124 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000125 Scope *CurScope, SourceLocation Loc) {
126 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
127 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128 }
129
130 void pop() {
131 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
132 Stack.pop_back();
133 }
134
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000135 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000136 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000137 /// for diagnostics.
138 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
139
Alexey Bataev758e55e2013-09-06 18:03:48 +0000140 /// \brief Adds explicit data sharing attribute to the specified declaration.
141 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
142
Alexey Bataev758e55e2013-09-06 18:03:48 +0000143 /// \brief Returns data sharing attributes from top of the stack for the
144 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000145 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000146 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000147 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000148 /// \brief Checks if the specified variables has data-sharing attributes which
149 /// match specified \a CPred predicate in any directive which matches \a DPred
150 /// predicate.
151 template <class ClausesPredicate, class DirectivesPredicate>
152 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000153 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000154 /// \brief Checks if the specified variables has data-sharing attributes which
155 /// match specified \a CPred predicate in any innermost directive which
156 /// matches \a DPred predicate.
157 template <class ClausesPredicate, class DirectivesPredicate>
158 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000159 DirectivesPredicate DPred,
160 bool FromParent);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000161 /// \brief Finds a directive which matches specified \a DPred predicate.
162 template <class NamedDirectivesPredicate>
163 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000164
Alexey Bataev758e55e2013-09-06 18:03:48 +0000165 /// \brief Returns currently analyzed directive.
166 OpenMPDirectiveKind getCurrentDirective() const {
167 return Stack.back().Directive;
168 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000169 /// \brief Returns parent directive.
170 OpenMPDirectiveKind getParentDirective() const {
171 if (Stack.size() > 2)
172 return Stack[Stack.size() - 2].Directive;
173 return OMPD_unknown;
174 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000175
176 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000177 void setDefaultDSANone(SourceLocation Loc) {
178 Stack.back().DefaultAttr = DSA_none;
179 Stack.back().DefaultAttrLoc = Loc;
180 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000181 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000182 void setDefaultDSAShared(SourceLocation Loc) {
183 Stack.back().DefaultAttr = DSA_shared;
184 Stack.back().DefaultAttrLoc = Loc;
185 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186
187 DefaultDataSharingAttributes getDefaultDSA() const {
188 return Stack.back().DefaultAttr;
189 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000190 SourceLocation getDefaultDSALocation() const {
191 return Stack.back().DefaultAttrLoc;
192 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000193
Alexey Bataevf29276e2014-06-18 04:14:57 +0000194 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000195 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000196 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000197 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000198 }
199
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000200 /// \brief Marks current region as ordered (it has an 'ordered' clause).
201 void setOrderedRegion(bool IsOrdered = true) {
202 Stack.back().OrderedRegion = IsOrdered;
203 }
204 /// \brief Returns true, if parent region is ordered (has associated
205 /// 'ordered' clause), false - otherwise.
206 bool isParentOrderedRegion() const {
207 if (Stack.size() > 2)
208 return Stack[Stack.size() - 2].OrderedRegion;
209 return false;
210 }
211
Alexey Bataev13314bf2014-10-09 04:18:56 +0000212 /// \brief Marks current target region as one with closely nested teams
213 /// region.
214 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
215 if (Stack.size() > 2)
216 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
217 }
218 /// \brief Returns true, if current region has closely nested teams region.
219 bool hasInnerTeamsRegion() const {
220 return getInnerTeamsRegionLoc().isValid();
221 }
222 /// \brief Returns location of the nested teams region (if any).
223 SourceLocation getInnerTeamsRegionLoc() const {
224 if (Stack.size() > 1)
225 return Stack.back().InnerTeamsRegionLoc;
226 return SourceLocation();
227 }
228
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000229 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000231 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000232};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000233bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
234 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000235 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000236}
Alexey Bataeved09d242014-05-28 05:53:51 +0000237} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000238
239DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
240 VarDecl *D) {
241 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000242 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000243 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
244 // in a region but not in construct]
245 // File-scope or namespace-scope variables referenced in called routines
246 // in the region are shared unless they appear in a threadprivate
247 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000248 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000249 DVar.CKind = OMPC_shared;
250
251 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
252 // in a region but not in construct]
253 // Variables with static storage duration that are declared in called
254 // routines in the region are shared.
255 if (D->hasGlobalStorage())
256 DVar.CKind = OMPC_shared;
257
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258 return DVar;
259 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000260
Alexey Bataev758e55e2013-09-06 18:03:48 +0000261 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000262 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
263 // in a Construct, C/C++, predetermined, p.1]
264 // Variables with automatic storage duration that are declared in a scope
265 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000266 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
267 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
268 DVar.CKind = OMPC_private;
269 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000270 }
271
Alexey Bataev758e55e2013-09-06 18:03:48 +0000272 // Explicitly specified attributes and local variables with predetermined
273 // attributes.
274 if (Iter->SharingMap.count(D)) {
275 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
276 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000277 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000278 return DVar;
279 }
280
281 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
282 // in a Construct, C/C++, implicitly determined, p.1]
283 // In a parallel or task construct, the data-sharing attributes of these
284 // variables are determined by the default clause, if present.
285 switch (Iter->DefaultAttr) {
286 case DSA_shared:
287 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000288 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000289 return DVar;
290 case DSA_none:
291 return DVar;
292 case DSA_unspecified:
293 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
294 // in a Construct, implicitly determined, p.2]
295 // In a parallel construct, if no default clause is present, these
296 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000297 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000298 if (isOpenMPParallelDirective(DVar.DKind) ||
299 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000300 DVar.CKind = OMPC_shared;
301 return DVar;
302 }
303
304 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
305 // in a Construct, implicitly determined, p.4]
306 // In a task construct, if no default clause is present, a variable that in
307 // the enclosing context is determined to be shared by all implicit tasks
308 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000309 if (DVar.DKind == OMPD_task) {
310 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000311 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000312 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000313 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
314 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000315 // in a Construct, implicitly determined, p.6]
316 // In a task construct, if no default clause is present, a variable
317 // whose data-sharing attribute is not determined by the rules above is
318 // firstprivate.
319 DVarTemp = getDSA(I, D);
320 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000321 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000322 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000323 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000324 return DVar;
325 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000326 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000327 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000328 }
329 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000330 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000331 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000332 return DVar;
333 }
334 }
335 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
336 // in a Construct, implicitly determined, p.3]
337 // For constructs other than task, if no default clause is present, these
338 // variables inherit their data-sharing attributes from the enclosing
339 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000340 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000341}
342
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000343DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
344 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
345 auto It = Stack.back().AlignedMap.find(D);
346 if (It == Stack.back().AlignedMap.end()) {
347 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
348 Stack.back().AlignedMap[D] = NewDE;
349 return nullptr;
350 } else {
351 assert(It->second && "Unexpected nullptr expr in the aligned map");
352 return It->second;
353 }
354 return nullptr;
355}
356
Alexey Bataev758e55e2013-09-06 18:03:48 +0000357void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
358 if (A == OMPC_threadprivate) {
359 Stack[0].SharingMap[D].Attributes = A;
360 Stack[0].SharingMap[D].RefExpr = E;
361 } else {
362 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
363 Stack.back().SharingMap[D].Attributes = A;
364 Stack.back().SharingMap[D].RefExpr = E;
365 }
366}
367
Alexey Bataeved09d242014-05-28 05:53:51 +0000368bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000369 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000370 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000371 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000372 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000373 ++I;
374 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000375 if (I == E)
376 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000377 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000378 Scope *CurScope = getCurScope();
379 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000380 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000381 }
382 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000383 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000384 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000385}
386
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000387DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000388 DSAVarData DVar;
389
390 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
391 // in a Construct, C/C++, predetermined, p.1]
392 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000393 if (D->getTLSKind() != VarDecl::TLS_None ||
394 D->getStorageClass() == SC_Register) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000395 DVar.CKind = OMPC_threadprivate;
396 return DVar;
397 }
398 if (Stack[0].SharingMap.count(D)) {
399 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
400 DVar.CKind = OMPC_threadprivate;
401 return DVar;
402 }
403
404 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
405 // in a Construct, C/C++, predetermined, p.1]
406 // Variables with automatic storage duration that are declared in a scope
407 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000408 OpenMPDirectiveKind Kind =
409 FromParent ? getParentDirective() : getCurrentDirective();
410 auto StartI = std::next(Stack.rbegin());
411 auto EndI = std::prev(Stack.rend());
412 if (FromParent && StartI != EndI) {
413 StartI = std::next(StartI);
414 }
415 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000416 if (isOpenMPLocal(D, StartI) &&
417 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
418 D->getStorageClass() == SC_None)) ||
419 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000420 DVar.CKind = OMPC_private;
421 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000422 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000423
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000424 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
425 // in a Construct, C/C++, predetermined, p.4]
426 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000427 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
428 // in a Construct, C/C++, predetermined, p.7]
429 // Variables with static storage duration that are declared in a scope
430 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000431 if (D->isStaticDataMember() || D->isStaticLocal()) {
432 DSAVarData DVarTemp =
433 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
434 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
435 return DVar;
436
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000437 DVar.CKind = OMPC_shared;
438 return DVar;
439 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000440 }
441
442 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000443 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
Alexey Bataev758e55e2013-09-06 18:03:48 +0000444 while (Type->isArrayType()) {
445 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
446 Type = ElemType.getNonReferenceType().getCanonicalType();
447 }
448 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
449 // in a Construct, C/C++, predetermined, p.6]
450 // Variables with const qualified type having no mutable member are
451 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000452 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000453 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000454 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000455 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000456 // Variables with const-qualified type having no mutable member may be
457 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000458 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
459 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000460 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
461 return DVar;
462
Alexey Bataev758e55e2013-09-06 18:03:48 +0000463 DVar.CKind = OMPC_shared;
464 return DVar;
465 }
466
Alexey Bataev758e55e2013-09-06 18:03:48 +0000467 // Explicitly specified attributes and local variables with predetermined
468 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000469 auto I = std::prev(StartI);
470 if (I->SharingMap.count(D)) {
471 DVar.RefExpr = I->SharingMap[D].RefExpr;
472 DVar.CKind = I->SharingMap[D].Attributes;
473 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000474 }
475
476 return DVar;
477}
478
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000479DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
480 auto StartI = Stack.rbegin();
481 auto EndI = std::prev(Stack.rend());
482 if (FromParent && StartI != EndI) {
483 StartI = std::next(StartI);
484 }
485 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000486}
487
Alexey Bataevf29276e2014-06-18 04:14:57 +0000488template <class ClausesPredicate, class DirectivesPredicate>
489DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000490 DirectivesPredicate DPred,
491 bool FromParent) {
492 auto StartI = std::next(Stack.rbegin());
493 auto EndI = std::prev(Stack.rend());
494 if (FromParent && StartI != EndI) {
495 StartI = std::next(StartI);
496 }
497 for (auto I = StartI, EE = EndI; I != EE; ++I) {
498 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000499 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000500 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000501 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000502 return DVar;
503 }
504 return DSAVarData();
505}
506
Alexey Bataevf29276e2014-06-18 04:14:57 +0000507template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000508DSAStackTy::DSAVarData
509DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
510 DirectivesPredicate DPred, bool FromParent) {
511 auto StartI = std::next(Stack.rbegin());
512 auto EndI = std::prev(Stack.rend());
513 if (FromParent && StartI != EndI) {
514 StartI = std::next(StartI);
515 }
516 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000517 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000518 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000519 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000520 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000521 return DVar;
522 return DSAVarData();
523 }
524 return DSAVarData();
525}
526
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000527template <class NamedDirectivesPredicate>
528bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
529 auto StartI = std::next(Stack.rbegin());
530 auto EndI = std::prev(Stack.rend());
531 if (FromParent && StartI != EndI) {
532 StartI = std::next(StartI);
533 }
534 for (auto I = StartI, EE = EndI; I != EE; ++I) {
535 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
536 return true;
537 }
538 return false;
539}
540
Alexey Bataev758e55e2013-09-06 18:03:48 +0000541void Sema::InitDataSharingAttributesStack() {
542 VarDataSharingAttributesStack = new DSAStackTy(*this);
543}
544
545#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
546
Alexey Bataevf841bd92014-12-16 07:00:22 +0000547bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
548 assert(LangOpts.OpenMP && "OpenMP is not allowed");
549 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
550 auto DVarPrivate = DSAStack->getTopDSA(VD, /*FromParent=*/false);
551 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
552 return true;
553 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
554 /*FromParent=*/false);
555 return DVarPrivate.CKind != OMPC_unknown;
556 }
557 return false;
558}
559
Alexey Bataeved09d242014-05-28 05:53:51 +0000560void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000561
562void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
563 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000564 Scope *CurScope, SourceLocation Loc) {
565 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000566 PushExpressionEvaluationContext(PotentiallyEvaluated);
567}
568
569void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000570 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
571 // A variable of class type (or array thereof) that appears in a lastprivate
572 // clause requires an accessible, unambiguous default constructor for the
573 // class type, unless the list item is also specified in a firstprivate
574 // clause.
575 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
576 for (auto C : D->clauses()) {
577 if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) {
578 for (auto VarRef : Clause->varlists()) {
579 if (VarRef->isValueDependent() || VarRef->isTypeDependent())
580 continue;
581 auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000582 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000583 if (DVar.CKind == OMPC_lastprivate) {
584 SourceLocation ELoc = VarRef->getExprLoc();
585 auto Type = VarRef->getType();
586 if (Type->isArrayType())
587 Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
588 CXXRecordDecl *RD =
Alexey Bataev23b69422014-06-18 07:08:49 +0000589 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
590 // FIXME This code must be replaced by actual constructing of the
591 // lastprivate variable.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000592 if (RD) {
593 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
594 PartialDiagnostic PD =
595 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
596 if (!CD ||
597 CheckConstructorAccess(
598 ELoc, CD, InitializedEntity::InitializeTemporary(Type),
599 CD->getAccess(), PD) == AR_inaccessible ||
600 CD->isDeleted()) {
601 Diag(ELoc, diag::err_omp_required_method)
602 << getOpenMPClauseName(OMPC_lastprivate) << 0;
603 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
604 VarDecl::DeclarationOnly;
605 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl
606 : diag::note_defined_here)
607 << VD;
608 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
609 continue;
610 }
611 MarkFunctionReferenced(ELoc, CD);
612 DiagnoseUseOfDecl(CD, ELoc);
613 }
614 }
615 }
616 }
617 }
618 }
619
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620 DSAStack->pop();
621 DiscardCleanupsInEvaluationContext();
622 PopExpressionEvaluationContext();
623}
624
Alexander Musman3276a272015-03-21 10:12:56 +0000625static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
626 Expr *NumIterations, Sema &SemaRef,
627 Scope *S);
628
Alexey Bataeva769e072013-03-22 06:34:35 +0000629namespace {
630
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000631class VarDeclFilterCCC : public CorrectionCandidateCallback {
632private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000633 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000634
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000635public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000636 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000637 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000638 NamedDecl *ND = Candidate.getCorrectionDecl();
639 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
640 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000641 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
642 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000643 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000644 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000645 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000646};
Alexey Bataeved09d242014-05-28 05:53:51 +0000647} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000648
649ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
650 CXXScopeSpec &ScopeSpec,
651 const DeclarationNameInfo &Id) {
652 LookupResult Lookup(*this, Id, LookupOrdinaryName);
653 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
654
655 if (Lookup.isAmbiguous())
656 return ExprError();
657
658 VarDecl *VD;
659 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000660 if (TypoCorrection Corrected = CorrectTypo(
661 Id, LookupOrdinaryName, CurScope, nullptr,
662 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000663 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000664 PDiag(Lookup.empty()
665 ? diag::err_undeclared_var_use_suggest
666 : diag::err_omp_expected_var_arg_suggest)
667 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000668 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000669 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000670 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
671 : diag::err_omp_expected_var_arg)
672 << Id.getName();
673 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000674 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000675 } else {
676 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000677 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000678 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
679 return ExprError();
680 }
681 }
682 Lookup.suppressDiagnostics();
683
684 // OpenMP [2.9.2, Syntax, C/C++]
685 // Variables must be file-scope, namespace-scope, or static block-scope.
686 if (!VD->hasGlobalStorage()) {
687 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000688 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
689 bool IsDecl =
690 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000691 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000692 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
693 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000694 return ExprError();
695 }
696
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000697 VarDecl *CanonicalVD = VD->getCanonicalDecl();
698 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000699 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
700 // A threadprivate directive for file-scope variables must appear outside
701 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000702 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
703 !getCurLexicalContext()->isTranslationUnit()) {
704 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000705 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
706 bool IsDecl =
707 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
708 Diag(VD->getLocation(),
709 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
710 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000711 return ExprError();
712 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000713 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
714 // A threadprivate directive for static class member variables must appear
715 // in the class definition, in the same scope in which the member
716 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000717 if (CanonicalVD->isStaticDataMember() &&
718 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
719 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000720 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
721 bool IsDecl =
722 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
723 Diag(VD->getLocation(),
724 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
725 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000726 return ExprError();
727 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000728 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
729 // A threadprivate directive for namespace-scope variables must appear
730 // outside any definition or declaration other than the namespace
731 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000732 if (CanonicalVD->getDeclContext()->isNamespace() &&
733 (!getCurLexicalContext()->isFileContext() ||
734 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
735 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000736 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
737 bool IsDecl =
738 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
739 Diag(VD->getLocation(),
740 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
741 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000742 return ExprError();
743 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000744 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
745 // A threadprivate directive for static block-scope variables must appear
746 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000747 if (CanonicalVD->isStaticLocal() && CurScope &&
748 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000749 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000750 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
751 bool IsDecl =
752 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
753 Diag(VD->getLocation(),
754 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
755 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000756 return ExprError();
757 }
758
759 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
760 // A threadprivate directive must lexically precede all references to any
761 // of the variables in its list.
Alexey Bataev7c2ed442015-04-08 12:45:41 +0000762 if (VD->isUsed() && !DSAStack->isThreadPrivate(CanonicalVD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000763 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000764 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000765 return ExprError();
766 }
767
768 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataevd178ad42014-03-07 08:03:37 +0000769 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000770 return DE;
771}
772
Alexey Bataeved09d242014-05-28 05:53:51 +0000773Sema::DeclGroupPtrTy
774Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
775 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000776 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000777 CurContext->addDecl(D);
778 return DeclGroupPtrTy::make(DeclGroupRef(D));
779 }
780 return DeclGroupPtrTy();
781}
782
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000783namespace {
784class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
785 Sema &SemaRef;
786
787public:
788 bool VisitDeclRefExpr(const DeclRefExpr *E) {
789 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
790 if (VD->hasLocalStorage()) {
791 SemaRef.Diag(E->getLocStart(),
792 diag::err_omp_local_var_in_threadprivate_init)
793 << E->getSourceRange();
794 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
795 << VD << VD->getSourceRange();
796 return true;
797 }
798 }
799 return false;
800 }
801 bool VisitStmt(const Stmt *S) {
802 for (auto Child : S->children()) {
803 if (Child && Visit(Child))
804 return true;
805 }
806 return false;
807 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000808 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000809};
810} // namespace
811
Alexey Bataeved09d242014-05-28 05:53:51 +0000812OMPThreadPrivateDecl *
813Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000814 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000815 for (auto &RefExpr : VarList) {
816 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000817 VarDecl *VD = cast<VarDecl>(DE->getDecl());
818 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000819
820 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
821 // A threadprivate variable must not have an incomplete type.
822 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000823 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000824 continue;
825 }
826
827 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
828 // A threadprivate variable must not have a reference type.
829 if (VD->getType()->isReferenceType()) {
830 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000831 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
832 bool IsDecl =
833 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
834 Diag(VD->getLocation(),
835 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
836 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000837 continue;
838 }
839
Richard Smithfd3834f2013-04-13 02:43:54 +0000840 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000841 if (VD->getTLSKind() != VarDecl::TLS_None ||
842 VD->getStorageClass() == SC_Register) {
843 Diag(ILoc, diag::err_omp_var_thread_local)
844 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000845 bool IsDecl =
846 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
847 Diag(VD->getLocation(),
848 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
849 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000850 continue;
851 }
852
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000853 // Check if initial value of threadprivate variable reference variable with
854 // local storage (it is not supported by runtime).
855 if (auto Init = VD->getAnyInitializer()) {
856 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000857 if (Checker.Visit(Init))
858 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000859 }
860
Alexey Bataeved09d242014-05-28 05:53:51 +0000861 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000862 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000863 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
864 Context, SourceRange(Loc, Loc)));
865 if (auto *ML = Context.getASTMutationListener())
866 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000867 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000868 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000869 if (!Vars.empty()) {
870 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
871 Vars);
872 D->setAccess(AS_public);
873 }
874 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000875}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000876
Alexey Bataev7ff55242014-06-19 09:13:45 +0000877static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
878 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
879 bool IsLoopIterVar = false) {
880 if (DVar.RefExpr) {
881 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
882 << getOpenMPClauseName(DVar.CKind);
883 return;
884 }
885 enum {
886 PDSA_StaticMemberShared,
887 PDSA_StaticLocalVarShared,
888 PDSA_LoopIterVarPrivate,
889 PDSA_LoopIterVarLinear,
890 PDSA_LoopIterVarLastprivate,
891 PDSA_ConstVarShared,
892 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000893 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000894 PDSA_LocalVarPrivate,
895 PDSA_Implicit
896 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000897 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000898 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000899 if (IsLoopIterVar) {
900 if (DVar.CKind == OMPC_private)
901 Reason = PDSA_LoopIterVarPrivate;
902 else if (DVar.CKind == OMPC_lastprivate)
903 Reason = PDSA_LoopIterVarLastprivate;
904 else
905 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000906 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
907 Reason = PDSA_TaskVarFirstprivate;
908 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000909 } else if (VD->isStaticLocal())
910 Reason = PDSA_StaticLocalVarShared;
911 else if (VD->isStaticDataMember())
912 Reason = PDSA_StaticMemberShared;
913 else if (VD->isFileVarDecl())
914 Reason = PDSA_GlobalVarShared;
915 else if (VD->getType().isConstant(SemaRef.getASTContext()))
916 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000917 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000918 ReportHint = true;
919 Reason = PDSA_LocalVarPrivate;
920 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000921 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000922 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +0000923 << Reason << ReportHint
924 << getOpenMPDirectiveName(Stack->getCurrentDirective());
925 } else if (DVar.ImplicitDSALoc.isValid()) {
926 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
927 << getOpenMPClauseName(DVar.CKind);
928 }
Alexey Bataev7ff55242014-06-19 09:13:45 +0000929}
930
Alexey Bataev758e55e2013-09-06 18:03:48 +0000931namespace {
932class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
933 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000934 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000935 bool ErrorFound;
936 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000937 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +0000938 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +0000939
Alexey Bataev758e55e2013-09-06 18:03:48 +0000940public:
941 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000942 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000943 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +0000944 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
945 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000946
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000947 auto DVar = Stack->getTopDSA(VD, false);
948 // Check if the variable has explicit DSA set and stop analysis if it so.
949 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000950
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000951 auto ELoc = E->getExprLoc();
952 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000953 // The default(none) clause requires that each variable that is referenced
954 // in the construct, and does not have a predetermined data-sharing
955 // attribute, must have its data-sharing attribute explicitly determined
956 // by being listed in a data-sharing attribute clause.
957 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000958 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +0000959 VarsWithInheritedDSA.count(VD) == 0) {
960 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000961 return;
962 }
963
964 // OpenMP [2.9.3.6, Restrictions, p.2]
965 // A list item that appears in a reduction clause of the innermost
966 // enclosing worksharing or parallel construct may not be accessed in an
967 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000968 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000969 [](OpenMPDirectiveKind K) -> bool {
970 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000971 isOpenMPWorksharingDirective(K) ||
972 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000973 },
974 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000975 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
976 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000977 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
978 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000979 return;
980 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000981
982 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000983 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000984 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000985 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000986 }
987 }
988 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000989 for (auto *C : S->clauses()) {
990 // Skip analysis of arguments of implicitly defined firstprivate clause
991 // for task directives.
992 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
993 for (auto *CC : C->children()) {
994 if (CC)
995 Visit(CC);
996 }
997 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000998 }
999 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001000 for (auto *C : S->children()) {
1001 if (C && !isa<OMPExecutableDirective>(C))
1002 Visit(C);
1003 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001004 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001005
1006 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001007 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001008 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1009 return VarsWithInheritedDSA;
1010 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001011
Alexey Bataev7ff55242014-06-19 09:13:45 +00001012 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1013 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001014};
Alexey Bataeved09d242014-05-28 05:53:51 +00001015} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001016
Alexey Bataevbae9a792014-06-27 10:37:06 +00001017void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001018 switch (DKind) {
1019 case OMPD_parallel: {
1020 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1021 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001022 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001023 std::make_pair(".global_tid.", KmpInt32PtrTy),
1024 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1025 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001026 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001027 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1028 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001029 break;
1030 }
1031 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001032 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001033 std::make_pair(StringRef(), QualType()) // __context with shared vars
1034 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001035 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1036 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001037 break;
1038 }
1039 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001040 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001041 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001042 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001043 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1044 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001045 break;
1046 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001047 case OMPD_for_simd: {
1048 Sema::CapturedParamNameType Params[] = {
1049 std::make_pair(StringRef(), QualType()) // __context with shared vars
1050 };
1051 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1052 Params);
1053 break;
1054 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001055 case OMPD_sections: {
1056 Sema::CapturedParamNameType Params[] = {
1057 std::make_pair(StringRef(), QualType()) // __context with shared vars
1058 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001059 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1060 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001061 break;
1062 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001063 case OMPD_section: {
1064 Sema::CapturedParamNameType Params[] = {
1065 std::make_pair(StringRef(), QualType()) // __context with shared vars
1066 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001067 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1068 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001069 break;
1070 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001071 case OMPD_single: {
1072 Sema::CapturedParamNameType Params[] = {
1073 std::make_pair(StringRef(), QualType()) // __context with shared vars
1074 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001075 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1076 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001077 break;
1078 }
Alexander Musman80c22892014-07-17 08:54:58 +00001079 case OMPD_master: {
1080 Sema::CapturedParamNameType Params[] = {
1081 std::make_pair(StringRef(), QualType()) // __context with shared vars
1082 };
1083 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1084 Params);
1085 break;
1086 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001087 case OMPD_critical: {
1088 Sema::CapturedParamNameType Params[] = {
1089 std::make_pair(StringRef(), QualType()) // __context with shared vars
1090 };
1091 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1092 Params);
1093 break;
1094 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001095 case OMPD_parallel_for: {
1096 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1097 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1098 Sema::CapturedParamNameType Params[] = {
1099 std::make_pair(".global_tid.", KmpInt32PtrTy),
1100 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1101 std::make_pair(StringRef(), QualType()) // __context with shared vars
1102 };
1103 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1104 Params);
1105 break;
1106 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001107 case OMPD_parallel_for_simd: {
1108 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1109 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1110 Sema::CapturedParamNameType Params[] = {
1111 std::make_pair(".global_tid.", KmpInt32PtrTy),
1112 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1113 std::make_pair(StringRef(), QualType()) // __context with shared vars
1114 };
1115 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1116 Params);
1117 break;
1118 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001119 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001120 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1121 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001122 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001123 std::make_pair(".global_tid.", KmpInt32PtrTy),
1124 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001125 std::make_pair(StringRef(), QualType()) // __context with shared vars
1126 };
1127 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1128 Params);
1129 break;
1130 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001131 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001132 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001133 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001134 std::make_pair(".global_tid.", KmpInt32Ty),
1135 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001136 std::make_pair(StringRef(), QualType()) // __context with shared vars
1137 };
1138 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1139 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001140 // Mark this captured region as inlined, because we don't use outlined
1141 // function directly.
1142 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1143 AlwaysInlineAttr::CreateImplicit(
1144 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001145 break;
1146 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001147 case OMPD_ordered: {
1148 Sema::CapturedParamNameType Params[] = {
1149 std::make_pair(StringRef(), QualType()) // __context with shared vars
1150 };
1151 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1152 Params);
1153 break;
1154 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001155 case OMPD_atomic: {
1156 Sema::CapturedParamNameType Params[] = {
1157 std::make_pair(StringRef(), QualType()) // __context with shared vars
1158 };
1159 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1160 Params);
1161 break;
1162 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001163 case OMPD_target: {
1164 Sema::CapturedParamNameType Params[] = {
1165 std::make_pair(StringRef(), QualType()) // __context with shared vars
1166 };
1167 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1168 Params);
1169 break;
1170 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001171 case OMPD_teams: {
1172 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1173 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1174 Sema::CapturedParamNameType Params[] = {
1175 std::make_pair(".global_tid.", KmpInt32PtrTy),
1176 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1177 std::make_pair(StringRef(), QualType()) // __context with shared vars
1178 };
1179 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1180 Params);
1181 break;
1182 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001183 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001184 case OMPD_taskyield:
1185 case OMPD_barrier:
1186 case OMPD_taskwait:
1187 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001188 llvm_unreachable("OpenMP Directive is not allowed");
1189 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001190 llvm_unreachable("Unknown OpenMP directive");
1191 }
1192}
1193
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001194StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1195 ArrayRef<OMPClause *> Clauses) {
1196 if (!S.isUsable()) {
1197 ActOnCapturedRegionError();
1198 return StmtError();
1199 }
1200 // Mark all variables in private list clauses as used in inner region. This is
1201 // required for proper codegen.
1202 for (auto *Clause : Clauses) {
1203 if (isOpenMPPrivate(Clause->getClauseKind())) {
1204 for (auto *VarRef : Clause->children()) {
1205 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001206 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001207 }
1208 }
1209 }
1210 }
1211 return ActOnCapturedRegionEnd(S.get());
1212}
1213
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001214static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1215 OpenMPDirectiveKind CurrentRegion,
1216 const DeclarationNameInfo &CurrentName,
1217 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001218 // Allowed nesting of constructs
1219 // +------------------+-----------------+------------------------------------+
1220 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1221 // +------------------+-----------------+------------------------------------+
1222 // | parallel | parallel | * |
1223 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001224 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001225 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001226 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001227 // | parallel | simd | * |
1228 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001229 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001230 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001231 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001232 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001233 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001234 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001235 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001236 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001237 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001238 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001239 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001240 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001241 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001242 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001243 // +------------------+-----------------+------------------------------------+
1244 // | for | parallel | * |
1245 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001246 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001247 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001248 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001249 // | for | simd | * |
1250 // | for | sections | + |
1251 // | for | section | + |
1252 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001253 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001254 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001255 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001256 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001257 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001258 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001259 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001260 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001261 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001262 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001263 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001264 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001265 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001266 // | master | parallel | * |
1267 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001268 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001269 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001270 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001271 // | master | simd | * |
1272 // | master | sections | + |
1273 // | master | section | + |
1274 // | master | single | + |
1275 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001276 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001277 // | master |parallel sections| * |
1278 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001279 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001280 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001281 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001282 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001283 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001284 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001285 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001286 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001287 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001288 // | critical | parallel | * |
1289 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001290 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001291 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001292 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001293 // | critical | simd | * |
1294 // | critical | sections | + |
1295 // | critical | section | + |
1296 // | critical | single | + |
1297 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001298 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001299 // | critical |parallel sections| * |
1300 // | critical | task | * |
1301 // | critical | taskyield | * |
1302 // | critical | barrier | + |
1303 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001304 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001305 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001306 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001307 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001308 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001309 // | simd | parallel | |
1310 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001311 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001312 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001313 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001314 // | simd | simd | |
1315 // | simd | sections | |
1316 // | simd | section | |
1317 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001318 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001319 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001320 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001321 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001322 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001323 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001324 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001325 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001326 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001327 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001328 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001329 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001330 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001331 // | for simd | parallel | |
1332 // | for simd | for | |
1333 // | for simd | for simd | |
1334 // | for simd | master | |
1335 // | for simd | critical | |
1336 // | for simd | simd | |
1337 // | for simd | sections | |
1338 // | for simd | section | |
1339 // | for simd | single | |
1340 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001341 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001342 // | for simd |parallel sections| |
1343 // | for simd | task | |
1344 // | for simd | taskyield | |
1345 // | for simd | barrier | |
1346 // | for simd | taskwait | |
1347 // | for simd | flush | |
1348 // | for simd | ordered | |
1349 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001350 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001351 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001352 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001353 // | parallel for simd| parallel | |
1354 // | parallel for simd| for | |
1355 // | parallel for simd| for simd | |
1356 // | parallel for simd| master | |
1357 // | parallel for simd| critical | |
1358 // | parallel for simd| simd | |
1359 // | parallel for simd| sections | |
1360 // | parallel for simd| section | |
1361 // | parallel for simd| single | |
1362 // | parallel for simd| parallel for | |
1363 // | parallel for simd|parallel for simd| |
1364 // | parallel for simd|parallel sections| |
1365 // | parallel for simd| task | |
1366 // | parallel for simd| taskyield | |
1367 // | parallel for simd| barrier | |
1368 // | parallel for simd| taskwait | |
1369 // | parallel for simd| flush | |
1370 // | parallel for simd| ordered | |
1371 // | parallel for simd| atomic | |
1372 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001373 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001374 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001375 // | sections | parallel | * |
1376 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001377 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001378 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001379 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001380 // | sections | simd | * |
1381 // | sections | sections | + |
1382 // | sections | section | * |
1383 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001384 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001385 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001386 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001387 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001388 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001389 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001390 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001391 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001392 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001393 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001394 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001395 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001396 // +------------------+-----------------+------------------------------------+
1397 // | section | parallel | * |
1398 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001399 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001400 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001401 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001402 // | section | simd | * |
1403 // | section | sections | + |
1404 // | section | section | + |
1405 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001406 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001407 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001408 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001409 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001410 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001411 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001412 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001413 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001414 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001415 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001416 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001417 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001418 // +------------------+-----------------+------------------------------------+
1419 // | single | parallel | * |
1420 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001421 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001422 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001423 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001424 // | single | simd | * |
1425 // | single | sections | + |
1426 // | single | section | + |
1427 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001428 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001429 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001430 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001431 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001432 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001433 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001434 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001435 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001436 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001437 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001438 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001439 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001440 // +------------------+-----------------+------------------------------------+
1441 // | parallel for | parallel | * |
1442 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001443 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001444 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001445 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001446 // | parallel for | simd | * |
1447 // | parallel for | sections | + |
1448 // | parallel for | section | + |
1449 // | parallel for | single | + |
1450 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001451 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001452 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001453 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001454 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001455 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001456 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001457 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001458 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001459 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001460 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001461 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001462 // +------------------+-----------------+------------------------------------+
1463 // | parallel sections| parallel | * |
1464 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001465 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001466 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001467 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001468 // | parallel sections| simd | * |
1469 // | parallel sections| sections | + |
1470 // | parallel sections| section | * |
1471 // | parallel sections| single | + |
1472 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001473 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001474 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001475 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001476 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001477 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001478 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001479 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001480 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001481 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001482 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001483 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001484 // +------------------+-----------------+------------------------------------+
1485 // | task | parallel | * |
1486 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001487 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001488 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001489 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001490 // | task | simd | * |
1491 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001492 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001493 // | task | single | + |
1494 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001495 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001496 // | task |parallel sections| * |
1497 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001498 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001499 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001500 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001501 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001502 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001503 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001504 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001505 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001506 // +------------------+-----------------+------------------------------------+
1507 // | ordered | parallel | * |
1508 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001509 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001510 // | ordered | master | * |
1511 // | ordered | critical | * |
1512 // | ordered | simd | * |
1513 // | ordered | sections | + |
1514 // | ordered | section | + |
1515 // | ordered | single | + |
1516 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001517 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001518 // | ordered |parallel sections| * |
1519 // | ordered | task | * |
1520 // | ordered | taskyield | * |
1521 // | ordered | barrier | + |
1522 // | ordered | taskwait | * |
1523 // | ordered | flush | * |
1524 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001525 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001526 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001527 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001528 // +------------------+-----------------+------------------------------------+
1529 // | atomic | parallel | |
1530 // | atomic | for | |
1531 // | atomic | for simd | |
1532 // | atomic | master | |
1533 // | atomic | critical | |
1534 // | atomic | simd | |
1535 // | atomic | sections | |
1536 // | atomic | section | |
1537 // | atomic | single | |
1538 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001539 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001540 // | atomic |parallel sections| |
1541 // | atomic | task | |
1542 // | atomic | taskyield | |
1543 // | atomic | barrier | |
1544 // | atomic | taskwait | |
1545 // | atomic | flush | |
1546 // | atomic | ordered | |
1547 // | atomic | atomic | |
1548 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001549 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001550 // +------------------+-----------------+------------------------------------+
1551 // | target | parallel | * |
1552 // | target | for | * |
1553 // | target | for simd | * |
1554 // | target | master | * |
1555 // | target | critical | * |
1556 // | target | simd | * |
1557 // | target | sections | * |
1558 // | target | section | * |
1559 // | target | single | * |
1560 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001561 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001562 // | target |parallel sections| * |
1563 // | target | task | * |
1564 // | target | taskyield | * |
1565 // | target | barrier | * |
1566 // | target | taskwait | * |
1567 // | target | flush | * |
1568 // | target | ordered | * |
1569 // | target | atomic | * |
1570 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001571 // | target | teams | * |
1572 // +------------------+-----------------+------------------------------------+
1573 // | teams | parallel | * |
1574 // | teams | for | + |
1575 // | teams | for simd | + |
1576 // | teams | master | + |
1577 // | teams | critical | + |
1578 // | teams | simd | + |
1579 // | teams | sections | + |
1580 // | teams | section | + |
1581 // | teams | single | + |
1582 // | teams | parallel for | * |
1583 // | teams |parallel for simd| * |
1584 // | teams |parallel sections| * |
1585 // | teams | task | + |
1586 // | teams | taskyield | + |
1587 // | teams | barrier | + |
1588 // | teams | taskwait | + |
1589 // | teams | flush | + |
1590 // | teams | ordered | + |
1591 // | teams | atomic | + |
1592 // | teams | target | + |
1593 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001594 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001595 if (Stack->getCurScope()) {
1596 auto ParentRegion = Stack->getParentDirective();
1597 bool NestingProhibited = false;
1598 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001599 enum {
1600 NoRecommend,
1601 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001602 ShouldBeInOrderedRegion,
1603 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001604 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001605 if (isOpenMPSimdDirective(ParentRegion)) {
1606 // OpenMP [2.16, Nesting of Regions]
1607 // OpenMP constructs may not be nested inside a simd region.
1608 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1609 return true;
1610 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001611 if (ParentRegion == OMPD_atomic) {
1612 // OpenMP [2.16, Nesting of Regions]
1613 // OpenMP constructs may not be nested inside an atomic region.
1614 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1615 return true;
1616 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001617 if (CurrentRegion == OMPD_section) {
1618 // OpenMP [2.7.2, sections Construct, Restrictions]
1619 // Orphaned section directives are prohibited. That is, the section
1620 // directives must appear within the sections construct and must not be
1621 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001622 if (ParentRegion != OMPD_sections &&
1623 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001624 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1625 << (ParentRegion != OMPD_unknown)
1626 << getOpenMPDirectiveName(ParentRegion);
1627 return true;
1628 }
1629 return false;
1630 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001631 // Allow some constructs to be orphaned (they could be used in functions,
1632 // called from OpenMP regions with the required preconditions).
1633 if (ParentRegion == OMPD_unknown)
1634 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001635 if (CurrentRegion == OMPD_master) {
1636 // OpenMP [2.16, Nesting of Regions]
1637 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001638 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001639 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1640 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001641 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1642 // OpenMP [2.16, Nesting of Regions]
1643 // A critical region may not be nested (closely or otherwise) inside a
1644 // critical region with the same name. Note that this restriction is not
1645 // sufficient to prevent deadlock.
1646 SourceLocation PreviousCriticalLoc;
1647 bool DeadLock =
1648 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1649 OpenMPDirectiveKind K,
1650 const DeclarationNameInfo &DNI,
1651 SourceLocation Loc)
1652 ->bool {
1653 if (K == OMPD_critical &&
1654 DNI.getName() == CurrentName.getName()) {
1655 PreviousCriticalLoc = Loc;
1656 return true;
1657 } else
1658 return false;
1659 },
1660 false /* skip top directive */);
1661 if (DeadLock) {
1662 SemaRef.Diag(StartLoc,
1663 diag::err_omp_prohibited_region_critical_same_name)
1664 << CurrentName.getName();
1665 if (PreviousCriticalLoc.isValid())
1666 SemaRef.Diag(PreviousCriticalLoc,
1667 diag::note_omp_previous_critical_region);
1668 return true;
1669 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001670 } else if (CurrentRegion == OMPD_barrier) {
1671 // OpenMP [2.16, Nesting of Regions]
1672 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001673 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001674 NestingProhibited =
1675 isOpenMPWorksharingDirective(ParentRegion) ||
1676 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1677 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001678 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001679 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001680 // OpenMP [2.16, Nesting of Regions]
1681 // A worksharing region may not be closely nested inside a worksharing,
1682 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001683 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001684 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001685 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1686 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1687 Recommend = ShouldBeInParallelRegion;
1688 } else if (CurrentRegion == OMPD_ordered) {
1689 // OpenMP [2.16, Nesting of Regions]
1690 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001691 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001692 // An ordered region must be closely nested inside a loop region (or
1693 // parallel loop region) with an ordered clause.
1694 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001695 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001696 !Stack->isParentOrderedRegion();
1697 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001698 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1699 // OpenMP [2.16, Nesting of Regions]
1700 // If specified, a teams construct must be contained within a target
1701 // construct.
1702 NestingProhibited = ParentRegion != OMPD_target;
1703 Recommend = ShouldBeInTargetRegion;
1704 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1705 }
1706 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1707 // OpenMP [2.16, Nesting of Regions]
1708 // distribute, parallel, parallel sections, parallel workshare, and the
1709 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1710 // constructs that can be closely nested in the teams region.
1711 // TODO: add distribute directive.
1712 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1713 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001714 }
1715 if (NestingProhibited) {
1716 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001717 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1718 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001719 return true;
1720 }
1721 }
1722 return false;
1723}
1724
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001725StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001726 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001727 ArrayRef<OMPClause *> Clauses,
1728 Stmt *AStmt,
1729 SourceLocation StartLoc,
1730 SourceLocation EndLoc) {
1731 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001732 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001733 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001734
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001735 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001736 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001737 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001738 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001739 if (AStmt) {
1740 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1741
1742 // Check default data sharing attributes for referenced variables.
1743 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1744 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1745 if (DSAChecker.isErrorFound())
1746 return StmtError();
1747 // Generate list of implicitly defined firstprivate variables.
1748 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001749
1750 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1751 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1752 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1753 SourceLocation(), SourceLocation())) {
1754 ClausesWithImplicit.push_back(Implicit);
1755 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1756 DSAChecker.getImplicitFirstprivate().size();
1757 } else
1758 ErrorFound = true;
1759 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001760 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001761
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001762 switch (Kind) {
1763 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001764 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1765 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001766 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001767 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001768 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1769 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001770 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001771 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001772 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1773 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001774 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001775 case OMPD_for_simd:
1776 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1777 EndLoc, VarsWithInheritedDSA);
1778 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001779 case OMPD_sections:
1780 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1781 EndLoc);
1782 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001783 case OMPD_section:
1784 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001785 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001786 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1787 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001788 case OMPD_single:
1789 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1790 EndLoc);
1791 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001792 case OMPD_master:
1793 assert(ClausesWithImplicit.empty() &&
1794 "No clauses are allowed for 'omp master' directive");
1795 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1796 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001797 case OMPD_critical:
1798 assert(ClausesWithImplicit.empty() &&
1799 "No clauses are allowed for 'omp critical' directive");
1800 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1801 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001802 case OMPD_parallel_for:
1803 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1804 EndLoc, VarsWithInheritedDSA);
1805 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001806 case OMPD_parallel_for_simd:
1807 Res = ActOnOpenMPParallelForSimdDirective(
1808 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1809 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001810 case OMPD_parallel_sections:
1811 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1812 StartLoc, EndLoc);
1813 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001814 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001815 Res =
1816 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1817 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001818 case OMPD_taskyield:
1819 assert(ClausesWithImplicit.empty() &&
1820 "No clauses are allowed for 'omp taskyield' directive");
1821 assert(AStmt == nullptr &&
1822 "No associated statement allowed for 'omp taskyield' directive");
1823 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1824 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001825 case OMPD_barrier:
1826 assert(ClausesWithImplicit.empty() &&
1827 "No clauses are allowed for 'omp barrier' directive");
1828 assert(AStmt == nullptr &&
1829 "No associated statement allowed for 'omp barrier' directive");
1830 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1831 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001832 case OMPD_taskwait:
1833 assert(ClausesWithImplicit.empty() &&
1834 "No clauses are allowed for 'omp taskwait' directive");
1835 assert(AStmt == nullptr &&
1836 "No associated statement allowed for 'omp taskwait' directive");
1837 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1838 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001839 case OMPD_flush:
1840 assert(AStmt == nullptr &&
1841 "No associated statement allowed for 'omp flush' directive");
1842 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1843 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001844 case OMPD_ordered:
1845 assert(ClausesWithImplicit.empty() &&
1846 "No clauses are allowed for 'omp ordered' directive");
1847 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1848 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001849 case OMPD_atomic:
1850 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1851 EndLoc);
1852 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001853 case OMPD_teams:
1854 Res =
1855 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1856 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001857 case OMPD_target:
1858 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1859 EndLoc);
1860 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001861 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001862 llvm_unreachable("OpenMP Directive is not allowed");
1863 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001864 llvm_unreachable("Unknown OpenMP directive");
1865 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001866
Alexey Bataev4acb8592014-07-07 13:01:15 +00001867 for (auto P : VarsWithInheritedDSA) {
1868 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1869 << P.first << P.second->getSourceRange();
1870 }
1871 if (!VarsWithInheritedDSA.empty())
1872 return StmtError();
1873
Alexey Bataeved09d242014-05-28 05:53:51 +00001874 if (ErrorFound)
1875 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001876 return Res;
1877}
1878
1879StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1880 Stmt *AStmt,
1881 SourceLocation StartLoc,
1882 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001883 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1884 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1885 // 1.2.2 OpenMP Language Terminology
1886 // Structured block - An executable statement with a single entry at the
1887 // top and a single exit at the bottom.
1888 // The point of exit cannot be a branch out of the structured block.
1889 // longjmp() and throw() must not violate the entry/exit criteria.
1890 CS->getCapturedDecl()->setNothrow();
1891
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001892 getCurFunction()->setHasBranchProtectedScope();
1893
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001894 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1895 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001896}
1897
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001898namespace {
1899/// \brief Helper class for checking canonical form of the OpenMP loops and
1900/// extracting iteration space of each loop in the loop nest, that will be used
1901/// for IR generation.
1902class OpenMPIterationSpaceChecker {
1903 /// \brief Reference to Sema.
1904 Sema &SemaRef;
1905 /// \brief A location for diagnostics (when there is no some better location).
1906 SourceLocation DefaultLoc;
1907 /// \brief A location for diagnostics (when increment is not compatible).
1908 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001909 /// \brief A source location for referring to loop init later.
1910 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001911 /// \brief A source location for referring to condition later.
1912 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001913 /// \brief A source location for referring to increment later.
1914 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001915 /// \brief Loop variable.
1916 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001917 /// \brief Reference to loop variable.
1918 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001919 /// \brief Lower bound (initializer for the var).
1920 Expr *LB;
1921 /// \brief Upper bound.
1922 Expr *UB;
1923 /// \brief Loop step (increment).
1924 Expr *Step;
1925 /// \brief This flag is true when condition is one of:
1926 /// Var < UB
1927 /// Var <= UB
1928 /// UB > Var
1929 /// UB >= Var
1930 bool TestIsLessOp;
1931 /// \brief This flag is true when condition is strict ( < or > ).
1932 bool TestIsStrictOp;
1933 /// \brief This flag is true when step is subtracted on each iteration.
1934 bool SubtractStep;
1935
1936public:
1937 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1938 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00001939 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1940 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001941 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1942 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001943 /// \brief Check init-expr for canonical loop form and save loop counter
1944 /// variable - #Var and its initialization value - #LB.
1945 bool CheckInit(Stmt *S);
1946 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1947 /// for less/greater and for strict/non-strict comparison.
1948 bool CheckCond(Expr *S);
1949 /// \brief Check incr-expr for canonical loop form and return true if it
1950 /// does not conform, otherwise save loop step (#Step).
1951 bool CheckInc(Expr *S);
1952 /// \brief Return the loop counter variable.
1953 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001954 /// \brief Return the reference expression to loop counter variable.
1955 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001956 /// \brief Source range of the loop init.
1957 SourceRange GetInitSrcRange() const { return InitSrcRange; }
1958 /// \brief Source range of the loop condition.
1959 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1960 /// \brief Source range of the loop increment.
1961 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1962 /// \brief True if the step should be subtracted.
1963 bool ShouldSubtractStep() const { return SubtractStep; }
1964 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00001965 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001966 /// \brief Build reference expression to the counter be used for codegen.
1967 Expr *BuildCounterVar() const;
1968 /// \brief Build initization of the counter be used for codegen.
1969 Expr *BuildCounterInit() const;
1970 /// \brief Build step of the counter be used for codegen.
1971 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001972 /// \brief Return true if any expression is dependent.
1973 bool Dependent() const;
1974
1975private:
1976 /// \brief Check the right-hand side of an assignment in the increment
1977 /// expression.
1978 bool CheckIncRHS(Expr *RHS);
1979 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001980 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001981 /// \brief Helper to set upper bound.
1982 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1983 const SourceLocation &SL);
1984 /// \brief Helper to set loop increment.
1985 bool SetStep(Expr *NewStep, bool Subtract);
1986};
1987
1988bool OpenMPIterationSpaceChecker::Dependent() const {
1989 if (!Var) {
1990 assert(!LB && !UB && !Step);
1991 return false;
1992 }
1993 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1994 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1995}
1996
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001997bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
1998 DeclRefExpr *NewVarRefExpr,
1999 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002000 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002001 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2002 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002003 if (!NewVar || !NewLB)
2004 return true;
2005 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002006 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002007 LB = NewLB;
2008 return false;
2009}
2010
2011bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2012 const SourceRange &SR,
2013 const SourceLocation &SL) {
2014 // State consistency checking to ensure correct usage.
2015 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2016 !TestIsLessOp && !TestIsStrictOp);
2017 if (!NewUB)
2018 return true;
2019 UB = NewUB;
2020 TestIsLessOp = LessOp;
2021 TestIsStrictOp = StrictOp;
2022 ConditionSrcRange = SR;
2023 ConditionLoc = SL;
2024 return false;
2025}
2026
2027bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2028 // State consistency checking to ensure correct usage.
2029 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2030 if (!NewStep)
2031 return true;
2032 if (!NewStep->isValueDependent()) {
2033 // Check that the step is integer expression.
2034 SourceLocation StepLoc = NewStep->getLocStart();
2035 ExprResult Val =
2036 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2037 if (Val.isInvalid())
2038 return true;
2039 NewStep = Val.get();
2040
2041 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2042 // If test-expr is of form var relational-op b and relational-op is < or
2043 // <= then incr-expr must cause var to increase on each iteration of the
2044 // loop. If test-expr is of form var relational-op b and relational-op is
2045 // > or >= then incr-expr must cause var to decrease on each iteration of
2046 // the loop.
2047 // If test-expr is of form b relational-op var and relational-op is < or
2048 // <= then incr-expr must cause var to decrease on each iteration of the
2049 // loop. If test-expr is of form b relational-op var and relational-op is
2050 // > or >= then incr-expr must cause var to increase on each iteration of
2051 // the loop.
2052 llvm::APSInt Result;
2053 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2054 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2055 bool IsConstNeg =
2056 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002057 bool IsConstPos =
2058 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002059 bool IsConstZero = IsConstant && !Result.getBoolValue();
2060 if (UB && (IsConstZero ||
2061 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002062 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002063 SemaRef.Diag(NewStep->getExprLoc(),
2064 diag::err_omp_loop_incr_not_compatible)
2065 << Var << TestIsLessOp << NewStep->getSourceRange();
2066 SemaRef.Diag(ConditionLoc,
2067 diag::note_omp_loop_cond_requres_compatible_incr)
2068 << TestIsLessOp << ConditionSrcRange;
2069 return true;
2070 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002071 if (TestIsLessOp == Subtract) {
2072 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2073 NewStep).get();
2074 Subtract = !Subtract;
2075 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002076 }
2077
2078 Step = NewStep;
2079 SubtractStep = Subtract;
2080 return false;
2081}
2082
2083bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2084 // Check init-expr for canonical loop form and save loop counter
2085 // variable - #Var and its initialization value - #LB.
2086 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2087 // var = lb
2088 // integer-type var = lb
2089 // random-access-iterator-type var = lb
2090 // pointer-type var = lb
2091 //
2092 if (!S) {
2093 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2094 return true;
2095 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002096 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002097 if (Expr *E = dyn_cast<Expr>(S))
2098 S = E->IgnoreParens();
2099 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2100 if (BO->getOpcode() == BO_Assign)
2101 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002102 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002103 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002104 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2105 if (DS->isSingleDecl()) {
2106 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2107 if (Var->hasInit()) {
2108 // Accept non-canonical init form here but emit ext. warning.
2109 if (Var->getInitStyle() != VarDecl::CInit)
2110 SemaRef.Diag(S->getLocStart(),
2111 diag::ext_omp_loop_not_canonical_init)
2112 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002113 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002114 }
2115 }
2116 }
2117 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2118 if (CE->getOperator() == OO_Equal)
2119 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002120 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2121 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002122
2123 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2124 << S->getSourceRange();
2125 return true;
2126}
2127
Alexey Bataev23b69422014-06-18 07:08:49 +00002128/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002129/// variable (which may be the loop variable) if possible.
2130static const VarDecl *GetInitVarDecl(const Expr *E) {
2131 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002132 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002133 E = E->IgnoreParenImpCasts();
2134 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2135 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2136 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2137 CE->getArg(0) != nullptr)
2138 E = CE->getArg(0)->IgnoreParenImpCasts();
2139 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2140 if (!DRE)
2141 return nullptr;
2142 return dyn_cast<VarDecl>(DRE->getDecl());
2143}
2144
2145bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2146 // Check test-expr for canonical form, save upper-bound UB, flags for
2147 // less/greater and for strict/non-strict comparison.
2148 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2149 // var relational-op b
2150 // b relational-op var
2151 //
2152 if (!S) {
2153 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2154 return true;
2155 }
2156 S = S->IgnoreParenImpCasts();
2157 SourceLocation CondLoc = S->getLocStart();
2158 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2159 if (BO->isRelationalOp()) {
2160 if (GetInitVarDecl(BO->getLHS()) == Var)
2161 return SetUB(BO->getRHS(),
2162 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2163 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2164 BO->getSourceRange(), BO->getOperatorLoc());
2165 if (GetInitVarDecl(BO->getRHS()) == Var)
2166 return SetUB(BO->getLHS(),
2167 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2168 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2169 BO->getSourceRange(), BO->getOperatorLoc());
2170 }
2171 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2172 if (CE->getNumArgs() == 2) {
2173 auto Op = CE->getOperator();
2174 switch (Op) {
2175 case OO_Greater:
2176 case OO_GreaterEqual:
2177 case OO_Less:
2178 case OO_LessEqual:
2179 if (GetInitVarDecl(CE->getArg(0)) == Var)
2180 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2181 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2182 CE->getOperatorLoc());
2183 if (GetInitVarDecl(CE->getArg(1)) == Var)
2184 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2185 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2186 CE->getOperatorLoc());
2187 break;
2188 default:
2189 break;
2190 }
2191 }
2192 }
2193 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2194 << S->getSourceRange() << Var;
2195 return true;
2196}
2197
2198bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2199 // RHS of canonical loop form increment can be:
2200 // var + incr
2201 // incr + var
2202 // var - incr
2203 //
2204 RHS = RHS->IgnoreParenImpCasts();
2205 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2206 if (BO->isAdditiveOp()) {
2207 bool IsAdd = BO->getOpcode() == BO_Add;
2208 if (GetInitVarDecl(BO->getLHS()) == Var)
2209 return SetStep(BO->getRHS(), !IsAdd);
2210 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2211 return SetStep(BO->getLHS(), false);
2212 }
2213 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2214 bool IsAdd = CE->getOperator() == OO_Plus;
2215 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2216 if (GetInitVarDecl(CE->getArg(0)) == Var)
2217 return SetStep(CE->getArg(1), !IsAdd);
2218 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2219 return SetStep(CE->getArg(0), false);
2220 }
2221 }
2222 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2223 << RHS->getSourceRange() << Var;
2224 return true;
2225}
2226
2227bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2228 // Check incr-expr for canonical loop form and return true if it
2229 // does not conform.
2230 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2231 // ++var
2232 // var++
2233 // --var
2234 // var--
2235 // var += incr
2236 // var -= incr
2237 // var = var + incr
2238 // var = incr + var
2239 // var = var - incr
2240 //
2241 if (!S) {
2242 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2243 return true;
2244 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002245 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002246 S = S->IgnoreParens();
2247 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2248 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2249 return SetStep(
2250 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2251 (UO->isDecrementOp() ? -1 : 1)).get(),
2252 false);
2253 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2254 switch (BO->getOpcode()) {
2255 case BO_AddAssign:
2256 case BO_SubAssign:
2257 if (GetInitVarDecl(BO->getLHS()) == Var)
2258 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2259 break;
2260 case BO_Assign:
2261 if (GetInitVarDecl(BO->getLHS()) == Var)
2262 return CheckIncRHS(BO->getRHS());
2263 break;
2264 default:
2265 break;
2266 }
2267 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2268 switch (CE->getOperator()) {
2269 case OO_PlusPlus:
2270 case OO_MinusMinus:
2271 if (GetInitVarDecl(CE->getArg(0)) == Var)
2272 return SetStep(
2273 SemaRef.ActOnIntegerConstant(
2274 CE->getLocStart(),
2275 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2276 false);
2277 break;
2278 case OO_PlusEqual:
2279 case OO_MinusEqual:
2280 if (GetInitVarDecl(CE->getArg(0)) == Var)
2281 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2282 break;
2283 case OO_Equal:
2284 if (GetInitVarDecl(CE->getArg(0)) == Var)
2285 return CheckIncRHS(CE->getArg(1));
2286 break;
2287 default:
2288 break;
2289 }
2290 }
2291 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2292 << S->getSourceRange() << Var;
2293 return true;
2294}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002295
2296/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002297Expr *
2298OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2299 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002300 ExprResult Diff;
2301 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2302 SemaRef.getLangOpts().CPlusPlus) {
2303 // Upper - Lower
2304 Expr *Upper = TestIsLessOp ? UB : LB;
2305 Expr *Lower = TestIsLessOp ? LB : UB;
2306
2307 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2308
2309 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2310 // BuildBinOp already emitted error, this one is to point user to upper
2311 // and lower bound, and to tell what is passed to 'operator-'.
2312 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2313 << Upper->getSourceRange() << Lower->getSourceRange();
2314 return nullptr;
2315 }
2316 }
2317
2318 if (!Diff.isUsable())
2319 return nullptr;
2320
2321 // Upper - Lower [- 1]
2322 if (TestIsStrictOp)
2323 Diff = SemaRef.BuildBinOp(
2324 S, DefaultLoc, BO_Sub, Diff.get(),
2325 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2326 if (!Diff.isUsable())
2327 return nullptr;
2328
2329 // Upper - Lower [- 1] + Step
2330 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2331 Step->IgnoreImplicit());
2332 if (!Diff.isUsable())
2333 return nullptr;
2334
2335 // Parentheses (for dumping/debugging purposes only).
2336 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2337 if (!Diff.isUsable())
2338 return nullptr;
2339
2340 // (Upper - Lower [- 1] + Step) / Step
2341 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2342 Step->IgnoreImplicit());
2343 if (!Diff.isUsable())
2344 return nullptr;
2345
Alexander Musman174b3ca2014-10-06 11:16:29 +00002346 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2347 if (LimitedType) {
2348 auto &C = SemaRef.Context;
2349 QualType Type = Diff.get()->getType();
2350 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2351 if (NewSize != C.getTypeSize(Type)) {
2352 if (NewSize < C.getTypeSize(Type)) {
2353 assert(NewSize == 64 && "incorrect loop var size");
2354 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2355 << InitSrcRange << ConditionSrcRange;
2356 }
2357 QualType NewType = C.getIntTypeForBitwidth(
2358 NewSize, Type->hasSignedIntegerRepresentation());
2359 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2360 Sema::AA_Converting, true);
2361 if (!Diff.isUsable())
2362 return nullptr;
2363 }
2364 }
2365
Alexander Musmana5f070a2014-10-01 06:03:56 +00002366 return Diff.get();
2367}
2368
2369/// \brief Build reference expression to the counter be used for codegen.
2370Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2371 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2372 GetIncrementSrcRange().getBegin(), Var, false,
2373 DefaultLoc, Var->getType(), VK_LValue);
2374}
2375
2376/// \brief Build initization of the counter be used for codegen.
2377Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2378
2379/// \brief Build step of the counter be used for codegen.
2380Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2381
2382/// \brief Iteration space of a single for loop.
2383struct LoopIterationSpace {
2384 /// \brief This expression calculates the number of iterations in the loop.
2385 /// It is always possible to calculate it before starting the loop.
2386 Expr *NumIterations;
2387 /// \brief The loop counter variable.
2388 Expr *CounterVar;
2389 /// \brief This is initializer for the initial value of #CounterVar.
2390 Expr *CounterInit;
2391 /// \brief This is step for the #CounterVar used to generate its update:
2392 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2393 Expr *CounterStep;
2394 /// \brief Should step be subtracted?
2395 bool Subtract;
2396 /// \brief Source range of the loop init.
2397 SourceRange InitSrcRange;
2398 /// \brief Source range of the loop condition.
2399 SourceRange CondSrcRange;
2400 /// \brief Source range of the loop increment.
2401 SourceRange IncSrcRange;
2402};
2403
Alexey Bataev23b69422014-06-18 07:08:49 +00002404} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002405
2406/// \brief Called on a for stmt to check and extract its iteration space
2407/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002408static bool CheckOpenMPIterationSpace(
2409 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2410 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2411 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002412 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2413 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002414 // OpenMP [2.6, Canonical Loop Form]
2415 // for (init-expr; test-expr; incr-expr) structured-block
2416 auto For = dyn_cast_or_null<ForStmt>(S);
2417 if (!For) {
2418 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002419 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2420 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2421 << CurrentNestedLoopCount;
2422 if (NestedLoopCount > 1)
2423 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2424 diag::note_omp_collapse_expr)
2425 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002426 return true;
2427 }
2428 assert(For->getBody());
2429
2430 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2431
2432 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002433 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002434 if (ISC.CheckInit(Init)) {
2435 return true;
2436 }
2437
2438 bool HasErrors = false;
2439
2440 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002441 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002442
2443 // OpenMP [2.6, Canonical Loop Form]
2444 // Var is one of the following:
2445 // A variable of signed or unsigned integer type.
2446 // For C++, a variable of a random access iterator type.
2447 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002448 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002449 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2450 !VarType->isPointerType() &&
2451 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2452 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2453 << SemaRef.getLangOpts().CPlusPlus;
2454 HasErrors = true;
2455 }
2456
Alexey Bataev4acb8592014-07-07 13:01:15 +00002457 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2458 // Construct
2459 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2460 // parallel for construct is (are) private.
2461 // The loop iteration variable in the associated for-loop of a simd construct
2462 // with just one associated for-loop is linear with a constant-linear-step
2463 // that is the increment of the associated for-loop.
2464 // Exclude loop var from the list of variables with implicitly defined data
2465 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002466 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002467
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002468 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2469 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002470 // The loop iteration variable in the associated for-loop of a simd construct
2471 // with just one associated for-loop may be listed in a linear clause with a
2472 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002473 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2474 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002475 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002476 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2477 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2478 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002479 auto PredeterminedCKind =
2480 isOpenMPSimdDirective(DKind)
2481 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2482 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002483 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002484 DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002485 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2486 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2487 DVar.CKind != OMPC_lastprivate)) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00002488 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002489 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002490 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2491 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002492 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002493 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002494 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002495 // Make the loop iteration variable private (for worksharing constructs),
2496 // linear (for simd directives with the only one associated loop) or
2497 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002498 // FIXME: the next check and error message must be removed once the
2499 // capturing of global variables in loops is fixed.
2500 if (DVar.CKind == OMPC_unknown)
2501 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2502 /*FromParent=*/false);
2503 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2504 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2505 << getOpenMPClauseName(PredeterminedCKind)
2506 << getOpenMPDirectiveName(DKind);
2507 HasErrors = true;
2508 } else
2509 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002510 }
2511
Alexey Bataev7ff55242014-06-19 09:13:45 +00002512 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002513
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002514 // Check test-expr.
2515 HasErrors |= ISC.CheckCond(For->getCond());
2516
2517 // Check incr-expr.
2518 HasErrors |= ISC.CheckInc(For->getInc());
2519
Alexander Musmana5f070a2014-10-01 06:03:56 +00002520 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002521 return HasErrors;
2522
Alexander Musmana5f070a2014-10-01 06:03:56 +00002523 // Build the loop's iteration space representation.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002524 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2525 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002526 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2527 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2528 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2529 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2530 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2531 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2532 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2533
2534 HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
2535 ResultIterSpace.CounterVar == nullptr ||
2536 ResultIterSpace.CounterInit == nullptr ||
2537 ResultIterSpace.CounterStep == nullptr);
2538
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002539 return HasErrors;
2540}
2541
Alexander Musmana5f070a2014-10-01 06:03:56 +00002542/// \brief Build a variable declaration for OpenMP loop iteration variable.
2543static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2544 StringRef Name) {
2545 DeclContext *DC = SemaRef.CurContext;
2546 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2547 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2548 VarDecl *Decl =
2549 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2550 Decl->setImplicit();
2551 return Decl;
2552}
2553
2554/// \brief Build 'VarRef = Start + Iter * Step'.
2555static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2556 SourceLocation Loc, ExprResult VarRef,
2557 ExprResult Start, ExprResult Iter,
2558 ExprResult Step, bool Subtract) {
2559 // Add parentheses (for debugging purposes only).
2560 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2561 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2562 !Step.isUsable())
2563 return ExprError();
2564
2565 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2566 Step.get()->IgnoreImplicit());
2567 if (!Update.isUsable())
2568 return ExprError();
2569
2570 // Build 'VarRef = Start + Iter * Step'.
2571 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2572 Start.get()->IgnoreImplicit(), Update.get());
2573 if (!Update.isUsable())
2574 return ExprError();
2575
2576 Update = SemaRef.PerformImplicitConversion(
2577 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2578 if (!Update.isUsable())
2579 return ExprError();
2580
2581 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2582 return Update;
2583}
2584
2585/// \brief Convert integer expression \a E to make it have at least \a Bits
2586/// bits.
2587static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2588 Sema &SemaRef) {
2589 if (E == nullptr)
2590 return ExprError();
2591 auto &C = SemaRef.Context;
2592 QualType OldType = E->getType();
2593 unsigned HasBits = C.getTypeSize(OldType);
2594 if (HasBits >= Bits)
2595 return ExprResult(E);
2596 // OK to convert to signed, because new type has more bits than old.
2597 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2598 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2599 true);
2600}
2601
2602/// \brief Check if the given expression \a E is a constant integer that fits
2603/// into \a Bits bits.
2604static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2605 if (E == nullptr)
2606 return false;
2607 llvm::APSInt Result;
2608 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2609 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2610 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002611}
2612
2613/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002614/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2615/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002616static unsigned
2617CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2618 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002619 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002620 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002621 unsigned NestedLoopCount = 1;
2622 if (NestedLoopCountExpr) {
2623 // Found 'collapse' clause - calculate collapse number.
2624 llvm::APSInt Result;
2625 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2626 NestedLoopCount = Result.getLimitedValue();
2627 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002628 // This is helper routine for loop directives (e.g., 'for', 'simd',
2629 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002630 SmallVector<LoopIterationSpace, 4> IterSpaces;
2631 IterSpaces.resize(NestedLoopCount);
2632 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002633 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002634 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002635 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002636 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002637 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002638 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002639 // OpenMP [2.8.1, simd construct, Restrictions]
2640 // All loops associated with the construct must be perfectly nested; that
2641 // is, there must be no intervening code nor any OpenMP directive between
2642 // any two loops.
2643 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002644 }
2645
Alexander Musmana5f070a2014-10-01 06:03:56 +00002646 Built.clear(/* size */ NestedLoopCount);
2647
2648 if (SemaRef.CurContext->isDependentContext())
2649 return NestedLoopCount;
2650
2651 // An example of what is generated for the following code:
2652 //
2653 // #pragma omp simd collapse(2)
2654 // for (i = 0; i < NI; ++i)
2655 // for (j = J0; j < NJ; j+=2) {
2656 // <loop body>
2657 // }
2658 //
2659 // We generate the code below.
2660 // Note: the loop body may be outlined in CodeGen.
2661 // Note: some counters may be C++ classes, operator- is used to find number of
2662 // iterations and operator+= to calculate counter value.
2663 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2664 // or i64 is currently supported).
2665 //
2666 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2667 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2668 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2669 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2670 // // similar updates for vars in clauses (e.g. 'linear')
2671 // <loop body (using local i and j)>
2672 // }
2673 // i = NI; // assign final values of counters
2674 // j = NJ;
2675 //
2676
2677 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2678 // the iteration counts of the collapsed for loops.
2679 auto N0 = IterSpaces[0].NumIterations;
2680 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2681 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2682
2683 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2684 return NestedLoopCount;
2685
2686 auto &C = SemaRef.Context;
2687 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2688
2689 Scope *CurScope = DSA.getCurScope();
2690 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2691 auto N = IterSpaces[Cnt].NumIterations;
2692 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2693 if (LastIteration32.isUsable())
2694 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2695 LastIteration32.get(), N);
2696 if (LastIteration64.isUsable())
2697 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2698 LastIteration64.get(), N);
2699 }
2700
2701 // Choose either the 32-bit or 64-bit version.
2702 ExprResult LastIteration = LastIteration64;
2703 if (LastIteration32.isUsable() &&
2704 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2705 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2706 FitsInto(
2707 32 /* Bits */,
2708 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2709 LastIteration64.get(), SemaRef)))
2710 LastIteration = LastIteration32;
2711
2712 if (!LastIteration.isUsable())
2713 return 0;
2714
2715 // Save the number of iterations.
2716 ExprResult NumIterations = LastIteration;
2717 {
2718 LastIteration = SemaRef.BuildBinOp(
2719 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2720 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2721 if (!LastIteration.isUsable())
2722 return 0;
2723 }
2724
2725 // Calculate the last iteration number beforehand instead of doing this on
2726 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2727 llvm::APSInt Result;
2728 bool IsConstant =
2729 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2730 ExprResult CalcLastIteration;
2731 if (!IsConstant) {
2732 SourceLocation SaveLoc;
2733 VarDecl *SaveVar =
2734 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2735 ".omp.last.iteration");
2736 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2737 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2738 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2739 SaveRef.get(), LastIteration.get());
2740 LastIteration = SaveRef;
2741
2742 // Prepare SaveRef + 1.
2743 NumIterations = SemaRef.BuildBinOp(
2744 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2745 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2746 if (!NumIterations.isUsable())
2747 return 0;
2748 }
2749
2750 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2751
2752 // Precondition tests if there is at least one iteration (LastIteration > 0).
2753 ExprResult PreCond = SemaRef.BuildBinOp(
2754 CurScope, InitLoc, BO_GT, LastIteration.get(),
2755 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2756
Alexander Musmanc6388682014-12-15 07:07:06 +00002757 QualType VType = LastIteration.get()->getType();
2758 // Build variables passed into runtime, nesessary for worksharing directives.
2759 ExprResult LB, UB, IL, ST, EUB;
2760 if (isOpenMPWorksharingDirective(DKind)) {
2761 // Lower bound variable, initialized with zero.
2762 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2763 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2764 SemaRef.AddInitializerToDecl(
2765 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2766 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2767
2768 // Upper bound variable, initialized with last iteration number.
2769 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2770 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2771 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2772 /*DirectInit*/ false,
2773 /*TypeMayContainAuto*/ false);
2774
2775 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2776 // This will be used to implement clause 'lastprivate'.
2777 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2778 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2779 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2780 SemaRef.AddInitializerToDecl(
2781 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2782 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2783
2784 // Stride variable returned by runtime (we initialize it to 1 by default).
2785 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2786 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2787 SemaRef.AddInitializerToDecl(
2788 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2789 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2790
2791 // Build expression: UB = min(UB, LastIteration)
2792 // It is nesessary for CodeGen of directives with static scheduling.
2793 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2794 UB.get(), LastIteration.get());
2795 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2796 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2797 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2798 CondOp.get());
2799 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2800 }
2801
2802 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002803 ExprResult IV;
2804 ExprResult Init;
2805 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002806 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2807 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2808 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2809 ? LB.get()
2810 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2811 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2812 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002813 }
2814
Alexander Musmanc6388682014-12-15 07:07:06 +00002815 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002816 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002817 ExprResult Cond =
2818 isOpenMPWorksharingDirective(DKind)
2819 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2820 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2821 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002822 // Loop condition with 1 iteration separated (IV < LastIteration)
2823 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2824 IV.get(), LastIteration.get());
2825
2826 // Loop increment (IV = IV + 1)
2827 SourceLocation IncLoc;
2828 ExprResult Inc =
2829 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2830 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2831 if (!Inc.isUsable())
2832 return 0;
2833 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002834 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2835 if (!Inc.isUsable())
2836 return 0;
2837
2838 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2839 // Used for directives with static scheduling.
2840 ExprResult NextLB, NextUB;
2841 if (isOpenMPWorksharingDirective(DKind)) {
2842 // LB + ST
2843 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2844 if (!NextLB.isUsable())
2845 return 0;
2846 // LB = LB + ST
2847 NextLB =
2848 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2849 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2850 if (!NextLB.isUsable())
2851 return 0;
2852 // UB + ST
2853 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2854 if (!NextUB.isUsable())
2855 return 0;
2856 // UB = UB + ST
2857 NextUB =
2858 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2859 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2860 if (!NextUB.isUsable())
2861 return 0;
2862 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002863
2864 // Build updates and final values of the loop counters.
2865 bool HasErrors = false;
2866 Built.Counters.resize(NestedLoopCount);
2867 Built.Updates.resize(NestedLoopCount);
2868 Built.Finals.resize(NestedLoopCount);
2869 {
2870 ExprResult Div;
2871 // Go from inner nested loop to outer.
2872 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2873 LoopIterationSpace &IS = IterSpaces[Cnt];
2874 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2875 // Build: Iter = (IV / Div) % IS.NumIters
2876 // where Div is product of previous iterations' IS.NumIters.
2877 ExprResult Iter;
2878 if (Div.isUsable()) {
2879 Iter =
2880 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2881 } else {
2882 Iter = IV;
2883 assert((Cnt == (int)NestedLoopCount - 1) &&
2884 "unusable div expected on first iteration only");
2885 }
2886
2887 if (Cnt != 0 && Iter.isUsable())
2888 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2889 IS.NumIterations);
2890 if (!Iter.isUsable()) {
2891 HasErrors = true;
2892 break;
2893 }
2894
2895 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2896 ExprResult Update =
2897 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2898 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2899 if (!Update.isUsable()) {
2900 HasErrors = true;
2901 break;
2902 }
2903
2904 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2905 ExprResult Final = BuildCounterUpdate(
2906 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2907 IS.NumIterations, IS.CounterStep, IS.Subtract);
2908 if (!Final.isUsable()) {
2909 HasErrors = true;
2910 break;
2911 }
2912
2913 // Build Div for the next iteration: Div <- Div * IS.NumIters
2914 if (Cnt != 0) {
2915 if (Div.isUnset())
2916 Div = IS.NumIterations;
2917 else
2918 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2919 IS.NumIterations);
2920
2921 // Add parentheses (for debugging purposes only).
2922 if (Div.isUsable())
2923 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2924 if (!Div.isUsable()) {
2925 HasErrors = true;
2926 break;
2927 }
2928 }
2929 if (!Update.isUsable() || !Final.isUsable()) {
2930 HasErrors = true;
2931 break;
2932 }
2933 // Save results
2934 Built.Counters[Cnt] = IS.CounterVar;
2935 Built.Updates[Cnt] = Update.get();
2936 Built.Finals[Cnt] = Final.get();
2937 }
2938 }
2939
2940 if (HasErrors)
2941 return 0;
2942
2943 // Save results
2944 Built.IterationVarRef = IV.get();
2945 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00002946 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002947 Built.CalcLastIteration = CalcLastIteration.get();
2948 Built.PreCond = PreCond.get();
2949 Built.Cond = Cond.get();
2950 Built.SeparatedCond = SeparatedCond.get();
2951 Built.Init = Init.get();
2952 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00002953 Built.LB = LB.get();
2954 Built.UB = UB.get();
2955 Built.IL = IL.get();
2956 Built.ST = ST.get();
2957 Built.EUB = EUB.get();
2958 Built.NLB = NextLB.get();
2959 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002960
Alexey Bataevabfc0692014-06-25 06:52:00 +00002961 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002962}
2963
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002964static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002965 auto CollapseFilter = [](const OMPClause *C) -> bool {
2966 return C->getClauseKind() == OMPC_collapse;
2967 };
2968 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2969 Clauses, CollapseFilter);
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002970 if (I)
2971 return cast<OMPCollapseClause>(*I)->getNumForLoops();
2972 return nullptr;
2973}
2974
Alexey Bataev4acb8592014-07-07 13:01:15 +00002975StmtResult Sema::ActOnOpenMPSimdDirective(
2976 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2977 SourceLocation EndLoc,
2978 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002979 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002980 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002981 unsigned NestedLoopCount =
2982 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002983 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00002984 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002985 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002986
Alexander Musmana5f070a2014-10-01 06:03:56 +00002987 assert((CurContext->isDependentContext() || B.builtAll()) &&
2988 "omp simd loop exprs were not built");
2989
Alexander Musman3276a272015-03-21 10:12:56 +00002990 if (!CurContext->isDependentContext()) {
2991 // Finalize the clauses that need pre-built expressions for CodeGen.
2992 for (auto C : Clauses) {
2993 if (auto LC = dyn_cast<OMPLinearClause>(C))
2994 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
2995 B.NumIterations, *this, CurScope))
2996 return StmtError();
2997 }
2998 }
2999
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003000 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003001 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3002 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003003}
3004
Alexey Bataev4acb8592014-07-07 13:01:15 +00003005StmtResult Sema::ActOnOpenMPForDirective(
3006 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3007 SourceLocation EndLoc,
3008 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003009 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003010 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003011 unsigned NestedLoopCount =
3012 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003013 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003014 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003015 return StmtError();
3016
Alexander Musmana5f070a2014-10-01 06:03:56 +00003017 assert((CurContext->isDependentContext() || B.builtAll()) &&
3018 "omp for loop exprs were not built");
3019
Alexey Bataevf29276e2014-06-18 04:14:57 +00003020 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003021 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3022 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003023}
3024
Alexander Musmanf82886e2014-09-18 05:12:34 +00003025StmtResult Sema::ActOnOpenMPForSimdDirective(
3026 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3027 SourceLocation EndLoc,
3028 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003029 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003030 // In presence of clause 'collapse', it will define the nested loops number.
3031 unsigned NestedLoopCount =
3032 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003033 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003034 if (NestedLoopCount == 0)
3035 return StmtError();
3036
Alexander Musmanc6388682014-12-15 07:07:06 +00003037 assert((CurContext->isDependentContext() || B.builtAll()) &&
3038 "omp for simd loop exprs were not built");
3039
Alexander Musmanf82886e2014-09-18 05:12:34 +00003040 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003041 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3042 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003043}
3044
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003045StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3046 Stmt *AStmt,
3047 SourceLocation StartLoc,
3048 SourceLocation EndLoc) {
3049 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3050 auto BaseStmt = AStmt;
3051 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3052 BaseStmt = CS->getCapturedStmt();
3053 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3054 auto S = C->children();
3055 if (!S)
3056 return StmtError();
3057 // All associated statements must be '#pragma omp section' except for
3058 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003059 for (++S; S; ++S) {
3060 auto SectionStmt = *S;
3061 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3062 if (SectionStmt)
3063 Diag(SectionStmt->getLocStart(),
3064 diag::err_omp_sections_substmt_not_section);
3065 return StmtError();
3066 }
3067 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003068 } else {
3069 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3070 return StmtError();
3071 }
3072
3073 getCurFunction()->setHasBranchProtectedScope();
3074
3075 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3076 AStmt);
3077}
3078
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003079StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3080 SourceLocation StartLoc,
3081 SourceLocation EndLoc) {
3082 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3083
3084 getCurFunction()->setHasBranchProtectedScope();
3085
3086 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3087}
3088
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003089StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3090 Stmt *AStmt,
3091 SourceLocation StartLoc,
3092 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003093 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3094
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003095 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003096
Alexey Bataev3255bf32015-01-19 05:20:46 +00003097 // OpenMP [2.7.3, single Construct, Restrictions]
3098 // The copyprivate clause must not be used with the nowait clause.
3099 OMPClause *Nowait = nullptr;
3100 OMPClause *Copyprivate = nullptr;
3101 for (auto *Clause : Clauses) {
3102 if (Clause->getClauseKind() == OMPC_nowait)
3103 Nowait = Clause;
3104 else if (Clause->getClauseKind() == OMPC_copyprivate)
3105 Copyprivate = Clause;
3106 if (Copyprivate && Nowait) {
3107 Diag(Copyprivate->getLocStart(),
3108 diag::err_omp_single_copyprivate_with_nowait);
3109 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3110 return StmtError();
3111 }
3112 }
3113
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003114 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3115}
3116
Alexander Musman80c22892014-07-17 08:54:58 +00003117StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3118 SourceLocation StartLoc,
3119 SourceLocation EndLoc) {
3120 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3121
3122 getCurFunction()->setHasBranchProtectedScope();
3123
3124 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3125}
3126
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003127StmtResult
3128Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3129 Stmt *AStmt, SourceLocation StartLoc,
3130 SourceLocation EndLoc) {
3131 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3132
3133 getCurFunction()->setHasBranchProtectedScope();
3134
3135 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3136 AStmt);
3137}
3138
Alexey Bataev4acb8592014-07-07 13:01:15 +00003139StmtResult Sema::ActOnOpenMPParallelForDirective(
3140 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3141 SourceLocation EndLoc,
3142 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3143 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3144 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3145 // 1.2.2 OpenMP Language Terminology
3146 // Structured block - An executable statement with a single entry at the
3147 // top and a single exit at the bottom.
3148 // The point of exit cannot be a branch out of the structured block.
3149 // longjmp() and throw() must not violate the entry/exit criteria.
3150 CS->getCapturedDecl()->setNothrow();
3151
Alexander Musmanc6388682014-12-15 07:07:06 +00003152 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003153 // In presence of clause 'collapse', it will define the nested loops number.
3154 unsigned NestedLoopCount =
3155 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003156 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003157 if (NestedLoopCount == 0)
3158 return StmtError();
3159
Alexander Musmana5f070a2014-10-01 06:03:56 +00003160 assert((CurContext->isDependentContext() || B.builtAll()) &&
3161 "omp parallel for loop exprs were not built");
3162
Alexey Bataev4acb8592014-07-07 13:01:15 +00003163 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003164 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3165 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003166}
3167
Alexander Musmane4e893b2014-09-23 09:33:00 +00003168StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3169 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3170 SourceLocation EndLoc,
3171 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3172 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3173 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3174 // 1.2.2 OpenMP Language Terminology
3175 // Structured block - An executable statement with a single entry at the
3176 // top and a single exit at the bottom.
3177 // The point of exit cannot be a branch out of the structured block.
3178 // longjmp() and throw() must not violate the entry/exit criteria.
3179 CS->getCapturedDecl()->setNothrow();
3180
Alexander Musmanc6388682014-12-15 07:07:06 +00003181 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003182 // In presence of clause 'collapse', it will define the nested loops number.
3183 unsigned NestedLoopCount =
3184 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003185 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003186 if (NestedLoopCount == 0)
3187 return StmtError();
3188
3189 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003190 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003191 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003192}
3193
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003194StmtResult
3195Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3196 Stmt *AStmt, SourceLocation StartLoc,
3197 SourceLocation EndLoc) {
3198 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3199 auto BaseStmt = AStmt;
3200 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3201 BaseStmt = CS->getCapturedStmt();
3202 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3203 auto S = C->children();
3204 if (!S)
3205 return StmtError();
3206 // All associated statements must be '#pragma omp section' except for
3207 // the first one.
3208 for (++S; S; ++S) {
3209 auto SectionStmt = *S;
3210 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3211 if (SectionStmt)
3212 Diag(SectionStmt->getLocStart(),
3213 diag::err_omp_parallel_sections_substmt_not_section);
3214 return StmtError();
3215 }
3216 }
3217 } else {
3218 Diag(AStmt->getLocStart(),
3219 diag::err_omp_parallel_sections_not_compound_stmt);
3220 return StmtError();
3221 }
3222
3223 getCurFunction()->setHasBranchProtectedScope();
3224
3225 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3226 Clauses, AStmt);
3227}
3228
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003229StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3230 Stmt *AStmt, SourceLocation StartLoc,
3231 SourceLocation EndLoc) {
3232 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3233 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3234 // 1.2.2 OpenMP Language Terminology
3235 // Structured block - An executable statement with a single entry at the
3236 // top and a single exit at the bottom.
3237 // The point of exit cannot be a branch out of the structured block.
3238 // longjmp() and throw() must not violate the entry/exit criteria.
3239 CS->getCapturedDecl()->setNothrow();
3240
3241 getCurFunction()->setHasBranchProtectedScope();
3242
3243 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3244}
3245
Alexey Bataev68446b72014-07-18 07:47:19 +00003246StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3247 SourceLocation EndLoc) {
3248 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3249}
3250
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003251StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3252 SourceLocation EndLoc) {
3253 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3254}
3255
Alexey Bataev2df347a2014-07-18 10:17:07 +00003256StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3257 SourceLocation EndLoc) {
3258 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3259}
3260
Alexey Bataev6125da92014-07-21 11:26:11 +00003261StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3262 SourceLocation StartLoc,
3263 SourceLocation EndLoc) {
3264 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3265 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3266}
3267
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003268StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3269 SourceLocation StartLoc,
3270 SourceLocation EndLoc) {
3271 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3272
3273 getCurFunction()->setHasBranchProtectedScope();
3274
3275 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3276}
3277
Alexey Bataev1d160b12015-03-13 12:27:31 +00003278namespace {
3279/// \brief Helper class for checking expression in 'omp atomic [update]'
3280/// construct.
3281class OpenMPAtomicUpdateChecker {
3282 /// \brief Error results for atomic update expressions.
3283 enum ExprAnalysisErrorCode {
3284 /// \brief A statement is not an expression statement.
3285 NotAnExpression,
3286 /// \brief Expression is not builtin binary or unary operation.
3287 NotABinaryOrUnaryExpression,
3288 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3289 NotAnUnaryIncDecExpression,
3290 /// \brief An expression is not of scalar type.
3291 NotAScalarType,
3292 /// \brief A binary operation is not an assignment operation.
3293 NotAnAssignmentOp,
3294 /// \brief RHS part of the binary operation is not a binary expression.
3295 NotABinaryExpression,
3296 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3297 /// expression.
3298 NotABinaryOperator,
3299 /// \brief RHS binary operation does not have reference to the updated LHS
3300 /// part.
3301 NotAnUpdateExpression,
3302 /// \brief No errors is found.
3303 NoError
3304 };
3305 /// \brief Reference to Sema.
3306 Sema &SemaRef;
3307 /// \brief A location for note diagnostics (when error is found).
3308 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003309 /// \brief 'x' lvalue part of the source atomic expression.
3310 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003311 /// \brief 'expr' rvalue part of the source atomic expression.
3312 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003313 /// \brief Helper expression of the form
3314 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3315 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3316 Expr *UpdateExpr;
3317 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3318 /// important for non-associative operations.
3319 bool IsXLHSInRHSPart;
3320 BinaryOperatorKind Op;
3321 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003322 /// \brief true if the source expression is a postfix unary operation, false
3323 /// if it is a prefix unary operation.
3324 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003325
3326public:
3327 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003328 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003329 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003330 /// \brief Check specified statement that it is suitable for 'atomic update'
3331 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003332 /// expression. If DiagId and NoteId == 0, then only check is performed
3333 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003334 /// \param DiagId Diagnostic which should be emitted if error is found.
3335 /// \param NoteId Diagnostic note for the main error message.
3336 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003337 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003338 /// \brief Return the 'x' lvalue part of the source atomic expression.
3339 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003340 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3341 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003342 /// \brief Return the update expression used in calculation of the updated
3343 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3344 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3345 Expr *getUpdateExpr() const { return UpdateExpr; }
3346 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3347 /// false otherwise.
3348 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3349
Alexey Bataevb78ca832015-04-01 03:33:17 +00003350 /// \brief true if the source expression is a postfix unary operation, false
3351 /// if it is a prefix unary operation.
3352 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3353
Alexey Bataev1d160b12015-03-13 12:27:31 +00003354private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003355 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3356 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003357};
3358} // namespace
3359
3360bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3361 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3362 ExprAnalysisErrorCode ErrorFound = NoError;
3363 SourceLocation ErrorLoc, NoteLoc;
3364 SourceRange ErrorRange, NoteRange;
3365 // Allowed constructs are:
3366 // x = x binop expr;
3367 // x = expr binop x;
3368 if (AtomicBinOp->getOpcode() == BO_Assign) {
3369 X = AtomicBinOp->getLHS();
3370 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3371 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3372 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3373 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3374 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003375 Op = AtomicInnerBinOp->getOpcode();
3376 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003377 auto *LHS = AtomicInnerBinOp->getLHS();
3378 auto *RHS = AtomicInnerBinOp->getRHS();
3379 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3380 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3381 /*Canonical=*/true);
3382 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3383 /*Canonical=*/true);
3384 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3385 /*Canonical=*/true);
3386 if (XId == LHSId) {
3387 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003388 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003389 } else if (XId == RHSId) {
3390 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003391 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003392 } else {
3393 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3394 ErrorRange = AtomicInnerBinOp->getSourceRange();
3395 NoteLoc = X->getExprLoc();
3396 NoteRange = X->getSourceRange();
3397 ErrorFound = NotAnUpdateExpression;
3398 }
3399 } else {
3400 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3401 ErrorRange = AtomicInnerBinOp->getSourceRange();
3402 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3403 NoteRange = SourceRange(NoteLoc, NoteLoc);
3404 ErrorFound = NotABinaryOperator;
3405 }
3406 } else {
3407 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3408 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3409 ErrorFound = NotABinaryExpression;
3410 }
3411 } else {
3412 ErrorLoc = AtomicBinOp->getExprLoc();
3413 ErrorRange = AtomicBinOp->getSourceRange();
3414 NoteLoc = AtomicBinOp->getOperatorLoc();
3415 NoteRange = SourceRange(NoteLoc, NoteLoc);
3416 ErrorFound = NotAnAssignmentOp;
3417 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003418 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003419 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3420 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3421 return true;
3422 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003423 E = X = UpdateExpr = nullptr;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003424 return false;
3425}
3426
3427bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3428 unsigned NoteId) {
3429 ExprAnalysisErrorCode ErrorFound = NoError;
3430 SourceLocation ErrorLoc, NoteLoc;
3431 SourceRange ErrorRange, NoteRange;
3432 // Allowed constructs are:
3433 // x++;
3434 // x--;
3435 // ++x;
3436 // --x;
3437 // x binop= expr;
3438 // x = x binop expr;
3439 // x = expr binop x;
3440 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3441 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3442 if (AtomicBody->getType()->isScalarType() ||
3443 AtomicBody->isInstantiationDependent()) {
3444 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3445 AtomicBody->IgnoreParenImpCasts())) {
3446 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003447 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003448 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003449 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003450 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003451 X = AtomicCompAssignOp->getLHS();
3452 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003453 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3454 AtomicBody->IgnoreParenImpCasts())) {
3455 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003456 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3457 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003458 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003459 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3460 // Check for Unary Operation
3461 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003462 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003463 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3464 OpLoc = AtomicUnaryOp->getOperatorLoc();
3465 X = AtomicUnaryOp->getSubExpr();
3466 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3467 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003468 } else {
3469 ErrorFound = NotAnUnaryIncDecExpression;
3470 ErrorLoc = AtomicUnaryOp->getExprLoc();
3471 ErrorRange = AtomicUnaryOp->getSourceRange();
3472 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3473 NoteRange = SourceRange(NoteLoc, NoteLoc);
3474 }
3475 } else {
3476 ErrorFound = NotABinaryOrUnaryExpression;
3477 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3478 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3479 }
3480 } else {
3481 ErrorFound = NotAScalarType;
3482 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3483 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3484 }
3485 } else {
3486 ErrorFound = NotAnExpression;
3487 NoteLoc = ErrorLoc = S->getLocStart();
3488 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3489 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003490 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003491 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3492 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3493 return true;
3494 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003495 E = X = UpdateExpr = nullptr;
3496 if (E && X) {
3497 // Build an update expression of form 'OpaqueValueExpr(x) binop
3498 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3499 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3500 auto *OVEX = new (SemaRef.getASTContext())
3501 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3502 auto *OVEExpr = new (SemaRef.getASTContext())
3503 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3504 auto Update =
3505 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3506 IsXLHSInRHSPart ? OVEExpr : OVEX);
3507 if (Update.isInvalid())
3508 return true;
3509 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3510 Sema::AA_Casting);
3511 if (Update.isInvalid())
3512 return true;
3513 UpdateExpr = Update.get();
3514 }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003515 return false;
3516}
3517
Alexey Bataev0162e452014-07-22 10:10:35 +00003518StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3519 Stmt *AStmt,
3520 SourceLocation StartLoc,
3521 SourceLocation EndLoc) {
3522 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003523 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003524 // 1.2.2 OpenMP Language Terminology
3525 // Structured block - An executable statement with a single entry at the
3526 // top and a single exit at the bottom.
3527 // The point of exit cannot be a branch out of the structured block.
3528 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003529 OpenMPClauseKind AtomicKind = OMPC_unknown;
3530 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003531 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003532 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003533 C->getClauseKind() == OMPC_update ||
3534 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003535 if (AtomicKind != OMPC_unknown) {
3536 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3537 << SourceRange(C->getLocStart(), C->getLocEnd());
3538 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3539 << getOpenMPClauseName(AtomicKind);
3540 } else {
3541 AtomicKind = C->getClauseKind();
3542 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003543 }
3544 }
3545 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003546
Alexey Bataev459dec02014-07-24 06:46:57 +00003547 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003548 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3549 Body = EWC->getSubExpr();
3550
Alexey Bataev62cec442014-11-18 10:14:22 +00003551 Expr *X = nullptr;
3552 Expr *V = nullptr;
3553 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003554 Expr *UE = nullptr;
3555 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003556 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003557 // OpenMP [2.12.6, atomic Construct]
3558 // In the next expressions:
3559 // * x and v (as applicable) are both l-value expressions with scalar type.
3560 // * During the execution of an atomic region, multiple syntactic
3561 // occurrences of x must designate the same storage location.
3562 // * Neither of v and expr (as applicable) may access the storage location
3563 // designated by x.
3564 // * Neither of x and expr (as applicable) may access the storage location
3565 // designated by v.
3566 // * expr is an expression with scalar type.
3567 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3568 // * binop, binop=, ++, and -- are not overloaded operators.
3569 // * The expression x binop expr must be numerically equivalent to x binop
3570 // (expr). This requirement is satisfied if the operators in expr have
3571 // precedence greater than binop, or by using parentheses around expr or
3572 // subexpressions of expr.
3573 // * The expression expr binop x must be numerically equivalent to (expr)
3574 // binop x. This requirement is satisfied if the operators in expr have
3575 // precedence equal to or greater than binop, or by using parentheses around
3576 // expr or subexpressions of expr.
3577 // * For forms that allow multiple occurrences of x, the number of times
3578 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003579 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003580 enum {
3581 NotAnExpression,
3582 NotAnAssignmentOp,
3583 NotAScalarType,
3584 NotAnLValue,
3585 NoError
3586 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003587 SourceLocation ErrorLoc, NoteLoc;
3588 SourceRange ErrorRange, NoteRange;
3589 // If clause is read:
3590 // v = x;
3591 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3592 auto AtomicBinOp =
3593 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3594 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3595 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3596 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3597 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3598 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3599 if (!X->isLValue() || !V->isLValue()) {
3600 auto NotLValueExpr = X->isLValue() ? V : X;
3601 ErrorFound = NotAnLValue;
3602 ErrorLoc = AtomicBinOp->getExprLoc();
3603 ErrorRange = AtomicBinOp->getSourceRange();
3604 NoteLoc = NotLValueExpr->getExprLoc();
3605 NoteRange = NotLValueExpr->getSourceRange();
3606 }
3607 } else if (!X->isInstantiationDependent() ||
3608 !V->isInstantiationDependent()) {
3609 auto NotScalarExpr =
3610 (X->isInstantiationDependent() || X->getType()->isScalarType())
3611 ? V
3612 : X;
3613 ErrorFound = NotAScalarType;
3614 ErrorLoc = AtomicBinOp->getExprLoc();
3615 ErrorRange = AtomicBinOp->getSourceRange();
3616 NoteLoc = NotScalarExpr->getExprLoc();
3617 NoteRange = NotScalarExpr->getSourceRange();
3618 }
3619 } else {
3620 ErrorFound = NotAnAssignmentOp;
3621 ErrorLoc = AtomicBody->getExprLoc();
3622 ErrorRange = AtomicBody->getSourceRange();
3623 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3624 : AtomicBody->getExprLoc();
3625 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3626 : AtomicBody->getSourceRange();
3627 }
3628 } else {
3629 ErrorFound = NotAnExpression;
3630 NoteLoc = ErrorLoc = Body->getLocStart();
3631 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003632 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003633 if (ErrorFound != NoError) {
3634 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3635 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003636 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3637 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003638 return StmtError();
3639 } else if (CurContext->isDependentContext())
3640 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003641 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003642 enum {
3643 NotAnExpression,
3644 NotAnAssignmentOp,
3645 NotAScalarType,
3646 NotAnLValue,
3647 NoError
3648 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003649 SourceLocation ErrorLoc, NoteLoc;
3650 SourceRange ErrorRange, NoteRange;
3651 // If clause is write:
3652 // x = expr;
3653 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3654 auto AtomicBinOp =
3655 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3656 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003657 X = AtomicBinOp->getLHS();
3658 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003659 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3660 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3661 if (!X->isLValue()) {
3662 ErrorFound = NotAnLValue;
3663 ErrorLoc = AtomicBinOp->getExprLoc();
3664 ErrorRange = AtomicBinOp->getSourceRange();
3665 NoteLoc = X->getExprLoc();
3666 NoteRange = X->getSourceRange();
3667 }
3668 } else if (!X->isInstantiationDependent() ||
3669 !E->isInstantiationDependent()) {
3670 auto NotScalarExpr =
3671 (X->isInstantiationDependent() || X->getType()->isScalarType())
3672 ? E
3673 : X;
3674 ErrorFound = NotAScalarType;
3675 ErrorLoc = AtomicBinOp->getExprLoc();
3676 ErrorRange = AtomicBinOp->getSourceRange();
3677 NoteLoc = NotScalarExpr->getExprLoc();
3678 NoteRange = NotScalarExpr->getSourceRange();
3679 }
3680 } else {
3681 ErrorFound = NotAnAssignmentOp;
3682 ErrorLoc = AtomicBody->getExprLoc();
3683 ErrorRange = AtomicBody->getSourceRange();
3684 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3685 : AtomicBody->getExprLoc();
3686 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3687 : AtomicBody->getSourceRange();
3688 }
3689 } else {
3690 ErrorFound = NotAnExpression;
3691 NoteLoc = ErrorLoc = Body->getLocStart();
3692 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003693 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003694 if (ErrorFound != NoError) {
3695 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3696 << ErrorRange;
3697 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3698 << NoteRange;
3699 return StmtError();
3700 } else if (CurContext->isDependentContext())
3701 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003702 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003703 // If clause is update:
3704 // x++;
3705 // x--;
3706 // ++x;
3707 // --x;
3708 // x binop= expr;
3709 // x = x binop expr;
3710 // x = expr binop x;
3711 OpenMPAtomicUpdateChecker Checker(*this);
3712 if (Checker.checkStatement(
3713 Body, (AtomicKind == OMPC_update)
3714 ? diag::err_omp_atomic_update_not_expression_statement
3715 : diag::err_omp_atomic_not_expression_statement,
3716 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003717 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003718 if (!CurContext->isDependentContext()) {
3719 E = Checker.getExpr();
3720 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003721 UE = Checker.getUpdateExpr();
3722 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003723 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003724 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003725 enum {
3726 NotAnAssignmentOp,
3727 NotACompoundStatement,
3728 NotTwoSubstatements,
3729 NotASpecificExpression,
3730 NoError
3731 } ErrorFound = NoError;
3732 SourceLocation ErrorLoc, NoteLoc;
3733 SourceRange ErrorRange, NoteRange;
3734 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3735 // If clause is a capture:
3736 // v = x++;
3737 // v = x--;
3738 // v = ++x;
3739 // v = --x;
3740 // v = x binop= expr;
3741 // v = x = x binop expr;
3742 // v = x = expr binop x;
3743 auto *AtomicBinOp =
3744 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3745 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3746 V = AtomicBinOp->getLHS();
3747 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3748 OpenMPAtomicUpdateChecker Checker(*this);
3749 if (Checker.checkStatement(
3750 Body, diag::err_omp_atomic_capture_not_expression_statement,
3751 diag::note_omp_atomic_update))
3752 return StmtError();
3753 E = Checker.getExpr();
3754 X = Checker.getX();
3755 UE = Checker.getUpdateExpr();
3756 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3757 IsPostfixUpdate = Checker.isPostfixUpdate();
3758 } else {
3759 ErrorLoc = AtomicBody->getExprLoc();
3760 ErrorRange = AtomicBody->getSourceRange();
3761 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3762 : AtomicBody->getExprLoc();
3763 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3764 : AtomicBody->getSourceRange();
3765 ErrorFound = NotAnAssignmentOp;
3766 }
3767 if (ErrorFound != NoError) {
3768 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3769 << ErrorRange;
3770 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3771 return StmtError();
3772 } else if (CurContext->isDependentContext()) {
3773 UE = V = E = X = nullptr;
3774 }
3775 } else {
3776 // If clause is a capture:
3777 // { v = x; x = expr; }
3778 // { v = x; x++; }
3779 // { v = x; x--; }
3780 // { v = x; ++x; }
3781 // { v = x; --x; }
3782 // { v = x; x binop= expr; }
3783 // { v = x; x = x binop expr; }
3784 // { v = x; x = expr binop x; }
3785 // { x++; v = x; }
3786 // { x--; v = x; }
3787 // { ++x; v = x; }
3788 // { --x; v = x; }
3789 // { x binop= expr; v = x; }
3790 // { x = x binop expr; v = x; }
3791 // { x = expr binop x; v = x; }
3792 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3793 // Check that this is { expr1; expr2; }
3794 if (CS->size() == 2) {
3795 auto *First = CS->body_front();
3796 auto *Second = CS->body_back();
3797 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3798 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3799 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3800 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3801 // Need to find what subexpression is 'v' and what is 'x'.
3802 OpenMPAtomicUpdateChecker Checker(*this);
3803 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3804 BinaryOperator *BinOp = nullptr;
3805 if (IsUpdateExprFound) {
3806 BinOp = dyn_cast<BinaryOperator>(First);
3807 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3808 }
3809 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3810 // { v = x; x++; }
3811 // { v = x; x--; }
3812 // { v = x; ++x; }
3813 // { v = x; --x; }
3814 // { v = x; x binop= expr; }
3815 // { v = x; x = x binop expr; }
3816 // { v = x; x = expr binop x; }
3817 // Check that the first expression has form v = x.
3818 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3819 llvm::FoldingSetNodeID XId, PossibleXId;
3820 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3821 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3822 IsUpdateExprFound = XId == PossibleXId;
3823 if (IsUpdateExprFound) {
3824 V = BinOp->getLHS();
3825 X = Checker.getX();
3826 E = Checker.getExpr();
3827 UE = Checker.getUpdateExpr();
3828 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3829 IsPostfixUpdate = Checker.isPostfixUpdate();
3830 }
3831 }
3832 if (!IsUpdateExprFound) {
3833 IsUpdateExprFound = !Checker.checkStatement(First);
3834 BinOp = nullptr;
3835 if (IsUpdateExprFound) {
3836 BinOp = dyn_cast<BinaryOperator>(Second);
3837 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3838 }
3839 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3840 // { x++; v = x; }
3841 // { x--; v = x; }
3842 // { ++x; v = x; }
3843 // { --x; v = x; }
3844 // { x binop= expr; v = x; }
3845 // { x = x binop expr; v = x; }
3846 // { x = expr binop x; v = x; }
3847 // Check that the second expression has form v = x.
3848 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3849 llvm::FoldingSetNodeID XId, PossibleXId;
3850 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3851 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3852 IsUpdateExprFound = XId == PossibleXId;
3853 if (IsUpdateExprFound) {
3854 V = BinOp->getLHS();
3855 X = Checker.getX();
3856 E = Checker.getExpr();
3857 UE = Checker.getUpdateExpr();
3858 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3859 IsPostfixUpdate = Checker.isPostfixUpdate();
3860 }
3861 }
3862 }
3863 if (!IsUpdateExprFound) {
3864 // { v = x; x = expr; }
3865 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3866 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3867 ErrorFound = NotAnAssignmentOp;
3868 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3869 : First->getLocStart();
3870 NoteRange = ErrorRange = FirstBinOp
3871 ? FirstBinOp->getSourceRange()
3872 : SourceRange(ErrorLoc, ErrorLoc);
3873 } else {
3874 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3875 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3876 ErrorFound = NotAnAssignmentOp;
3877 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3878 : Second->getLocStart();
3879 NoteRange = ErrorRange = SecondBinOp
3880 ? SecondBinOp->getSourceRange()
3881 : SourceRange(ErrorLoc, ErrorLoc);
3882 } else {
3883 auto *PossibleXRHSInFirst =
3884 FirstBinOp->getRHS()->IgnoreParenImpCasts();
3885 auto *PossibleXLHSInSecond =
3886 SecondBinOp->getLHS()->IgnoreParenImpCasts();
3887 llvm::FoldingSetNodeID X1Id, X2Id;
3888 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
3889 PossibleXLHSInSecond->Profile(X2Id, Context,
3890 /*Canonical=*/true);
3891 IsUpdateExprFound = X1Id == X2Id;
3892 if (IsUpdateExprFound) {
3893 V = FirstBinOp->getLHS();
3894 X = SecondBinOp->getLHS();
3895 E = SecondBinOp->getRHS();
3896 UE = nullptr;
3897 IsXLHSInRHSPart = false;
3898 IsPostfixUpdate = true;
3899 } else {
3900 ErrorFound = NotASpecificExpression;
3901 ErrorLoc = FirstBinOp->getExprLoc();
3902 ErrorRange = FirstBinOp->getSourceRange();
3903 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
3904 NoteRange = SecondBinOp->getRHS()->getSourceRange();
3905 }
3906 }
3907 }
3908 }
3909 } else {
3910 NoteLoc = ErrorLoc = Body->getLocStart();
3911 NoteRange = ErrorRange =
3912 SourceRange(Body->getLocStart(), Body->getLocStart());
3913 ErrorFound = NotTwoSubstatements;
3914 }
3915 } else {
3916 NoteLoc = ErrorLoc = Body->getLocStart();
3917 NoteRange = ErrorRange =
3918 SourceRange(Body->getLocStart(), Body->getLocStart());
3919 ErrorFound = NotACompoundStatement;
3920 }
3921 if (ErrorFound != NoError) {
3922 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
3923 << ErrorRange;
3924 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3925 return StmtError();
3926 } else if (CurContext->isDependentContext()) {
3927 UE = V = E = X = nullptr;
3928 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003929 }
Alexey Bataevdea47612014-07-23 07:46:59 +00003930 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003931
3932 getCurFunction()->setHasBranchProtectedScope();
3933
Alexey Bataev62cec442014-11-18 10:14:22 +00003934 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00003935 X, V, E, UE, IsXLHSInRHSPart,
3936 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00003937}
3938
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003939StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3940 Stmt *AStmt,
3941 SourceLocation StartLoc,
3942 SourceLocation EndLoc) {
3943 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3944
Alexey Bataev13314bf2014-10-09 04:18:56 +00003945 // OpenMP [2.16, Nesting of Regions]
3946 // If specified, a teams construct must be contained within a target
3947 // construct. That target construct must contain no statements or directives
3948 // outside of the teams construct.
3949 if (DSAStack->hasInnerTeamsRegion()) {
3950 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3951 bool OMPTeamsFound = true;
3952 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3953 auto I = CS->body_begin();
3954 while (I != CS->body_end()) {
3955 auto OED = dyn_cast<OMPExecutableDirective>(*I);
3956 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3957 OMPTeamsFound = false;
3958 break;
3959 }
3960 ++I;
3961 }
3962 assert(I != CS->body_end() && "Not found statement");
3963 S = *I;
3964 }
3965 if (!OMPTeamsFound) {
3966 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
3967 Diag(DSAStack->getInnerTeamsRegionLoc(),
3968 diag::note_omp_nested_teams_construct_here);
3969 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
3970 << isa<OMPExecutableDirective>(S);
3971 return StmtError();
3972 }
3973 }
3974
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003975 getCurFunction()->setHasBranchProtectedScope();
3976
3977 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3978}
3979
Alexey Bataev13314bf2014-10-09 04:18:56 +00003980StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
3981 Stmt *AStmt, SourceLocation StartLoc,
3982 SourceLocation EndLoc) {
3983 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3984 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3985 // 1.2.2 OpenMP Language Terminology
3986 // Structured block - An executable statement with a single entry at the
3987 // top and a single exit at the bottom.
3988 // The point of exit cannot be a branch out of the structured block.
3989 // longjmp() and throw() must not violate the entry/exit criteria.
3990 CS->getCapturedDecl()->setNothrow();
3991
3992 getCurFunction()->setHasBranchProtectedScope();
3993
3994 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3995}
3996
Alexey Bataeved09d242014-05-28 05:53:51 +00003997OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003998 SourceLocation StartLoc,
3999 SourceLocation LParenLoc,
4000 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004001 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004002 switch (Kind) {
4003 case OMPC_if:
4004 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4005 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004006 case OMPC_final:
4007 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4008 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004009 case OMPC_num_threads:
4010 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4011 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004012 case OMPC_safelen:
4013 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4014 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004015 case OMPC_collapse:
4016 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4017 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004018 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004019 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004020 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004021 case OMPC_private:
4022 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004023 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004024 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004025 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004026 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004027 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004028 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004029 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004030 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004031 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004032 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004033 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004034 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004035 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004036 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004037 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004038 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004039 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004040 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004041 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004042 llvm_unreachable("Clause is not allowed.");
4043 }
4044 return Res;
4045}
4046
Alexey Bataeved09d242014-05-28 05:53:51 +00004047OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004048 SourceLocation LParenLoc,
4049 SourceLocation EndLoc) {
4050 Expr *ValExpr = Condition;
4051 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4052 !Condition->isInstantiationDependent() &&
4053 !Condition->containsUnexpandedParameterPack()) {
4054 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004055 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004056 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004057 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004058
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004059 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004060 }
4061
4062 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4063}
4064
Alexey Bataev3778b602014-07-17 07:32:53 +00004065OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4066 SourceLocation StartLoc,
4067 SourceLocation LParenLoc,
4068 SourceLocation EndLoc) {
4069 Expr *ValExpr = Condition;
4070 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4071 !Condition->isInstantiationDependent() &&
4072 !Condition->containsUnexpandedParameterPack()) {
4073 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4074 Condition->getExprLoc(), Condition);
4075 if (Val.isInvalid())
4076 return nullptr;
4077
4078 ValExpr = Val.get();
4079 }
4080
4081 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4082}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004083ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4084 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004085 if (!Op)
4086 return ExprError();
4087
4088 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4089 public:
4090 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004091 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004092 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4093 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004094 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4095 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004096 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4097 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004098 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4099 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004100 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4101 QualType T,
4102 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004103 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4104 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004105 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4106 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004107 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004108 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004109 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004110 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4111 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004112 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4113 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004114 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4115 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004116 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004117 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004118 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004119 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4120 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004121 llvm_unreachable("conversion functions are permitted");
4122 }
4123 } ConvertDiagnoser;
4124 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4125}
4126
4127OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4128 SourceLocation StartLoc,
4129 SourceLocation LParenLoc,
4130 SourceLocation EndLoc) {
4131 Expr *ValExpr = NumThreads;
4132 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004133 !NumThreads->containsUnexpandedParameterPack()) {
4134 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4135 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004136 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004137 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004138 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004139
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004140 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004141
4142 // OpenMP [2.5, Restrictions]
4143 // The num_threads expression must evaluate to a positive integer value.
4144 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004145 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4146 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004147 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4148 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004149 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004150 }
4151 }
4152
Alexey Bataeved09d242014-05-28 05:53:51 +00004153 return new (Context)
4154 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004155}
4156
Alexey Bataev62c87d22014-03-21 04:51:18 +00004157ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4158 OpenMPClauseKind CKind) {
4159 if (!E)
4160 return ExprError();
4161 if (E->isValueDependent() || E->isTypeDependent() ||
4162 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004163 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004164 llvm::APSInt Result;
4165 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4166 if (ICE.isInvalid())
4167 return ExprError();
4168 if (!Result.isStrictlyPositive()) {
4169 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4170 << getOpenMPClauseName(CKind) << E->getSourceRange();
4171 return ExprError();
4172 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004173 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4174 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4175 << E->getSourceRange();
4176 return ExprError();
4177 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004178 return ICE;
4179}
4180
4181OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4182 SourceLocation LParenLoc,
4183 SourceLocation EndLoc) {
4184 // OpenMP [2.8.1, simd construct, Description]
4185 // The parameter of the safelen clause must be a constant
4186 // positive integer expression.
4187 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4188 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004189 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004190 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004191 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004192}
4193
Alexander Musman64d33f12014-06-04 07:53:32 +00004194OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4195 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004196 SourceLocation LParenLoc,
4197 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004198 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004199 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004200 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004201 // The parameter of the collapse clause must be a constant
4202 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004203 ExprResult NumForLoopsResult =
4204 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4205 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004206 return nullptr;
4207 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004208 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004209}
4210
Alexey Bataeved09d242014-05-28 05:53:51 +00004211OMPClause *Sema::ActOnOpenMPSimpleClause(
4212 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4213 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004214 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004215 switch (Kind) {
4216 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004217 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004218 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4219 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004220 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004221 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004222 Res = ActOnOpenMPProcBindClause(
4223 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4224 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004225 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004226 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004227 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004228 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004229 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004230 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004231 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004232 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004233 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004234 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004235 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004236 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004237 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004238 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004239 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004240 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004241 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004242 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004243 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004244 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004245 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004246 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004247 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004248 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004249 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004250 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004251 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004252 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004253 llvm_unreachable("Clause is not allowed.");
4254 }
4255 return Res;
4256}
4257
4258OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4259 SourceLocation KindKwLoc,
4260 SourceLocation StartLoc,
4261 SourceLocation LParenLoc,
4262 SourceLocation EndLoc) {
4263 if (Kind == OMPC_DEFAULT_unknown) {
4264 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004265 static_assert(OMPC_DEFAULT_unknown > 0,
4266 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004267 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004268 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004269 Values += "'";
4270 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4271 Values += "'";
4272 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004273 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004274 Values += " or ";
4275 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004276 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004277 break;
4278 default:
4279 Values += Sep;
4280 break;
4281 }
4282 }
4283 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004284 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004285 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004286 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004287 switch (Kind) {
4288 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004289 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004290 break;
4291 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004292 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004293 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004294 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004295 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004296 break;
4297 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004298 return new (Context)
4299 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004300}
4301
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004302OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4303 SourceLocation KindKwLoc,
4304 SourceLocation StartLoc,
4305 SourceLocation LParenLoc,
4306 SourceLocation EndLoc) {
4307 if (Kind == OMPC_PROC_BIND_unknown) {
4308 std::string Values;
4309 std::string Sep(", ");
4310 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4311 Values += "'";
4312 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4313 Values += "'";
4314 switch (i) {
4315 case OMPC_PROC_BIND_unknown - 2:
4316 Values += " or ";
4317 break;
4318 case OMPC_PROC_BIND_unknown - 1:
4319 break;
4320 default:
4321 Values += Sep;
4322 break;
4323 }
4324 }
4325 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004326 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004327 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004328 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004329 return new (Context)
4330 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004331}
4332
Alexey Bataev56dafe82014-06-20 07:16:17 +00004333OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4334 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4335 SourceLocation StartLoc, SourceLocation LParenLoc,
4336 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4337 SourceLocation EndLoc) {
4338 OMPClause *Res = nullptr;
4339 switch (Kind) {
4340 case OMPC_schedule:
4341 Res = ActOnOpenMPScheduleClause(
4342 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4343 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4344 break;
4345 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004346 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004347 case OMPC_num_threads:
4348 case OMPC_safelen:
4349 case OMPC_collapse:
4350 case OMPC_default:
4351 case OMPC_proc_bind:
4352 case OMPC_private:
4353 case OMPC_firstprivate:
4354 case OMPC_lastprivate:
4355 case OMPC_shared:
4356 case OMPC_reduction:
4357 case OMPC_linear:
4358 case OMPC_aligned:
4359 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004360 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004361 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004362 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004363 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004364 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004365 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004366 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004367 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004368 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004369 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004370 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004371 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004372 case OMPC_unknown:
4373 llvm_unreachable("Clause is not allowed.");
4374 }
4375 return Res;
4376}
4377
4378OMPClause *Sema::ActOnOpenMPScheduleClause(
4379 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4380 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4381 SourceLocation EndLoc) {
4382 if (Kind == OMPC_SCHEDULE_unknown) {
4383 std::string Values;
4384 std::string Sep(", ");
4385 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4386 Values += "'";
4387 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4388 Values += "'";
4389 switch (i) {
4390 case OMPC_SCHEDULE_unknown - 2:
4391 Values += " or ";
4392 break;
4393 case OMPC_SCHEDULE_unknown - 1:
4394 break;
4395 default:
4396 Values += Sep;
4397 break;
4398 }
4399 }
4400 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4401 << Values << getOpenMPClauseName(OMPC_schedule);
4402 return nullptr;
4403 }
4404 Expr *ValExpr = ChunkSize;
4405 if (ChunkSize) {
4406 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4407 !ChunkSize->isInstantiationDependent() &&
4408 !ChunkSize->containsUnexpandedParameterPack()) {
4409 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4410 ExprResult Val =
4411 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4412 if (Val.isInvalid())
4413 return nullptr;
4414
4415 ValExpr = Val.get();
4416
4417 // OpenMP [2.7.1, Restrictions]
4418 // chunk_size must be a loop invariant integer expression with a positive
4419 // value.
4420 llvm::APSInt Result;
4421 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
4422 Result.isSigned() && !Result.isStrictlyPositive()) {
4423 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4424 << "schedule" << ChunkSize->getSourceRange();
4425 return nullptr;
4426 }
4427 }
4428 }
4429
4430 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4431 EndLoc, Kind, ValExpr);
4432}
4433
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004434OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4435 SourceLocation StartLoc,
4436 SourceLocation EndLoc) {
4437 OMPClause *Res = nullptr;
4438 switch (Kind) {
4439 case OMPC_ordered:
4440 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4441 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004442 case OMPC_nowait:
4443 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4444 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004445 case OMPC_untied:
4446 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4447 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004448 case OMPC_mergeable:
4449 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4450 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004451 case OMPC_read:
4452 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4453 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004454 case OMPC_write:
4455 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4456 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004457 case OMPC_update:
4458 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4459 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004460 case OMPC_capture:
4461 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4462 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004463 case OMPC_seq_cst:
4464 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4465 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004466 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004467 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004468 case OMPC_num_threads:
4469 case OMPC_safelen:
4470 case OMPC_collapse:
4471 case OMPC_schedule:
4472 case OMPC_private:
4473 case OMPC_firstprivate:
4474 case OMPC_lastprivate:
4475 case OMPC_shared:
4476 case OMPC_reduction:
4477 case OMPC_linear:
4478 case OMPC_aligned:
4479 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004480 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004481 case OMPC_default:
4482 case OMPC_proc_bind:
4483 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004484 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004485 case OMPC_unknown:
4486 llvm_unreachable("Clause is not allowed.");
4487 }
4488 return Res;
4489}
4490
4491OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4492 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004493 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004494 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4495}
4496
Alexey Bataev236070f2014-06-20 11:19:47 +00004497OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4498 SourceLocation EndLoc) {
4499 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4500}
4501
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004502OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4503 SourceLocation EndLoc) {
4504 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4505}
4506
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004507OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4508 SourceLocation EndLoc) {
4509 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4510}
4511
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004512OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4513 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004514 return new (Context) OMPReadClause(StartLoc, EndLoc);
4515}
4516
Alexey Bataevdea47612014-07-23 07:46:59 +00004517OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4518 SourceLocation EndLoc) {
4519 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4520}
4521
Alexey Bataev67a4f222014-07-23 10:25:33 +00004522OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4523 SourceLocation EndLoc) {
4524 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4525}
4526
Alexey Bataev459dec02014-07-24 06:46:57 +00004527OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4528 SourceLocation EndLoc) {
4529 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4530}
4531
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004532OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4533 SourceLocation EndLoc) {
4534 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4535}
4536
Alexey Bataevc5e02582014-06-16 07:08:35 +00004537OMPClause *Sema::ActOnOpenMPVarListClause(
4538 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4539 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4540 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4541 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004542 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004543 switch (Kind) {
4544 case OMPC_private:
4545 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4546 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004547 case OMPC_firstprivate:
4548 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4549 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004550 case OMPC_lastprivate:
4551 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4552 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004553 case OMPC_shared:
4554 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4555 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004556 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004557 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4558 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004559 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004560 case OMPC_linear:
4561 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4562 ColonLoc, EndLoc);
4563 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004564 case OMPC_aligned:
4565 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4566 ColonLoc, EndLoc);
4567 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004568 case OMPC_copyin:
4569 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4570 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004571 case OMPC_copyprivate:
4572 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4573 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004574 case OMPC_flush:
4575 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4576 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004577 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004578 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004579 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004580 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004581 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004582 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004583 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004584 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004585 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004586 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004587 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004588 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004589 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004590 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004591 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004592 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004593 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004594 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004595 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004596 llvm_unreachable("Clause is not allowed.");
4597 }
4598 return Res;
4599}
4600
4601OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4602 SourceLocation StartLoc,
4603 SourceLocation LParenLoc,
4604 SourceLocation EndLoc) {
4605 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004606 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004607 for (auto &RefExpr : VarList) {
4608 assert(RefExpr && "NULL expr in OpenMP private clause.");
4609 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004610 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004611 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004612 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004613 continue;
4614 }
4615
Alexey Bataeved09d242014-05-28 05:53:51 +00004616 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004617 // OpenMP [2.1, C/C++]
4618 // A list item is a variable name.
4619 // OpenMP [2.9.3.3, Restrictions, p.1]
4620 // A variable that is part of another variable (as an array or
4621 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004622 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004623 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004624 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004625 continue;
4626 }
4627 Decl *D = DE->getDecl();
4628 VarDecl *VD = cast<VarDecl>(D);
4629
4630 QualType Type = VD->getType();
4631 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4632 // It will be analyzed later.
4633 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004634 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004635 continue;
4636 }
4637
4638 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4639 // A variable that appears in a private clause must not have an incomplete
4640 // type or a reference type.
4641 if (RequireCompleteType(ELoc, Type,
4642 diag::err_omp_private_incomplete_type)) {
4643 continue;
4644 }
4645 if (Type->isReferenceType()) {
4646 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004647 << getOpenMPClauseName(OMPC_private) << Type;
4648 bool IsDecl =
4649 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4650 Diag(VD->getLocation(),
4651 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4652 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004653 continue;
4654 }
4655
4656 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4657 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004658 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004659 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004660 while (Type->isArrayType()) {
4661 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004662 }
4663
Alexey Bataev758e55e2013-09-06 18:03:48 +00004664 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4665 // in a Construct]
4666 // Variables with the predetermined data-sharing attributes may not be
4667 // listed in data-sharing attributes clauses, except for the cases
4668 // listed below. For these exceptions only, listing a predetermined
4669 // variable in a data-sharing attribute clause is allowed and overrides
4670 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004671 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004672 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004673 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4674 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004675 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004676 continue;
4677 }
4678
Alexey Bataev03b340a2014-10-21 03:16:40 +00004679 // Generate helper private variable and initialize it with the default
4680 // value. The address of the original variable is replaced by the address of
4681 // the new private variable in CodeGen. This new variable is not added to
4682 // IdResolver, so the code in the OpenMP region uses original variable for
4683 // proper diagnostics.
4684 auto VDPrivate =
4685 VarDecl::Create(Context, CurContext, DE->getLocStart(),
4686 DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
4687 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4688 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4689 if (VDPrivate->isInvalidDecl())
4690 continue;
4691 CurContext->addDecl(VDPrivate);
Alexey Bataev07649fb2014-12-16 08:01:48 +00004692 auto VDPrivateRefExpr =
4693 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4694 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004695 /*RefersToEnclosingVariableOrCapture*/ false,
Alexey Bataev07649fb2014-12-16 08:01:48 +00004696 /*NameLoc*/ SourceLocation(), DE->getType(),
4697 /*VK*/ VK_LValue);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004698
Alexey Bataev758e55e2013-09-06 18:03:48 +00004699 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004700 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004701 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004702 }
4703
Alexey Bataeved09d242014-05-28 05:53:51 +00004704 if (Vars.empty())
4705 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004706
Alexey Bataev03b340a2014-10-21 03:16:40 +00004707 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4708 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004709}
4710
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004711namespace {
4712class DiagsUninitializedSeveretyRAII {
4713private:
4714 DiagnosticsEngine &Diags;
4715 SourceLocation SavedLoc;
4716 bool IsIgnored;
4717
4718public:
4719 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4720 bool IsIgnored)
4721 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4722 if (!IsIgnored) {
4723 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4724 /*Map*/ diag::Severity::Ignored, Loc);
4725 }
4726 }
4727 ~DiagsUninitializedSeveretyRAII() {
4728 if (!IsIgnored)
4729 Diags.popMappings(SavedLoc);
4730 }
4731};
4732}
4733
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004734OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4735 SourceLocation StartLoc,
4736 SourceLocation LParenLoc,
4737 SourceLocation EndLoc) {
4738 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004739 SmallVector<Expr *, 8> PrivateCopies;
4740 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004741 bool IsImplicitClause =
4742 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4743 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4744
Alexey Bataeved09d242014-05-28 05:53:51 +00004745 for (auto &RefExpr : VarList) {
4746 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4747 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004748 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004749 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004750 PrivateCopies.push_back(nullptr);
4751 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004752 continue;
4753 }
4754
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004755 SourceLocation ELoc =
4756 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004757 // OpenMP [2.1, C/C++]
4758 // A list item is a variable name.
4759 // OpenMP [2.9.3.3, Restrictions, p.1]
4760 // A variable that is part of another variable (as an array or
4761 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004762 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004763 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004764 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004765 continue;
4766 }
4767 Decl *D = DE->getDecl();
4768 VarDecl *VD = cast<VarDecl>(D);
4769
4770 QualType Type = VD->getType();
4771 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4772 // It will be analyzed later.
4773 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004774 PrivateCopies.push_back(nullptr);
4775 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004776 continue;
4777 }
4778
4779 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4780 // A variable that appears in a private clause must not have an incomplete
4781 // type or a reference type.
4782 if (RequireCompleteType(ELoc, Type,
4783 diag::err_omp_firstprivate_incomplete_type)) {
4784 continue;
4785 }
4786 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004787 if (IsImplicitClause) {
4788 Diag(ImplicitClauseLoc,
4789 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4790 << Type;
4791 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4792 } else {
4793 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4794 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4795 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004796 bool IsDecl =
4797 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4798 Diag(VD->getLocation(),
4799 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4800 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004801 continue;
4802 }
4803
4804 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4805 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004806 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004807 // class type.
4808 Type = Context.getBaseElementType(Type);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004809
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004810 // If an implicit firstprivate variable found it was checked already.
4811 if (!IsImplicitClause) {
4812 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004813 Type = Type.getNonReferenceType().getCanonicalType();
4814 bool IsConstant = Type.isConstant(Context);
4815 Type = Context.getBaseElementType(Type);
4816 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4817 // A list item that specifies a given variable may not appear in more
4818 // than one clause on the same directive, except that a variable may be
4819 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004820 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004821 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004822 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004823 << getOpenMPClauseName(DVar.CKind)
4824 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004825 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004826 continue;
4827 }
4828
4829 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4830 // in a Construct]
4831 // Variables with the predetermined data-sharing attributes may not be
4832 // listed in data-sharing attributes clauses, except for the cases
4833 // listed below. For these exceptions only, listing a predetermined
4834 // variable in a data-sharing attribute clause is allowed and overrides
4835 // the variable's predetermined data-sharing attributes.
4836 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4837 // in a Construct, C/C++, p.2]
4838 // Variables with const-qualified type having no mutable member may be
4839 // listed in a firstprivate clause, even if they are static data members.
4840 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4841 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4842 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004843 << getOpenMPClauseName(DVar.CKind)
4844 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004845 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004846 continue;
4847 }
4848
Alexey Bataevf29276e2014-06-18 04:14:57 +00004849 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004850 // OpenMP [2.9.3.4, Restrictions, p.2]
4851 // A list item that is private within a parallel region must not appear
4852 // in a firstprivate clause on a worksharing construct if any of the
4853 // worksharing regions arising from the worksharing construct ever bind
4854 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004855 if (isOpenMPWorksharingDirective(CurrDir) &&
4856 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004857 DVar = DSAStack->getImplicitDSA(VD, true);
4858 if (DVar.CKind != OMPC_shared &&
4859 (isOpenMPParallelDirective(DVar.DKind) ||
4860 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004861 Diag(ELoc, diag::err_omp_required_access)
4862 << getOpenMPClauseName(OMPC_firstprivate)
4863 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004864 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004865 continue;
4866 }
4867 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004868 // OpenMP [2.9.3.4, Restrictions, p.3]
4869 // A list item that appears in a reduction clause of a parallel construct
4870 // must not appear in a firstprivate clause on a worksharing or task
4871 // construct if any of the worksharing or task regions arising from the
4872 // worksharing or task construct ever bind to any of the parallel regions
4873 // arising from the parallel construct.
4874 // OpenMP [2.9.3.4, Restrictions, p.4]
4875 // A list item that appears in a reduction clause in worksharing
4876 // construct must not appear in a firstprivate clause in a task construct
4877 // encountered during execution of any of the worksharing regions arising
4878 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004879 if (CurrDir == OMPD_task) {
4880 DVar =
4881 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4882 [](OpenMPDirectiveKind K) -> bool {
4883 return isOpenMPParallelDirective(K) ||
4884 isOpenMPWorksharingDirective(K);
4885 },
4886 false);
4887 if (DVar.CKind == OMPC_reduction &&
4888 (isOpenMPParallelDirective(DVar.DKind) ||
4889 isOpenMPWorksharingDirective(DVar.DKind))) {
4890 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4891 << getOpenMPDirectiveName(DVar.DKind);
4892 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4893 continue;
4894 }
4895 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004896 }
4897
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004898 Type = Type.getUnqualifiedType();
4899 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4900 ELoc, VD->getIdentifier(), VD->getType(),
4901 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4902 // Generate helper private variable and initialize it with the value of the
4903 // original variable. The address of the original variable is replaced by
4904 // the address of the new private variable in the CodeGen. This new variable
4905 // is not added to IdResolver, so the code in the OpenMP region uses
4906 // original variable for proper diagnostics and variable capturing.
4907 Expr *VDInitRefExpr = nullptr;
4908 // For arrays generate initializer for single element and replace it by the
4909 // original array element in CodeGen.
4910 if (DE->getType()->isArrayType()) {
4911 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4912 ELoc, VD->getIdentifier(), Type,
4913 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4914 CurContext->addHiddenDecl(VDInit);
4915 VDInitRefExpr = DeclRefExpr::Create(
4916 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4917 /*TemplateKWLoc*/ SourceLocation(), VDInit,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004918 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004919 /*VK*/ VK_LValue);
4920 VDInit->setIsUsed();
4921 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
4922 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit);
4923 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4924
4925 InitializationSequence InitSeq(*this, Entity, Kind, Init);
4926 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4927 if (Result.isInvalid())
4928 VDPrivate->setInvalidDecl();
4929 else
4930 VDPrivate->setInit(Result.getAs<Expr>());
4931 } else {
Alexey Bataevf841bd92014-12-16 07:00:22 +00004932 AddInitializerToDecl(
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004933 VDPrivate,
4934 DefaultLvalueConversion(
4935 DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
4936 SourceLocation(), DE->getDecl(),
4937 /*RefersToEnclosingVariableOrCapture=*/true,
4938 DE->getExprLoc(), DE->getType(),
4939 /*VK=*/VK_LValue)).get(),
Alexey Bataevf841bd92014-12-16 07:00:22 +00004940 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004941 }
4942 if (VDPrivate->isInvalidDecl()) {
4943 if (IsImplicitClause) {
4944 Diag(DE->getExprLoc(),
4945 diag::note_omp_task_predetermined_firstprivate_here);
4946 }
4947 continue;
4948 }
4949 CurContext->addDecl(VDPrivate);
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004950 auto VDPrivateRefExpr =
4951 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4952 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4953 /*RefersToEnclosingVariableOrCapture*/ false,
4954 DE->getLocStart(), DE->getType(),
4955 /*VK*/ VK_LValue);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004956 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4957 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004958 PrivateCopies.push_back(VDPrivateRefExpr);
4959 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004960 }
4961
Alexey Bataeved09d242014-05-28 05:53:51 +00004962 if (Vars.empty())
4963 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004964
4965 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004966 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004967}
4968
Alexander Musman1bb328c2014-06-04 13:06:39 +00004969OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
4970 SourceLocation StartLoc,
4971 SourceLocation LParenLoc,
4972 SourceLocation EndLoc) {
4973 SmallVector<Expr *, 8> Vars;
4974 for (auto &RefExpr : VarList) {
4975 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
4976 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4977 // It will be analyzed later.
4978 Vars.push_back(RefExpr);
4979 continue;
4980 }
4981
4982 SourceLocation ELoc = RefExpr->getExprLoc();
4983 // OpenMP [2.1, C/C++]
4984 // A list item is a variable name.
4985 // OpenMP [2.14.3.5, Restrictions, p.1]
4986 // A variable that is part of another variable (as an array or structure
4987 // element) cannot appear in a lastprivate clause.
4988 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4989 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4990 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4991 continue;
4992 }
4993 Decl *D = DE->getDecl();
4994 VarDecl *VD = cast<VarDecl>(D);
4995
4996 QualType Type = VD->getType();
4997 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4998 // It will be analyzed later.
4999 Vars.push_back(DE);
5000 continue;
5001 }
5002
5003 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5004 // A variable that appears in a lastprivate clause must not have an
5005 // incomplete type or a reference type.
5006 if (RequireCompleteType(ELoc, Type,
5007 diag::err_omp_lastprivate_incomplete_type)) {
5008 continue;
5009 }
5010 if (Type->isReferenceType()) {
5011 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5012 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5013 bool IsDecl =
5014 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5015 Diag(VD->getLocation(),
5016 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5017 << VD;
5018 continue;
5019 }
5020
5021 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5022 // in a Construct]
5023 // Variables with the predetermined data-sharing attributes may not be
5024 // listed in data-sharing attributes clauses, except for the cases
5025 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005026 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005027 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5028 DVar.CKind != OMPC_firstprivate &&
5029 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5030 Diag(ELoc, diag::err_omp_wrong_dsa)
5031 << getOpenMPClauseName(DVar.CKind)
5032 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005033 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005034 continue;
5035 }
5036
Alexey Bataevf29276e2014-06-18 04:14:57 +00005037 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5038 // OpenMP [2.14.3.5, Restrictions, p.2]
5039 // A list item that is private within a parallel region, or that appears in
5040 // the reduction clause of a parallel construct, must not appear in a
5041 // lastprivate clause on a worksharing construct if any of the corresponding
5042 // worksharing regions ever binds to any of the corresponding parallel
5043 // regions.
Alexey Bataev549210e2014-06-24 04:39:47 +00005044 if (isOpenMPWorksharingDirective(CurrDir) &&
5045 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005046 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005047 if (DVar.CKind != OMPC_shared) {
5048 Diag(ELoc, diag::err_omp_required_access)
5049 << getOpenMPClauseName(OMPC_lastprivate)
5050 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005051 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005052 continue;
5053 }
5054 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005055 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005056 // A variable of class type (or array thereof) that appears in a
5057 // lastprivate clause requires an accessible, unambiguous default
5058 // constructor for the class type, unless the list item is also specified
5059 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005060 // A variable of class type (or array thereof) that appears in a
5061 // lastprivate clause requires an accessible, unambiguous copy assignment
5062 // operator for the class type.
5063 while (Type.getNonReferenceType()->isArrayType())
5064 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
5065 ->getElementType();
5066 CXXRecordDecl *RD = getLangOpts().CPlusPlus
5067 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
5068 : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005069 // FIXME This code must be replaced by actual copying and destructing of the
5070 // lastprivate variable.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005071 if (RD) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00005072 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5073 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005074 if (MD) {
5075 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5076 MD->isDeleted()) {
5077 Diag(ELoc, diag::err_omp_required_method)
5078 << getOpenMPClauseName(OMPC_lastprivate) << 2;
5079 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5080 VarDecl::DeclarationOnly;
5081 Diag(VD->getLocation(),
5082 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5083 << VD;
5084 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5085 continue;
5086 }
5087 MarkFunctionReferenced(ELoc, MD);
5088 DiagnoseUseOfDecl(MD, ELoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005089 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005090
5091 CXXDestructorDecl *DD = RD->getDestructor();
5092 if (DD) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005093 PartialDiagnostic PD =
5094 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005095 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
5096 DD->isDeleted()) {
5097 Diag(ELoc, diag::err_omp_required_method)
5098 << getOpenMPClauseName(OMPC_lastprivate) << 4;
5099 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5100 VarDecl::DeclarationOnly;
5101 Diag(VD->getLocation(),
5102 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5103 << VD;
5104 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5105 continue;
5106 }
5107 MarkFunctionReferenced(ELoc, DD);
5108 DiagnoseUseOfDecl(DD, ELoc);
5109 }
5110 }
5111
Alexey Bataevf29276e2014-06-18 04:14:57 +00005112 if (DVar.CKind != OMPC_firstprivate)
5113 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005114 Vars.push_back(DE);
5115 }
5116
5117 if (Vars.empty())
5118 return nullptr;
5119
5120 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5121 Vars);
5122}
5123
Alexey Bataev758e55e2013-09-06 18:03:48 +00005124OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5125 SourceLocation StartLoc,
5126 SourceLocation LParenLoc,
5127 SourceLocation EndLoc) {
5128 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005129 for (auto &RefExpr : VarList) {
5130 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5131 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005132 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005133 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005134 continue;
5135 }
5136
Alexey Bataeved09d242014-05-28 05:53:51 +00005137 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005138 // OpenMP [2.1, C/C++]
5139 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005140 // OpenMP [2.14.3.2, Restrictions, p.1]
5141 // A variable that is part of another variable (as an array or structure
5142 // element) cannot appear in a shared unless it is a static data member
5143 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005144 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005145 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005146 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005147 continue;
5148 }
5149 Decl *D = DE->getDecl();
5150 VarDecl *VD = cast<VarDecl>(D);
5151
5152 QualType Type = VD->getType();
5153 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5154 // It will be analyzed later.
5155 Vars.push_back(DE);
5156 continue;
5157 }
5158
5159 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5160 // in a Construct]
5161 // Variables with the predetermined data-sharing attributes may not be
5162 // listed in data-sharing attributes clauses, except for the cases
5163 // listed below. For these exceptions only, listing a predetermined
5164 // variable in a data-sharing attribute clause is allowed and overrides
5165 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005166 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005167 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5168 DVar.RefExpr) {
5169 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5170 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005171 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005172 continue;
5173 }
5174
5175 DSAStack->addDSA(VD, DE, OMPC_shared);
5176 Vars.push_back(DE);
5177 }
5178
Alexey Bataeved09d242014-05-28 05:53:51 +00005179 if (Vars.empty())
5180 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005181
5182 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5183}
5184
Alexey Bataevc5e02582014-06-16 07:08:35 +00005185namespace {
5186class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5187 DSAStackTy *Stack;
5188
5189public:
5190 bool VisitDeclRefExpr(DeclRefExpr *E) {
5191 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005192 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005193 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5194 return false;
5195 if (DVar.CKind != OMPC_unknown)
5196 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005197 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005198 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005199 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005200 return true;
5201 return false;
5202 }
5203 return false;
5204 }
5205 bool VisitStmt(Stmt *S) {
5206 for (auto Child : S->children()) {
5207 if (Child && Visit(Child))
5208 return true;
5209 }
5210 return false;
5211 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005212 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005213};
Alexey Bataev23b69422014-06-18 07:08:49 +00005214} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005215
5216OMPClause *Sema::ActOnOpenMPReductionClause(
5217 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5218 SourceLocation ColonLoc, SourceLocation EndLoc,
5219 CXXScopeSpec &ReductionIdScopeSpec,
5220 const DeclarationNameInfo &ReductionId) {
5221 // TODO: Allow scope specification search when 'declare reduction' is
5222 // supported.
5223 assert(ReductionIdScopeSpec.isEmpty() &&
5224 "No support for scoped reduction identifiers yet.");
5225
5226 auto DN = ReductionId.getName();
5227 auto OOK = DN.getCXXOverloadedOperator();
5228 BinaryOperatorKind BOK = BO_Comma;
5229
5230 // OpenMP [2.14.3.6, reduction clause]
5231 // C
5232 // reduction-identifier is either an identifier or one of the following
5233 // operators: +, -, *, &, |, ^, && and ||
5234 // C++
5235 // reduction-identifier is either an id-expression or one of the following
5236 // operators: +, -, *, &, |, ^, && and ||
5237 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5238 switch (OOK) {
5239 case OO_Plus:
5240 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005241 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005242 break;
5243 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005244 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005245 break;
5246 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005247 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005248 break;
5249 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005250 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005251 break;
5252 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005253 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005254 break;
5255 case OO_AmpAmp:
5256 BOK = BO_LAnd;
5257 break;
5258 case OO_PipePipe:
5259 BOK = BO_LOr;
5260 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005261 case OO_New:
5262 case OO_Delete:
5263 case OO_Array_New:
5264 case OO_Array_Delete:
5265 case OO_Slash:
5266 case OO_Percent:
5267 case OO_Tilde:
5268 case OO_Exclaim:
5269 case OO_Equal:
5270 case OO_Less:
5271 case OO_Greater:
5272 case OO_LessEqual:
5273 case OO_GreaterEqual:
5274 case OO_PlusEqual:
5275 case OO_MinusEqual:
5276 case OO_StarEqual:
5277 case OO_SlashEqual:
5278 case OO_PercentEqual:
5279 case OO_CaretEqual:
5280 case OO_AmpEqual:
5281 case OO_PipeEqual:
5282 case OO_LessLess:
5283 case OO_GreaterGreater:
5284 case OO_LessLessEqual:
5285 case OO_GreaterGreaterEqual:
5286 case OO_EqualEqual:
5287 case OO_ExclaimEqual:
5288 case OO_PlusPlus:
5289 case OO_MinusMinus:
5290 case OO_Comma:
5291 case OO_ArrowStar:
5292 case OO_Arrow:
5293 case OO_Call:
5294 case OO_Subscript:
5295 case OO_Conditional:
5296 case NUM_OVERLOADED_OPERATORS:
5297 llvm_unreachable("Unexpected reduction identifier");
5298 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005299 if (auto II = DN.getAsIdentifierInfo()) {
5300 if (II->isStr("max"))
5301 BOK = BO_GT;
5302 else if (II->isStr("min"))
5303 BOK = BO_LT;
5304 }
5305 break;
5306 }
5307 SourceRange ReductionIdRange;
5308 if (ReductionIdScopeSpec.isValid()) {
5309 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5310 }
5311 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5312 if (BOK == BO_Comma) {
5313 // Not allowed reduction identifier is found.
5314 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5315 << ReductionIdRange;
5316 return nullptr;
5317 }
5318
5319 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005320 SmallVector<Expr *, 8> LHSs;
5321 SmallVector<Expr *, 8> RHSs;
5322 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005323 for (auto RefExpr : VarList) {
5324 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5325 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5326 // It will be analyzed later.
5327 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005328 LHSs.push_back(nullptr);
5329 RHSs.push_back(nullptr);
5330 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005331 continue;
5332 }
5333
5334 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5335 RefExpr->isInstantiationDependent() ||
5336 RefExpr->containsUnexpandedParameterPack()) {
5337 // It will be analyzed later.
5338 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005339 LHSs.push_back(nullptr);
5340 RHSs.push_back(nullptr);
5341 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005342 continue;
5343 }
5344
5345 auto ELoc = RefExpr->getExprLoc();
5346 auto ERange = RefExpr->getSourceRange();
5347 // OpenMP [2.1, C/C++]
5348 // A list item is a variable or array section, subject to the restrictions
5349 // specified in Section 2.4 on page 42 and in each of the sections
5350 // describing clauses and directives for which a list appears.
5351 // OpenMP [2.14.3.3, Restrictions, p.1]
5352 // A variable that is part of another variable (as an array or
5353 // structure element) cannot appear in a private clause.
5354 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5355 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5356 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5357 continue;
5358 }
5359 auto D = DE->getDecl();
5360 auto VD = cast<VarDecl>(D);
5361 auto Type = VD->getType();
5362 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5363 // A variable that appears in a private clause must not have an incomplete
5364 // type or a reference type.
5365 if (RequireCompleteType(ELoc, Type,
5366 diag::err_omp_reduction_incomplete_type))
5367 continue;
5368 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5369 // Arrays may not appear in a reduction clause.
5370 if (Type.getNonReferenceType()->isArrayType()) {
5371 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5372 bool IsDecl =
5373 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5374 Diag(VD->getLocation(),
5375 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5376 << VD;
5377 continue;
5378 }
5379 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5380 // A list item that appears in a reduction clause must not be
5381 // const-qualified.
5382 if (Type.getNonReferenceType().isConstant(Context)) {
5383 Diag(ELoc, diag::err_omp_const_variable)
5384 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5385 bool IsDecl =
5386 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5387 Diag(VD->getLocation(),
5388 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5389 << VD;
5390 continue;
5391 }
5392 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5393 // If a list-item is a reference type then it must bind to the same object
5394 // for all threads of the team.
5395 VarDecl *VDDef = VD->getDefinition();
5396 if (Type->isReferenceType() && VDDef) {
5397 DSARefChecker Check(DSAStack);
5398 if (Check.Visit(VDDef->getInit())) {
5399 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5400 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5401 continue;
5402 }
5403 }
5404 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5405 // The type of a list item that appears in a reduction clause must be valid
5406 // for the reduction-identifier. For a max or min reduction in C, the type
5407 // of the list item must be an allowed arithmetic data type: char, int,
5408 // float, double, or _Bool, possibly modified with long, short, signed, or
5409 // unsigned. For a max or min reduction in C++, the type of the list item
5410 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5411 // double, or bool, possibly modified with long, short, signed, or unsigned.
5412 if ((BOK == BO_GT || BOK == BO_LT) &&
5413 !(Type->isScalarType() ||
5414 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5415 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5416 << getLangOpts().CPlusPlus;
5417 bool IsDecl =
5418 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5419 Diag(VD->getLocation(),
5420 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5421 << VD;
5422 continue;
5423 }
5424 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5425 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5426 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5427 bool IsDecl =
5428 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5429 Diag(VD->getLocation(),
5430 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5431 << VD;
5432 continue;
5433 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005434 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5435 // in a Construct]
5436 // Variables with the predetermined data-sharing attributes may not be
5437 // listed in data-sharing attributes clauses, except for the cases
5438 // listed below. For these exceptions only, listing a predetermined
5439 // variable in a data-sharing attribute clause is allowed and overrides
5440 // the variable's predetermined data-sharing attributes.
5441 // OpenMP [2.14.3.6, Restrictions, p.3]
5442 // Any number of reduction clauses can be specified on the directive,
5443 // but a list item can appear only once in the reduction clauses for that
5444 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005445 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005446 if (DVar.CKind == OMPC_reduction) {
5447 Diag(ELoc, diag::err_omp_once_referenced)
5448 << getOpenMPClauseName(OMPC_reduction);
5449 if (DVar.RefExpr) {
5450 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5451 }
5452 } else if (DVar.CKind != OMPC_unknown) {
5453 Diag(ELoc, diag::err_omp_wrong_dsa)
5454 << getOpenMPClauseName(DVar.CKind)
5455 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005456 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005457 continue;
5458 }
5459
5460 // OpenMP [2.14.3.6, Restrictions, p.1]
5461 // A list item that appears in a reduction clause of a worksharing
5462 // construct must be shared in the parallel regions to which any of the
5463 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005464 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005465 if (isOpenMPWorksharingDirective(CurrDir) &&
5466 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005467 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005468 if (DVar.CKind != OMPC_shared) {
5469 Diag(ELoc, diag::err_omp_required_access)
5470 << getOpenMPClauseName(OMPC_reduction)
5471 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005472 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005473 continue;
5474 }
5475 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005476 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
5477 auto *LHSVD = BuildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5478 auto *RHSVD = BuildVarDecl(*this, ELoc, Type, VD->getName());
5479 // Add initializer for private variable.
5480 Expr *Init = nullptr;
5481 switch (BOK) {
5482 case BO_Add:
5483 case BO_Xor:
5484 case BO_Or:
5485 case BO_LOr:
5486 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5487 if (Type->isScalarType() || Type->isAnyComplexType()) {
5488 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005489 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005490 break;
5491 case BO_Mul:
5492 case BO_LAnd:
5493 if (Type->isScalarType() || Type->isAnyComplexType()) {
5494 // '*' and '&&' reduction ops - initializer is '1'.
5495 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5496 }
5497 break;
5498 case BO_And: {
5499 // '&' reduction op - initializer is '~0'.
5500 QualType OrigType = Type;
5501 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5502 Type = ComplexTy->getElementType();
5503 }
5504 if (Type->isRealFloatingType()) {
5505 llvm::APFloat InitValue =
5506 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5507 /*isIEEE=*/true);
5508 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5509 Type, ELoc);
5510 } else if (Type->isScalarType()) {
5511 auto Size = Context.getTypeSize(Type);
5512 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5513 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5514 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5515 }
5516 if (Init && OrigType->isAnyComplexType()) {
5517 // Init = 0xFFFF + 0xFFFFi;
5518 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5519 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5520 }
5521 Type = OrigType;
5522 break;
5523 }
5524 case BO_LT:
5525 case BO_GT: {
5526 // 'min' reduction op - initializer is 'Largest representable number in
5527 // the reduction list item type'.
5528 // 'max' reduction op - initializer is 'Least representable number in
5529 // the reduction list item type'.
5530 if (Type->isIntegerType() || Type->isPointerType()) {
5531 bool IsSigned = Type->hasSignedIntegerRepresentation();
5532 auto Size = Context.getTypeSize(Type);
5533 QualType IntTy =
5534 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5535 llvm::APInt InitValue =
5536 (BOK != BO_LT)
5537 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5538 : llvm::APInt::getMinValue(Size)
5539 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5540 : llvm::APInt::getMaxValue(Size);
5541 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5542 if (Type->isPointerType()) {
5543 // Cast to pointer type.
5544 auto CastExpr = BuildCStyleCastExpr(
5545 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5546 SourceLocation(), Init);
5547 if (CastExpr.isInvalid())
5548 continue;
5549 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005550 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005551 } else if (Type->isRealFloatingType()) {
5552 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5553 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5554 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5555 Type, ELoc);
5556 }
5557 break;
5558 }
5559 case BO_PtrMemD:
5560 case BO_PtrMemI:
5561 case BO_MulAssign:
5562 case BO_Div:
5563 case BO_Rem:
5564 case BO_Sub:
5565 case BO_Shl:
5566 case BO_Shr:
5567 case BO_LE:
5568 case BO_GE:
5569 case BO_EQ:
5570 case BO_NE:
5571 case BO_AndAssign:
5572 case BO_XorAssign:
5573 case BO_OrAssign:
5574 case BO_Assign:
5575 case BO_AddAssign:
5576 case BO_SubAssign:
5577 case BO_DivAssign:
5578 case BO_RemAssign:
5579 case BO_ShlAssign:
5580 case BO_ShrAssign:
5581 case BO_Comma:
5582 llvm_unreachable("Unexpected reduction operation");
5583 }
5584 if (Init) {
5585 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5586 /*TypeMayContainAuto=*/false);
5587 } else {
5588 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5589 }
5590 if (!RHSVD->hasInit()) {
5591 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5592 << ReductionIdRange;
5593 bool IsDecl =
5594 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5595 Diag(VD->getLocation(),
5596 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5597 << VD;
5598 continue;
5599 }
5600 auto *LHSDRE = BuildDeclRefExpr(LHSVD, Type, VK_LValue, ELoc).get();
5601 auto *RHSDRE = BuildDeclRefExpr(RHSVD, Type, VK_LValue, ELoc).get();
5602 ExprResult ReductionOp =
5603 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5604 LHSDRE, RHSDRE);
5605 if (ReductionOp.isUsable()) {
5606 if (BOK != BO_LOr && BOK != BO_LAnd) {
5607 ReductionOp =
5608 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5609 BO_Assign, LHSDRE, ReductionOp.get());
5610 } else {
5611 auto *ConditionalOp = new (Context) ConditionalOperator(
5612 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5613 RHSDRE, Type, VK_LValue, OK_Ordinary);
5614 ReductionOp =
5615 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5616 BO_Assign, LHSDRE, ConditionalOp);
5617 }
5618 if (ReductionOp.isUsable()) {
5619 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005620 }
5621 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005622 if (ReductionOp.isInvalid())
5623 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005624
5625 DSAStack->addDSA(VD, DE, OMPC_reduction);
5626 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005627 LHSs.push_back(LHSDRE);
5628 RHSs.push_back(RHSDRE);
5629 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005630 }
5631
5632 if (Vars.empty())
5633 return nullptr;
5634
5635 return OMPReductionClause::Create(
5636 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005637 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5638 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005639}
5640
Alexander Musman8dba6642014-04-22 13:09:42 +00005641OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5642 SourceLocation StartLoc,
5643 SourceLocation LParenLoc,
5644 SourceLocation ColonLoc,
5645 SourceLocation EndLoc) {
5646 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005647 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005648 for (auto &RefExpr : VarList) {
5649 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5650 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005651 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005652 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005653 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005654 continue;
5655 }
5656
5657 // OpenMP [2.14.3.7, linear clause]
5658 // A list item that appears in a linear clause is subject to the private
5659 // clause semantics described in Section 2.14.3.3 on page 159 except as
5660 // noted. In addition, the value of the new list item on each iteration
5661 // of the associated loop(s) corresponds to the value of the original
5662 // list item before entering the construct plus the logical number of
5663 // the iteration times linear-step.
5664
Alexey Bataeved09d242014-05-28 05:53:51 +00005665 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005666 // OpenMP [2.1, C/C++]
5667 // A list item is a variable name.
5668 // OpenMP [2.14.3.3, Restrictions, p.1]
5669 // A variable that is part of another variable (as an array or
5670 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005671 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005672 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005673 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005674 continue;
5675 }
5676
5677 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5678
5679 // OpenMP [2.14.3.7, linear clause]
5680 // A list-item cannot appear in more than one linear clause.
5681 // A list-item that appears in a linear clause cannot appear in any
5682 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005683 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005684 if (DVar.RefExpr) {
5685 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5686 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005687 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005688 continue;
5689 }
5690
5691 QualType QType = VD->getType();
5692 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5693 // It will be analyzed later.
5694 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005695 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005696 continue;
5697 }
5698
5699 // A variable must not have an incomplete type or a reference type.
5700 if (RequireCompleteType(ELoc, QType,
5701 diag::err_omp_linear_incomplete_type)) {
5702 continue;
5703 }
5704 if (QType->isReferenceType()) {
5705 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5706 << getOpenMPClauseName(OMPC_linear) << QType;
5707 bool IsDecl =
5708 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5709 Diag(VD->getLocation(),
5710 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5711 << VD;
5712 continue;
5713 }
5714
5715 // A list item must not be const-qualified.
5716 if (QType.isConstant(Context)) {
5717 Diag(ELoc, diag::err_omp_const_variable)
5718 << getOpenMPClauseName(OMPC_linear);
5719 bool IsDecl =
5720 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5721 Diag(VD->getLocation(),
5722 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5723 << VD;
5724 continue;
5725 }
5726
5727 // A list item must be of integral or pointer type.
5728 QType = QType.getUnqualifiedType().getCanonicalType();
5729 const Type *Ty = QType.getTypePtrOrNull();
5730 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5731 !Ty->isPointerType())) {
5732 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5733 bool IsDecl =
5734 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5735 Diag(VD->getLocation(),
5736 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5737 << VD;
5738 continue;
5739 }
5740
Alexander Musman3276a272015-03-21 10:12:56 +00005741 // Build var to save initial value.
5742 VarDecl *Init = BuildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
5743 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5744 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5745 CurContext->addDecl(Init);
5746 Init->setIsUsed();
5747 auto InitRef = DeclRefExpr::Create(
5748 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5749 /*TemplateKWLoc*/ SourceLocation(), Init,
5750 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
5751 /*VK*/ VK_LValue);
Alexander Musman8dba6642014-04-22 13:09:42 +00005752 DSAStack->addDSA(VD, DE, OMPC_linear);
5753 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005754 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005755 }
5756
5757 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005758 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005759
5760 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005761 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005762 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5763 !Step->isInstantiationDependent() &&
5764 !Step->containsUnexpandedParameterPack()) {
5765 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005766 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005767 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005768 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005769 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005770
Alexander Musman3276a272015-03-21 10:12:56 +00005771 // Build var to save the step value.
5772 VarDecl *SaveVar =
5773 BuildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5774 CurContext->addDecl(SaveVar);
5775 SaveVar->setIsUsed();
5776 ExprResult SaveRef =
5777 BuildDeclRefExpr(SaveVar, StepExpr->getType(), VK_LValue, StepLoc);
5778 ExprResult CalcStep =
5779 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5780
Alexander Musman8dba6642014-04-22 13:09:42 +00005781 // Warn about zero linear step (it would be probably better specified as
5782 // making corresponding variables 'const').
5783 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005784 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5785 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005786 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5787 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005788 if (!IsConstant && CalcStep.isUsable()) {
5789 // Calculate the step beforehand instead of doing this on each iteration.
5790 // (This is not used if the number of iterations may be kfold-ed).
5791 CalcStepExpr = CalcStep.get();
5792 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005793 }
5794
5795 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005796 Vars, Inits, StepExpr, CalcStepExpr);
5797}
5798
5799static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5800 Expr *NumIterations, Sema &SemaRef,
5801 Scope *S) {
5802 // Walk the vars and build update/final expressions for the CodeGen.
5803 SmallVector<Expr *, 8> Updates;
5804 SmallVector<Expr *, 8> Finals;
5805 Expr *Step = Clause.getStep();
5806 Expr *CalcStep = Clause.getCalcStep();
5807 // OpenMP [2.14.3.7, linear clause]
5808 // If linear-step is not specified it is assumed to be 1.
5809 if (Step == nullptr)
5810 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5811 else if (CalcStep)
5812 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5813 bool HasErrors = false;
5814 auto CurInit = Clause.inits().begin();
5815 for (auto &RefExpr : Clause.varlists()) {
5816 Expr *InitExpr = *CurInit;
5817
5818 // Build privatized reference to the current linear var.
5819 auto DE = cast<DeclRefExpr>(RefExpr);
5820 auto PrivateRef = DeclRefExpr::Create(
5821 SemaRef.Context, /*QualifierLoc*/ DE->getQualifierLoc(),
5822 /*TemplateKWLoc*/ SourceLocation(), DE->getDecl(),
5823 /* RefersToEnclosingVariableOrCapture */ true, DE->getLocStart(),
5824 DE->getType(), /*VK*/ VK_LValue);
5825
5826 // Build update: Var = InitExpr + IV * Step
5827 ExprResult Update =
5828 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5829 InitExpr, IV, Step, /* Subtract */ false);
5830 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5831
5832 // Build final: Var = InitExpr + NumIterations * Step
5833 ExprResult Final =
5834 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), RefExpr, InitExpr,
5835 NumIterations, Step, /* Subtract */ false);
5836 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5837 if (!Update.isUsable() || !Final.isUsable()) {
5838 Updates.push_back(nullptr);
5839 Finals.push_back(nullptr);
5840 HasErrors = true;
5841 } else {
5842 Updates.push_back(Update.get());
5843 Finals.push_back(Final.get());
5844 }
5845 ++CurInit;
5846 }
5847 Clause.setUpdates(Updates);
5848 Clause.setFinals(Finals);
5849 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005850}
5851
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005852OMPClause *Sema::ActOnOpenMPAlignedClause(
5853 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5854 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5855
5856 SmallVector<Expr *, 8> Vars;
5857 for (auto &RefExpr : VarList) {
5858 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5859 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5860 // It will be analyzed later.
5861 Vars.push_back(RefExpr);
5862 continue;
5863 }
5864
5865 SourceLocation ELoc = RefExpr->getExprLoc();
5866 // OpenMP [2.1, C/C++]
5867 // A list item is a variable name.
5868 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5869 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5870 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5871 continue;
5872 }
5873
5874 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5875
5876 // OpenMP [2.8.1, simd construct, Restrictions]
5877 // The type of list items appearing in the aligned clause must be
5878 // array, pointer, reference to array, or reference to pointer.
5879 QualType QType = DE->getType()
5880 .getNonReferenceType()
5881 .getUnqualifiedType()
5882 .getCanonicalType();
5883 const Type *Ty = QType.getTypePtrOrNull();
5884 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5885 !Ty->isPointerType())) {
5886 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5887 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5888 bool IsDecl =
5889 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5890 Diag(VD->getLocation(),
5891 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5892 << VD;
5893 continue;
5894 }
5895
5896 // OpenMP [2.8.1, simd construct, Restrictions]
5897 // A list-item cannot appear in more than one aligned clause.
5898 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5899 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5900 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5901 << getOpenMPClauseName(OMPC_aligned);
5902 continue;
5903 }
5904
5905 Vars.push_back(DE);
5906 }
5907
5908 // OpenMP [2.8.1, simd construct, Description]
5909 // The parameter of the aligned clause, alignment, must be a constant
5910 // positive integer expression.
5911 // If no optional parameter is specified, implementation-defined default
5912 // alignments for SIMD instructions on the target platforms are assumed.
5913 if (Alignment != nullptr) {
5914 ExprResult AlignResult =
5915 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5916 if (AlignResult.isInvalid())
5917 return nullptr;
5918 Alignment = AlignResult.get();
5919 }
5920 if (Vars.empty())
5921 return nullptr;
5922
5923 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5924 EndLoc, Vars, Alignment);
5925}
5926
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005927OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5928 SourceLocation StartLoc,
5929 SourceLocation LParenLoc,
5930 SourceLocation EndLoc) {
5931 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005932 for (auto &RefExpr : VarList) {
5933 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5934 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005935 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005936 Vars.push_back(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005937 continue;
5938 }
5939
Alexey Bataeved09d242014-05-28 05:53:51 +00005940 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005941 // OpenMP [2.1, C/C++]
5942 // A list item is a variable name.
5943 // OpenMP [2.14.4.1, Restrictions, p.1]
5944 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00005945 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005946 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005947 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005948 continue;
5949 }
5950
5951 Decl *D = DE->getDecl();
5952 VarDecl *VD = cast<VarDecl>(D);
5953
5954 QualType Type = VD->getType();
5955 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5956 // It will be analyzed later.
5957 Vars.push_back(DE);
5958 continue;
5959 }
5960
5961 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5962 // A list item that appears in a copyin clause must be threadprivate.
5963 if (!DSAStack->isThreadPrivate(VD)) {
5964 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00005965 << getOpenMPClauseName(OMPC_copyin)
5966 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005967 continue;
5968 }
5969
5970 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5971 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00005972 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005973 // operator for the class type.
5974 Type = Context.getBaseElementType(Type);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005975 CXXRecordDecl *RD =
5976 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005977 // FIXME This code must be replaced by actual assignment of the
5978 // threadprivate variable.
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005979 if (RD) {
5980 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5981 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005982 if (MD) {
5983 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5984 MD->isDeleted()) {
5985 Diag(ELoc, diag::err_omp_required_method)
5986 << getOpenMPClauseName(OMPC_copyin) << 2;
5987 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5988 VarDecl::DeclarationOnly;
5989 Diag(VD->getLocation(),
5990 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5991 << VD;
5992 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5993 continue;
5994 }
5995 MarkFunctionReferenced(ELoc, MD);
5996 DiagnoseUseOfDecl(MD, ELoc);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005997 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005998 }
5999
6000 DSAStack->addDSA(VD, DE, OMPC_copyin);
6001 Vars.push_back(DE);
6002 }
6003
Alexey Bataeved09d242014-05-28 05:53:51 +00006004 if (Vars.empty())
6005 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006006
6007 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
6008}
6009
Alexey Bataevbae9a792014-06-27 10:37:06 +00006010OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6011 SourceLocation StartLoc,
6012 SourceLocation LParenLoc,
6013 SourceLocation EndLoc) {
6014 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006015 SmallVector<Expr *, 8> SrcExprs;
6016 SmallVector<Expr *, 8> DstExprs;
6017 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006018 for (auto &RefExpr : VarList) {
6019 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6020 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6021 // It will be analyzed later.
6022 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006023 SrcExprs.push_back(nullptr);
6024 DstExprs.push_back(nullptr);
6025 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006026 continue;
6027 }
6028
6029 SourceLocation ELoc = RefExpr->getExprLoc();
6030 // OpenMP [2.1, C/C++]
6031 // A list item is a variable name.
6032 // OpenMP [2.14.4.1, Restrictions, p.1]
6033 // A list item that appears in a copyin clause must be threadprivate.
6034 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6035 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6036 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6037 continue;
6038 }
6039
6040 Decl *D = DE->getDecl();
6041 VarDecl *VD = cast<VarDecl>(D);
6042
6043 QualType Type = VD->getType();
6044 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6045 // It will be analyzed later.
6046 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006047 SrcExprs.push_back(nullptr);
6048 DstExprs.push_back(nullptr);
6049 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006050 continue;
6051 }
6052
6053 // OpenMP [2.14.4.2, Restrictions, p.2]
6054 // A list item that appears in a copyprivate clause may not appear in a
6055 // private or firstprivate clause on the single construct.
6056 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006057 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006058 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6059 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006060 Diag(ELoc, diag::err_omp_wrong_dsa)
6061 << getOpenMPClauseName(DVar.CKind)
6062 << getOpenMPClauseName(OMPC_copyprivate);
6063 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6064 continue;
6065 }
6066
6067 // OpenMP [2.11.4.2, Restrictions, p.1]
6068 // All list items that appear in a copyprivate clause must be either
6069 // threadprivate or private in the enclosing context.
6070 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006071 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006072 if (DVar.CKind == OMPC_shared) {
6073 Diag(ELoc, diag::err_omp_required_access)
6074 << getOpenMPClauseName(OMPC_copyprivate)
6075 << "threadprivate or private in the enclosing context";
6076 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6077 continue;
6078 }
6079 }
6080 }
6081
6082 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6083 // A variable of class type (or array thereof) that appears in a
6084 // copyin clause requires an accessible, unambiguous copy assignment
6085 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006086 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6087 auto *SrcVD =
6088 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6089 auto *PseudoSrcExpr =
6090 BuildDeclRefExpr(SrcVD, Type, VK_LValue, DE->getExprLoc()).get();
6091 auto *DstVD =
6092 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6093 auto *PseudoDstExpr =
6094 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
Alexey Bataeva63048e2015-03-23 06:18:07 +00006095 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6096 PseudoDstExpr, PseudoSrcExpr);
6097 if (AssignmentOp.isInvalid())
6098 continue;
6099 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6100 /*DiscardedValue=*/true);
6101 if (AssignmentOp.isInvalid())
6102 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006103
6104 // No need to mark vars as copyprivate, they are already threadprivate or
6105 // implicitly private.
6106 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006107 SrcExprs.push_back(PseudoSrcExpr);
6108 DstExprs.push_back(PseudoDstExpr);
6109 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006110 }
6111
6112 if (Vars.empty())
6113 return nullptr;
6114
Alexey Bataeva63048e2015-03-23 06:18:07 +00006115 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6116 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006117}
6118
Alexey Bataev6125da92014-07-21 11:26:11 +00006119OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6120 SourceLocation StartLoc,
6121 SourceLocation LParenLoc,
6122 SourceLocation EndLoc) {
6123 if (VarList.empty())
6124 return nullptr;
6125
6126 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6127}
Alexey Bataevdea47612014-07-23 07:46:59 +00006128