blob: 92552207813aba323b30c9c2e65a010da3c63894 [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.
762 if (VD->isUsed()) {
763 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: {
1120 Sema::CapturedParamNameType Params[] = {
1121 std::make_pair(StringRef(), QualType()) // __context with shared vars
1122 };
1123 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1124 Params);
1125 break;
1126 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001127 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001128 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001129 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001130 std::make_pair(".global_tid.", KmpInt32Ty),
1131 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001132 std::make_pair(StringRef(), QualType()) // __context with shared vars
1133 };
1134 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1135 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001136 // Mark this captured region as inlined, because we don't use outlined
1137 // function directly.
1138 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1139 AlwaysInlineAttr::CreateImplicit(
1140 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001141 break;
1142 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001143 case OMPD_ordered: {
1144 Sema::CapturedParamNameType Params[] = {
1145 std::make_pair(StringRef(), QualType()) // __context with shared vars
1146 };
1147 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1148 Params);
1149 break;
1150 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001151 case OMPD_atomic: {
1152 Sema::CapturedParamNameType Params[] = {
1153 std::make_pair(StringRef(), QualType()) // __context with shared vars
1154 };
1155 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1156 Params);
1157 break;
1158 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001159 case OMPD_target: {
1160 Sema::CapturedParamNameType Params[] = {
1161 std::make_pair(StringRef(), QualType()) // __context with shared vars
1162 };
1163 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1164 Params);
1165 break;
1166 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001167 case OMPD_teams: {
1168 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1169 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1170 Sema::CapturedParamNameType Params[] = {
1171 std::make_pair(".global_tid.", KmpInt32PtrTy),
1172 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1173 std::make_pair(StringRef(), QualType()) // __context with shared vars
1174 };
1175 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1176 Params);
1177 break;
1178 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001179 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001180 case OMPD_taskyield:
1181 case OMPD_barrier:
1182 case OMPD_taskwait:
1183 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001184 llvm_unreachable("OpenMP Directive is not allowed");
1185 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001186 llvm_unreachable("Unknown OpenMP directive");
1187 }
1188}
1189
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001190StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1191 ArrayRef<OMPClause *> Clauses) {
1192 if (!S.isUsable()) {
1193 ActOnCapturedRegionError();
1194 return StmtError();
1195 }
1196 // Mark all variables in private list clauses as used in inner region. This is
1197 // required for proper codegen.
1198 for (auto *Clause : Clauses) {
1199 if (isOpenMPPrivate(Clause->getClauseKind())) {
1200 for (auto *VarRef : Clause->children()) {
1201 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001202 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001203 }
1204 }
1205 }
1206 }
1207 return ActOnCapturedRegionEnd(S.get());
1208}
1209
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001210static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1211 OpenMPDirectiveKind CurrentRegion,
1212 const DeclarationNameInfo &CurrentName,
1213 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001214 // Allowed nesting of constructs
1215 // +------------------+-----------------+------------------------------------+
1216 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1217 // +------------------+-----------------+------------------------------------+
1218 // | parallel | parallel | * |
1219 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001220 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001221 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001222 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001223 // | parallel | simd | * |
1224 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001225 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001226 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001227 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001228 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001229 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001230 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001231 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001232 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001233 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001234 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001235 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001236 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001237 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001238 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001239 // +------------------+-----------------+------------------------------------+
1240 // | for | parallel | * |
1241 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001242 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001243 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001244 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001245 // | for | simd | * |
1246 // | for | sections | + |
1247 // | for | section | + |
1248 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001249 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001250 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001251 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001252 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001253 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001254 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001255 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001256 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001257 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001258 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001259 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001260 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001261 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001262 // | master | parallel | * |
1263 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001264 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001265 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001266 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001267 // | master | simd | * |
1268 // | master | sections | + |
1269 // | master | section | + |
1270 // | master | single | + |
1271 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001272 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001273 // | master |parallel sections| * |
1274 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001275 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001276 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001277 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001278 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001279 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001280 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001281 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001282 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001283 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001284 // | critical | parallel | * |
1285 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001286 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001287 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001288 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001289 // | critical | simd | * |
1290 // | critical | sections | + |
1291 // | critical | section | + |
1292 // | critical | single | + |
1293 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001294 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001295 // | critical |parallel sections| * |
1296 // | critical | task | * |
1297 // | critical | taskyield | * |
1298 // | critical | barrier | + |
1299 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001300 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001301 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001302 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001303 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001304 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001305 // | simd | parallel | |
1306 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001307 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001308 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001309 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001310 // | simd | simd | |
1311 // | simd | sections | |
1312 // | simd | section | |
1313 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001314 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001315 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001316 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001317 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001318 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001319 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001320 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001321 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001322 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001323 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001324 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001325 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001326 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001327 // | for simd | parallel | |
1328 // | for simd | for | |
1329 // | for simd | for simd | |
1330 // | for simd | master | |
1331 // | for simd | critical | |
1332 // | for simd | simd | |
1333 // | for simd | sections | |
1334 // | for simd | section | |
1335 // | for simd | single | |
1336 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001337 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001338 // | for simd |parallel sections| |
1339 // | for simd | task | |
1340 // | for simd | taskyield | |
1341 // | for simd | barrier | |
1342 // | for simd | taskwait | |
1343 // | for simd | flush | |
1344 // | for simd | ordered | |
1345 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001346 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001347 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001348 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001349 // | parallel for simd| parallel | |
1350 // | parallel for simd| for | |
1351 // | parallel for simd| for simd | |
1352 // | parallel for simd| master | |
1353 // | parallel for simd| critical | |
1354 // | parallel for simd| simd | |
1355 // | parallel for simd| sections | |
1356 // | parallel for simd| section | |
1357 // | parallel for simd| single | |
1358 // | parallel for simd| parallel for | |
1359 // | parallel for simd|parallel for simd| |
1360 // | parallel for simd|parallel sections| |
1361 // | parallel for simd| task | |
1362 // | parallel for simd| taskyield | |
1363 // | parallel for simd| barrier | |
1364 // | parallel for simd| taskwait | |
1365 // | parallel for simd| flush | |
1366 // | parallel for simd| ordered | |
1367 // | parallel for simd| atomic | |
1368 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001369 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001370 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001371 // | sections | parallel | * |
1372 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001373 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001374 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001375 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001376 // | sections | simd | * |
1377 // | sections | sections | + |
1378 // | sections | section | * |
1379 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001380 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001381 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001382 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001383 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001384 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001385 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001386 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001387 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001388 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001389 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001390 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001391 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001392 // +------------------+-----------------+------------------------------------+
1393 // | section | parallel | * |
1394 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001395 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001396 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001397 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001398 // | section | simd | * |
1399 // | section | sections | + |
1400 // | section | section | + |
1401 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001402 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001403 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001404 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001405 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001406 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001407 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001408 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001409 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001410 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001411 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001412 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001413 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001414 // +------------------+-----------------+------------------------------------+
1415 // | single | parallel | * |
1416 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001417 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001418 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001419 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001420 // | single | simd | * |
1421 // | single | sections | + |
1422 // | single | section | + |
1423 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001424 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001425 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001426 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001427 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001428 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001429 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001430 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001431 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001432 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001433 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001434 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001435 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001436 // +------------------+-----------------+------------------------------------+
1437 // | parallel for | parallel | * |
1438 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001439 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001440 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001441 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001442 // | parallel for | simd | * |
1443 // | parallel for | sections | + |
1444 // | parallel for | section | + |
1445 // | parallel for | single | + |
1446 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001447 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001448 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001450 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001451 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001452 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001453 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001454 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001455 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001456 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001457 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001458 // +------------------+-----------------+------------------------------------+
1459 // | parallel sections| parallel | * |
1460 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001461 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001462 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001463 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001464 // | parallel sections| simd | * |
1465 // | parallel sections| sections | + |
1466 // | parallel sections| section | * |
1467 // | parallel sections| single | + |
1468 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001469 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001470 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001471 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001472 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001473 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001474 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001475 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001476 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001477 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001478 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001479 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001480 // +------------------+-----------------+------------------------------------+
1481 // | task | parallel | * |
1482 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001483 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001484 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001485 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001486 // | task | simd | * |
1487 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001488 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 // | task | single | + |
1490 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001491 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001492 // | task |parallel sections| * |
1493 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001494 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001495 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001496 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001497 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001498 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001499 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001500 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001501 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001502 // +------------------+-----------------+------------------------------------+
1503 // | ordered | parallel | * |
1504 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001505 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001506 // | ordered | master | * |
1507 // | ordered | critical | * |
1508 // | ordered | simd | * |
1509 // | ordered | sections | + |
1510 // | ordered | section | + |
1511 // | ordered | single | + |
1512 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001513 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001514 // | ordered |parallel sections| * |
1515 // | ordered | task | * |
1516 // | ordered | taskyield | * |
1517 // | ordered | barrier | + |
1518 // | ordered | taskwait | * |
1519 // | ordered | flush | * |
1520 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001521 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001522 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001523 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001524 // +------------------+-----------------+------------------------------------+
1525 // | atomic | parallel | |
1526 // | atomic | for | |
1527 // | atomic | for simd | |
1528 // | atomic | master | |
1529 // | atomic | critical | |
1530 // | atomic | simd | |
1531 // | atomic | sections | |
1532 // | atomic | section | |
1533 // | atomic | single | |
1534 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001535 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001536 // | atomic |parallel sections| |
1537 // | atomic | task | |
1538 // | atomic | taskyield | |
1539 // | atomic | barrier | |
1540 // | atomic | taskwait | |
1541 // | atomic | flush | |
1542 // | atomic | ordered | |
1543 // | atomic | atomic | |
1544 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001545 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001546 // +------------------+-----------------+------------------------------------+
1547 // | target | parallel | * |
1548 // | target | for | * |
1549 // | target | for simd | * |
1550 // | target | master | * |
1551 // | target | critical | * |
1552 // | target | simd | * |
1553 // | target | sections | * |
1554 // | target | section | * |
1555 // | target | single | * |
1556 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001557 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001558 // | target |parallel sections| * |
1559 // | target | task | * |
1560 // | target | taskyield | * |
1561 // | target | barrier | * |
1562 // | target | taskwait | * |
1563 // | target | flush | * |
1564 // | target | ordered | * |
1565 // | target | atomic | * |
1566 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001567 // | target | teams | * |
1568 // +------------------+-----------------+------------------------------------+
1569 // | teams | parallel | * |
1570 // | teams | for | + |
1571 // | teams | for simd | + |
1572 // | teams | master | + |
1573 // | teams | critical | + |
1574 // | teams | simd | + |
1575 // | teams | sections | + |
1576 // | teams | section | + |
1577 // | teams | single | + |
1578 // | teams | parallel for | * |
1579 // | teams |parallel for simd| * |
1580 // | teams |parallel sections| * |
1581 // | teams | task | + |
1582 // | teams | taskyield | + |
1583 // | teams | barrier | + |
1584 // | teams | taskwait | + |
1585 // | teams | flush | + |
1586 // | teams | ordered | + |
1587 // | teams | atomic | + |
1588 // | teams | target | + |
1589 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001590 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001591 if (Stack->getCurScope()) {
1592 auto ParentRegion = Stack->getParentDirective();
1593 bool NestingProhibited = false;
1594 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001595 enum {
1596 NoRecommend,
1597 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001598 ShouldBeInOrderedRegion,
1599 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001600 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001601 if (isOpenMPSimdDirective(ParentRegion)) {
1602 // OpenMP [2.16, Nesting of Regions]
1603 // OpenMP constructs may not be nested inside a simd region.
1604 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1605 return true;
1606 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001607 if (ParentRegion == OMPD_atomic) {
1608 // OpenMP [2.16, Nesting of Regions]
1609 // OpenMP constructs may not be nested inside an atomic region.
1610 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1611 return true;
1612 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001613 if (CurrentRegion == OMPD_section) {
1614 // OpenMP [2.7.2, sections Construct, Restrictions]
1615 // Orphaned section directives are prohibited. That is, the section
1616 // directives must appear within the sections construct and must not be
1617 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001618 if (ParentRegion != OMPD_sections &&
1619 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001620 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1621 << (ParentRegion != OMPD_unknown)
1622 << getOpenMPDirectiveName(ParentRegion);
1623 return true;
1624 }
1625 return false;
1626 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001627 // Allow some constructs to be orphaned (they could be used in functions,
1628 // called from OpenMP regions with the required preconditions).
1629 if (ParentRegion == OMPD_unknown)
1630 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001631 if (CurrentRegion == OMPD_master) {
1632 // OpenMP [2.16, Nesting of Regions]
1633 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001634 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001635 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1636 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001637 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1638 // OpenMP [2.16, Nesting of Regions]
1639 // A critical region may not be nested (closely or otherwise) inside a
1640 // critical region with the same name. Note that this restriction is not
1641 // sufficient to prevent deadlock.
1642 SourceLocation PreviousCriticalLoc;
1643 bool DeadLock =
1644 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1645 OpenMPDirectiveKind K,
1646 const DeclarationNameInfo &DNI,
1647 SourceLocation Loc)
1648 ->bool {
1649 if (K == OMPD_critical &&
1650 DNI.getName() == CurrentName.getName()) {
1651 PreviousCriticalLoc = Loc;
1652 return true;
1653 } else
1654 return false;
1655 },
1656 false /* skip top directive */);
1657 if (DeadLock) {
1658 SemaRef.Diag(StartLoc,
1659 diag::err_omp_prohibited_region_critical_same_name)
1660 << CurrentName.getName();
1661 if (PreviousCriticalLoc.isValid())
1662 SemaRef.Diag(PreviousCriticalLoc,
1663 diag::note_omp_previous_critical_region);
1664 return true;
1665 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001666 } else if (CurrentRegion == OMPD_barrier) {
1667 // OpenMP [2.16, Nesting of Regions]
1668 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001669 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001670 NestingProhibited =
1671 isOpenMPWorksharingDirective(ParentRegion) ||
1672 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1673 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001674 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001675 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001676 // OpenMP [2.16, Nesting of Regions]
1677 // A worksharing region may not be closely nested inside a worksharing,
1678 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001679 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001680 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001681 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1682 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1683 Recommend = ShouldBeInParallelRegion;
1684 } else if (CurrentRegion == OMPD_ordered) {
1685 // OpenMP [2.16, Nesting of Regions]
1686 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001687 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001688 // An ordered region must be closely nested inside a loop region (or
1689 // parallel loop region) with an ordered clause.
1690 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001691 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001692 !Stack->isParentOrderedRegion();
1693 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001694 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1695 // OpenMP [2.16, Nesting of Regions]
1696 // If specified, a teams construct must be contained within a target
1697 // construct.
1698 NestingProhibited = ParentRegion != OMPD_target;
1699 Recommend = ShouldBeInTargetRegion;
1700 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1701 }
1702 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1703 // OpenMP [2.16, Nesting of Regions]
1704 // distribute, parallel, parallel sections, parallel workshare, and the
1705 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1706 // constructs that can be closely nested in the teams region.
1707 // TODO: add distribute directive.
1708 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1709 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001710 }
1711 if (NestingProhibited) {
1712 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001713 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1714 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001715 return true;
1716 }
1717 }
1718 return false;
1719}
1720
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001721StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001722 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001723 ArrayRef<OMPClause *> Clauses,
1724 Stmt *AStmt,
1725 SourceLocation StartLoc,
1726 SourceLocation EndLoc) {
1727 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001728 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001729 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001730
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001731 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001732 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001733 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001734 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001735 if (AStmt) {
1736 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1737
1738 // Check default data sharing attributes for referenced variables.
1739 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1740 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1741 if (DSAChecker.isErrorFound())
1742 return StmtError();
1743 // Generate list of implicitly defined firstprivate variables.
1744 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001745
1746 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1747 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1748 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1749 SourceLocation(), SourceLocation())) {
1750 ClausesWithImplicit.push_back(Implicit);
1751 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1752 DSAChecker.getImplicitFirstprivate().size();
1753 } else
1754 ErrorFound = true;
1755 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001756 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001757
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001758 switch (Kind) {
1759 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001760 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1761 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001762 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001763 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001764 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1765 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001766 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001767 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001768 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1769 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001770 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001771 case OMPD_for_simd:
1772 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1773 EndLoc, VarsWithInheritedDSA);
1774 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001775 case OMPD_sections:
1776 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1777 EndLoc);
1778 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001779 case OMPD_section:
1780 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001781 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001782 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1783 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001784 case OMPD_single:
1785 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1786 EndLoc);
1787 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001788 case OMPD_master:
1789 assert(ClausesWithImplicit.empty() &&
1790 "No clauses are allowed for 'omp master' directive");
1791 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1792 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001793 case OMPD_critical:
1794 assert(ClausesWithImplicit.empty() &&
1795 "No clauses are allowed for 'omp critical' directive");
1796 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1797 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001798 case OMPD_parallel_for:
1799 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1800 EndLoc, VarsWithInheritedDSA);
1801 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001802 case OMPD_parallel_for_simd:
1803 Res = ActOnOpenMPParallelForSimdDirective(
1804 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1805 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001806 case OMPD_parallel_sections:
1807 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1808 StartLoc, EndLoc);
1809 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001810 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001811 Res =
1812 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1813 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001814 case OMPD_taskyield:
1815 assert(ClausesWithImplicit.empty() &&
1816 "No clauses are allowed for 'omp taskyield' directive");
1817 assert(AStmt == nullptr &&
1818 "No associated statement allowed for 'omp taskyield' directive");
1819 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1820 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001821 case OMPD_barrier:
1822 assert(ClausesWithImplicit.empty() &&
1823 "No clauses are allowed for 'omp barrier' directive");
1824 assert(AStmt == nullptr &&
1825 "No associated statement allowed for 'omp barrier' directive");
1826 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1827 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001828 case OMPD_taskwait:
1829 assert(ClausesWithImplicit.empty() &&
1830 "No clauses are allowed for 'omp taskwait' directive");
1831 assert(AStmt == nullptr &&
1832 "No associated statement allowed for 'omp taskwait' directive");
1833 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1834 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001835 case OMPD_flush:
1836 assert(AStmt == nullptr &&
1837 "No associated statement allowed for 'omp flush' directive");
1838 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1839 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001840 case OMPD_ordered:
1841 assert(ClausesWithImplicit.empty() &&
1842 "No clauses are allowed for 'omp ordered' directive");
1843 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1844 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001845 case OMPD_atomic:
1846 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1847 EndLoc);
1848 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001849 case OMPD_teams:
1850 Res =
1851 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1852 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001853 case OMPD_target:
1854 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1855 EndLoc);
1856 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001857 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001858 llvm_unreachable("OpenMP Directive is not allowed");
1859 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001860 llvm_unreachable("Unknown OpenMP directive");
1861 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001862
Alexey Bataev4acb8592014-07-07 13:01:15 +00001863 for (auto P : VarsWithInheritedDSA) {
1864 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1865 << P.first << P.second->getSourceRange();
1866 }
1867 if (!VarsWithInheritedDSA.empty())
1868 return StmtError();
1869
Alexey Bataeved09d242014-05-28 05:53:51 +00001870 if (ErrorFound)
1871 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001872 return Res;
1873}
1874
1875StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1876 Stmt *AStmt,
1877 SourceLocation StartLoc,
1878 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001879 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1880 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1881 // 1.2.2 OpenMP Language Terminology
1882 // Structured block - An executable statement with a single entry at the
1883 // top and a single exit at the bottom.
1884 // The point of exit cannot be a branch out of the structured block.
1885 // longjmp() and throw() must not violate the entry/exit criteria.
1886 CS->getCapturedDecl()->setNothrow();
1887
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001888 getCurFunction()->setHasBranchProtectedScope();
1889
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001890 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1891 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001892}
1893
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001894namespace {
1895/// \brief Helper class for checking canonical form of the OpenMP loops and
1896/// extracting iteration space of each loop in the loop nest, that will be used
1897/// for IR generation.
1898class OpenMPIterationSpaceChecker {
1899 /// \brief Reference to Sema.
1900 Sema &SemaRef;
1901 /// \brief A location for diagnostics (when there is no some better location).
1902 SourceLocation DefaultLoc;
1903 /// \brief A location for diagnostics (when increment is not compatible).
1904 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001905 /// \brief A source location for referring to loop init later.
1906 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001907 /// \brief A source location for referring to condition later.
1908 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001909 /// \brief A source location for referring to increment later.
1910 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001911 /// \brief Loop variable.
1912 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001913 /// \brief Reference to loop variable.
1914 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001915 /// \brief Lower bound (initializer for the var).
1916 Expr *LB;
1917 /// \brief Upper bound.
1918 Expr *UB;
1919 /// \brief Loop step (increment).
1920 Expr *Step;
1921 /// \brief This flag is true when condition is one of:
1922 /// Var < UB
1923 /// Var <= UB
1924 /// UB > Var
1925 /// UB >= Var
1926 bool TestIsLessOp;
1927 /// \brief This flag is true when condition is strict ( < or > ).
1928 bool TestIsStrictOp;
1929 /// \brief This flag is true when step is subtracted on each iteration.
1930 bool SubtractStep;
1931
1932public:
1933 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1934 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00001935 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1936 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001937 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1938 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001939 /// \brief Check init-expr for canonical loop form and save loop counter
1940 /// variable - #Var and its initialization value - #LB.
1941 bool CheckInit(Stmt *S);
1942 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1943 /// for less/greater and for strict/non-strict comparison.
1944 bool CheckCond(Expr *S);
1945 /// \brief Check incr-expr for canonical loop form and return true if it
1946 /// does not conform, otherwise save loop step (#Step).
1947 bool CheckInc(Expr *S);
1948 /// \brief Return the loop counter variable.
1949 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001950 /// \brief Return the reference expression to loop counter variable.
1951 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001952 /// \brief Source range of the loop init.
1953 SourceRange GetInitSrcRange() const { return InitSrcRange; }
1954 /// \brief Source range of the loop condition.
1955 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1956 /// \brief Source range of the loop increment.
1957 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1958 /// \brief True if the step should be subtracted.
1959 bool ShouldSubtractStep() const { return SubtractStep; }
1960 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00001961 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001962 /// \brief Build reference expression to the counter be used for codegen.
1963 Expr *BuildCounterVar() const;
1964 /// \brief Build initization of the counter be used for codegen.
1965 Expr *BuildCounterInit() const;
1966 /// \brief Build step of the counter be used for codegen.
1967 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001968 /// \brief Return true if any expression is dependent.
1969 bool Dependent() const;
1970
1971private:
1972 /// \brief Check the right-hand side of an assignment in the increment
1973 /// expression.
1974 bool CheckIncRHS(Expr *RHS);
1975 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001976 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001977 /// \brief Helper to set upper bound.
1978 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1979 const SourceLocation &SL);
1980 /// \brief Helper to set loop increment.
1981 bool SetStep(Expr *NewStep, bool Subtract);
1982};
1983
1984bool OpenMPIterationSpaceChecker::Dependent() const {
1985 if (!Var) {
1986 assert(!LB && !UB && !Step);
1987 return false;
1988 }
1989 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1990 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1991}
1992
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001993bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
1994 DeclRefExpr *NewVarRefExpr,
1995 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001996 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001997 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
1998 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001999 if (!NewVar || !NewLB)
2000 return true;
2001 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002002 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002003 LB = NewLB;
2004 return false;
2005}
2006
2007bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2008 const SourceRange &SR,
2009 const SourceLocation &SL) {
2010 // State consistency checking to ensure correct usage.
2011 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2012 !TestIsLessOp && !TestIsStrictOp);
2013 if (!NewUB)
2014 return true;
2015 UB = NewUB;
2016 TestIsLessOp = LessOp;
2017 TestIsStrictOp = StrictOp;
2018 ConditionSrcRange = SR;
2019 ConditionLoc = SL;
2020 return false;
2021}
2022
2023bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2024 // State consistency checking to ensure correct usage.
2025 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2026 if (!NewStep)
2027 return true;
2028 if (!NewStep->isValueDependent()) {
2029 // Check that the step is integer expression.
2030 SourceLocation StepLoc = NewStep->getLocStart();
2031 ExprResult Val =
2032 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2033 if (Val.isInvalid())
2034 return true;
2035 NewStep = Val.get();
2036
2037 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2038 // If test-expr is of form var relational-op b and relational-op is < or
2039 // <= then incr-expr must cause var to increase on each iteration of the
2040 // loop. If test-expr is of form var relational-op b and relational-op is
2041 // > or >= then incr-expr must cause var to decrease on each iteration of
2042 // the loop.
2043 // If test-expr is of form b relational-op var and relational-op is < or
2044 // <= then incr-expr must cause var to decrease on each iteration of the
2045 // loop. If test-expr is of form b relational-op var and relational-op is
2046 // > or >= then incr-expr must cause var to increase on each iteration of
2047 // the loop.
2048 llvm::APSInt Result;
2049 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2050 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2051 bool IsConstNeg =
2052 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002053 bool IsConstPos =
2054 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002055 bool IsConstZero = IsConstant && !Result.getBoolValue();
2056 if (UB && (IsConstZero ||
2057 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002058 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002059 SemaRef.Diag(NewStep->getExprLoc(),
2060 diag::err_omp_loop_incr_not_compatible)
2061 << Var << TestIsLessOp << NewStep->getSourceRange();
2062 SemaRef.Diag(ConditionLoc,
2063 diag::note_omp_loop_cond_requres_compatible_incr)
2064 << TestIsLessOp << ConditionSrcRange;
2065 return true;
2066 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002067 if (TestIsLessOp == Subtract) {
2068 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2069 NewStep).get();
2070 Subtract = !Subtract;
2071 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002072 }
2073
2074 Step = NewStep;
2075 SubtractStep = Subtract;
2076 return false;
2077}
2078
2079bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2080 // Check init-expr for canonical loop form and save loop counter
2081 // variable - #Var and its initialization value - #LB.
2082 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2083 // var = lb
2084 // integer-type var = lb
2085 // random-access-iterator-type var = lb
2086 // pointer-type var = lb
2087 //
2088 if (!S) {
2089 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2090 return true;
2091 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002092 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002093 if (Expr *E = dyn_cast<Expr>(S))
2094 S = E->IgnoreParens();
2095 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2096 if (BO->getOpcode() == BO_Assign)
2097 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002098 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002099 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002100 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2101 if (DS->isSingleDecl()) {
2102 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2103 if (Var->hasInit()) {
2104 // Accept non-canonical init form here but emit ext. warning.
2105 if (Var->getInitStyle() != VarDecl::CInit)
2106 SemaRef.Diag(S->getLocStart(),
2107 diag::ext_omp_loop_not_canonical_init)
2108 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002109 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002110 }
2111 }
2112 }
2113 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2114 if (CE->getOperator() == OO_Equal)
2115 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002116 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2117 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002118
2119 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2120 << S->getSourceRange();
2121 return true;
2122}
2123
Alexey Bataev23b69422014-06-18 07:08:49 +00002124/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002125/// variable (which may be the loop variable) if possible.
2126static const VarDecl *GetInitVarDecl(const Expr *E) {
2127 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002128 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002129 E = E->IgnoreParenImpCasts();
2130 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2131 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2132 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2133 CE->getArg(0) != nullptr)
2134 E = CE->getArg(0)->IgnoreParenImpCasts();
2135 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2136 if (!DRE)
2137 return nullptr;
2138 return dyn_cast<VarDecl>(DRE->getDecl());
2139}
2140
2141bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2142 // Check test-expr for canonical form, save upper-bound UB, flags for
2143 // less/greater and for strict/non-strict comparison.
2144 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2145 // var relational-op b
2146 // b relational-op var
2147 //
2148 if (!S) {
2149 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2150 return true;
2151 }
2152 S = S->IgnoreParenImpCasts();
2153 SourceLocation CondLoc = S->getLocStart();
2154 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2155 if (BO->isRelationalOp()) {
2156 if (GetInitVarDecl(BO->getLHS()) == Var)
2157 return SetUB(BO->getRHS(),
2158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2159 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2160 BO->getSourceRange(), BO->getOperatorLoc());
2161 if (GetInitVarDecl(BO->getRHS()) == Var)
2162 return SetUB(BO->getLHS(),
2163 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2164 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2165 BO->getSourceRange(), BO->getOperatorLoc());
2166 }
2167 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2168 if (CE->getNumArgs() == 2) {
2169 auto Op = CE->getOperator();
2170 switch (Op) {
2171 case OO_Greater:
2172 case OO_GreaterEqual:
2173 case OO_Less:
2174 case OO_LessEqual:
2175 if (GetInitVarDecl(CE->getArg(0)) == Var)
2176 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2177 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2178 CE->getOperatorLoc());
2179 if (GetInitVarDecl(CE->getArg(1)) == Var)
2180 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2181 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2182 CE->getOperatorLoc());
2183 break;
2184 default:
2185 break;
2186 }
2187 }
2188 }
2189 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2190 << S->getSourceRange() << Var;
2191 return true;
2192}
2193
2194bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2195 // RHS of canonical loop form increment can be:
2196 // var + incr
2197 // incr + var
2198 // var - incr
2199 //
2200 RHS = RHS->IgnoreParenImpCasts();
2201 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2202 if (BO->isAdditiveOp()) {
2203 bool IsAdd = BO->getOpcode() == BO_Add;
2204 if (GetInitVarDecl(BO->getLHS()) == Var)
2205 return SetStep(BO->getRHS(), !IsAdd);
2206 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2207 return SetStep(BO->getLHS(), false);
2208 }
2209 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2210 bool IsAdd = CE->getOperator() == OO_Plus;
2211 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2212 if (GetInitVarDecl(CE->getArg(0)) == Var)
2213 return SetStep(CE->getArg(1), !IsAdd);
2214 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2215 return SetStep(CE->getArg(0), false);
2216 }
2217 }
2218 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2219 << RHS->getSourceRange() << Var;
2220 return true;
2221}
2222
2223bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2224 // Check incr-expr for canonical loop form and return true if it
2225 // does not conform.
2226 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2227 // ++var
2228 // var++
2229 // --var
2230 // var--
2231 // var += incr
2232 // var -= incr
2233 // var = var + incr
2234 // var = incr + var
2235 // var = var - incr
2236 //
2237 if (!S) {
2238 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2239 return true;
2240 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002241 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002242 S = S->IgnoreParens();
2243 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2244 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2245 return SetStep(
2246 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2247 (UO->isDecrementOp() ? -1 : 1)).get(),
2248 false);
2249 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2250 switch (BO->getOpcode()) {
2251 case BO_AddAssign:
2252 case BO_SubAssign:
2253 if (GetInitVarDecl(BO->getLHS()) == Var)
2254 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2255 break;
2256 case BO_Assign:
2257 if (GetInitVarDecl(BO->getLHS()) == Var)
2258 return CheckIncRHS(BO->getRHS());
2259 break;
2260 default:
2261 break;
2262 }
2263 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2264 switch (CE->getOperator()) {
2265 case OO_PlusPlus:
2266 case OO_MinusMinus:
2267 if (GetInitVarDecl(CE->getArg(0)) == Var)
2268 return SetStep(
2269 SemaRef.ActOnIntegerConstant(
2270 CE->getLocStart(),
2271 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2272 false);
2273 break;
2274 case OO_PlusEqual:
2275 case OO_MinusEqual:
2276 if (GetInitVarDecl(CE->getArg(0)) == Var)
2277 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2278 break;
2279 case OO_Equal:
2280 if (GetInitVarDecl(CE->getArg(0)) == Var)
2281 return CheckIncRHS(CE->getArg(1));
2282 break;
2283 default:
2284 break;
2285 }
2286 }
2287 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2288 << S->getSourceRange() << Var;
2289 return true;
2290}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002291
2292/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002293Expr *
2294OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2295 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002296 ExprResult Diff;
2297 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2298 SemaRef.getLangOpts().CPlusPlus) {
2299 // Upper - Lower
2300 Expr *Upper = TestIsLessOp ? UB : LB;
2301 Expr *Lower = TestIsLessOp ? LB : UB;
2302
2303 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2304
2305 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2306 // BuildBinOp already emitted error, this one is to point user to upper
2307 // and lower bound, and to tell what is passed to 'operator-'.
2308 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2309 << Upper->getSourceRange() << Lower->getSourceRange();
2310 return nullptr;
2311 }
2312 }
2313
2314 if (!Diff.isUsable())
2315 return nullptr;
2316
2317 // Upper - Lower [- 1]
2318 if (TestIsStrictOp)
2319 Diff = SemaRef.BuildBinOp(
2320 S, DefaultLoc, BO_Sub, Diff.get(),
2321 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2322 if (!Diff.isUsable())
2323 return nullptr;
2324
2325 // Upper - Lower [- 1] + Step
2326 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2327 Step->IgnoreImplicit());
2328 if (!Diff.isUsable())
2329 return nullptr;
2330
2331 // Parentheses (for dumping/debugging purposes only).
2332 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2333 if (!Diff.isUsable())
2334 return nullptr;
2335
2336 // (Upper - Lower [- 1] + Step) / Step
2337 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2338 Step->IgnoreImplicit());
2339 if (!Diff.isUsable())
2340 return nullptr;
2341
Alexander Musman174b3ca2014-10-06 11:16:29 +00002342 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2343 if (LimitedType) {
2344 auto &C = SemaRef.Context;
2345 QualType Type = Diff.get()->getType();
2346 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2347 if (NewSize != C.getTypeSize(Type)) {
2348 if (NewSize < C.getTypeSize(Type)) {
2349 assert(NewSize == 64 && "incorrect loop var size");
2350 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2351 << InitSrcRange << ConditionSrcRange;
2352 }
2353 QualType NewType = C.getIntTypeForBitwidth(
2354 NewSize, Type->hasSignedIntegerRepresentation());
2355 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2356 Sema::AA_Converting, true);
2357 if (!Diff.isUsable())
2358 return nullptr;
2359 }
2360 }
2361
Alexander Musmana5f070a2014-10-01 06:03:56 +00002362 return Diff.get();
2363}
2364
2365/// \brief Build reference expression to the counter be used for codegen.
2366Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2367 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2368 GetIncrementSrcRange().getBegin(), Var, false,
2369 DefaultLoc, Var->getType(), VK_LValue);
2370}
2371
2372/// \brief Build initization of the counter be used for codegen.
2373Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2374
2375/// \brief Build step of the counter be used for codegen.
2376Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2377
2378/// \brief Iteration space of a single for loop.
2379struct LoopIterationSpace {
2380 /// \brief This expression calculates the number of iterations in the loop.
2381 /// It is always possible to calculate it before starting the loop.
2382 Expr *NumIterations;
2383 /// \brief The loop counter variable.
2384 Expr *CounterVar;
2385 /// \brief This is initializer for the initial value of #CounterVar.
2386 Expr *CounterInit;
2387 /// \brief This is step for the #CounterVar used to generate its update:
2388 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2389 Expr *CounterStep;
2390 /// \brief Should step be subtracted?
2391 bool Subtract;
2392 /// \brief Source range of the loop init.
2393 SourceRange InitSrcRange;
2394 /// \brief Source range of the loop condition.
2395 SourceRange CondSrcRange;
2396 /// \brief Source range of the loop increment.
2397 SourceRange IncSrcRange;
2398};
2399
Alexey Bataev23b69422014-06-18 07:08:49 +00002400} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002401
2402/// \brief Called on a for stmt to check and extract its iteration space
2403/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002404static bool CheckOpenMPIterationSpace(
2405 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2406 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2407 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002408 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2409 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002410 // OpenMP [2.6, Canonical Loop Form]
2411 // for (init-expr; test-expr; incr-expr) structured-block
2412 auto For = dyn_cast_or_null<ForStmt>(S);
2413 if (!For) {
2414 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002415 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2416 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2417 << CurrentNestedLoopCount;
2418 if (NestedLoopCount > 1)
2419 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2420 diag::note_omp_collapse_expr)
2421 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002422 return true;
2423 }
2424 assert(For->getBody());
2425
2426 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2427
2428 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002429 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002430 if (ISC.CheckInit(Init)) {
2431 return true;
2432 }
2433
2434 bool HasErrors = false;
2435
2436 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002437 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002438
2439 // OpenMP [2.6, Canonical Loop Form]
2440 // Var is one of the following:
2441 // A variable of signed or unsigned integer type.
2442 // For C++, a variable of a random access iterator type.
2443 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002444 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002445 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2446 !VarType->isPointerType() &&
2447 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2448 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2449 << SemaRef.getLangOpts().CPlusPlus;
2450 HasErrors = true;
2451 }
2452
Alexey Bataev4acb8592014-07-07 13:01:15 +00002453 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2454 // Construct
2455 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2456 // parallel for construct is (are) private.
2457 // The loop iteration variable in the associated for-loop of a simd construct
2458 // with just one associated for-loop is linear with a constant-linear-step
2459 // that is the increment of the associated for-loop.
2460 // Exclude loop var from the list of variables with implicitly defined data
2461 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002462 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002463
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002464 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2465 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002466 // The loop iteration variable in the associated for-loop of a simd construct
2467 // with just one associated for-loop may be listed in a linear clause with a
2468 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002469 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2470 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002471 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002472 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2473 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2474 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002475 auto PredeterminedCKind =
2476 isOpenMPSimdDirective(DKind)
2477 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2478 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002479 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002480 DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002481 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2482 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2483 DVar.CKind != OMPC_lastprivate)) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00002484 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002485 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002486 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2487 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002488 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002489 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002490 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002491 // Make the loop iteration variable private (for worksharing constructs),
2492 // linear (for simd directives with the only one associated loop) or
2493 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002494 // FIXME: the next check and error message must be removed once the
2495 // capturing of global variables in loops is fixed.
2496 if (DVar.CKind == OMPC_unknown)
2497 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2498 /*FromParent=*/false);
2499 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2500 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2501 << getOpenMPClauseName(PredeterminedCKind)
2502 << getOpenMPDirectiveName(DKind);
2503 HasErrors = true;
2504 } else
2505 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002506 }
2507
Alexey Bataev7ff55242014-06-19 09:13:45 +00002508 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002509
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002510 // Check test-expr.
2511 HasErrors |= ISC.CheckCond(For->getCond());
2512
2513 // Check incr-expr.
2514 HasErrors |= ISC.CheckInc(For->getInc());
2515
Alexander Musmana5f070a2014-10-01 06:03:56 +00002516 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002517 return HasErrors;
2518
Alexander Musmana5f070a2014-10-01 06:03:56 +00002519 // Build the loop's iteration space representation.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002520 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2521 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002522 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2523 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2524 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2525 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2526 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2527 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2528 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2529
2530 HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
2531 ResultIterSpace.CounterVar == nullptr ||
2532 ResultIterSpace.CounterInit == nullptr ||
2533 ResultIterSpace.CounterStep == nullptr);
2534
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002535 return HasErrors;
2536}
2537
Alexander Musmana5f070a2014-10-01 06:03:56 +00002538/// \brief Build a variable declaration for OpenMP loop iteration variable.
2539static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2540 StringRef Name) {
2541 DeclContext *DC = SemaRef.CurContext;
2542 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2543 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2544 VarDecl *Decl =
2545 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2546 Decl->setImplicit();
2547 return Decl;
2548}
2549
2550/// \brief Build 'VarRef = Start + Iter * Step'.
2551static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2552 SourceLocation Loc, ExprResult VarRef,
2553 ExprResult Start, ExprResult Iter,
2554 ExprResult Step, bool Subtract) {
2555 // Add parentheses (for debugging purposes only).
2556 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2557 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2558 !Step.isUsable())
2559 return ExprError();
2560
2561 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2562 Step.get()->IgnoreImplicit());
2563 if (!Update.isUsable())
2564 return ExprError();
2565
2566 // Build 'VarRef = Start + Iter * Step'.
2567 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2568 Start.get()->IgnoreImplicit(), Update.get());
2569 if (!Update.isUsable())
2570 return ExprError();
2571
2572 Update = SemaRef.PerformImplicitConversion(
2573 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2574 if (!Update.isUsable())
2575 return ExprError();
2576
2577 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2578 return Update;
2579}
2580
2581/// \brief Convert integer expression \a E to make it have at least \a Bits
2582/// bits.
2583static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2584 Sema &SemaRef) {
2585 if (E == nullptr)
2586 return ExprError();
2587 auto &C = SemaRef.Context;
2588 QualType OldType = E->getType();
2589 unsigned HasBits = C.getTypeSize(OldType);
2590 if (HasBits >= Bits)
2591 return ExprResult(E);
2592 // OK to convert to signed, because new type has more bits than old.
2593 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2594 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2595 true);
2596}
2597
2598/// \brief Check if the given expression \a E is a constant integer that fits
2599/// into \a Bits bits.
2600static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2601 if (E == nullptr)
2602 return false;
2603 llvm::APSInt Result;
2604 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2605 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2606 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002607}
2608
2609/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002610/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2611/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002612static unsigned
2613CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2614 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002615 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002616 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002617 unsigned NestedLoopCount = 1;
2618 if (NestedLoopCountExpr) {
2619 // Found 'collapse' clause - calculate collapse number.
2620 llvm::APSInt Result;
2621 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2622 NestedLoopCount = Result.getLimitedValue();
2623 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002624 // This is helper routine for loop directives (e.g., 'for', 'simd',
2625 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002626 SmallVector<LoopIterationSpace, 4> IterSpaces;
2627 IterSpaces.resize(NestedLoopCount);
2628 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002629 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002630 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002631 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002632 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002633 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002634 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002635 // OpenMP [2.8.1, simd construct, Restrictions]
2636 // All loops associated with the construct must be perfectly nested; that
2637 // is, there must be no intervening code nor any OpenMP directive between
2638 // any two loops.
2639 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002640 }
2641
Alexander Musmana5f070a2014-10-01 06:03:56 +00002642 Built.clear(/* size */ NestedLoopCount);
2643
2644 if (SemaRef.CurContext->isDependentContext())
2645 return NestedLoopCount;
2646
2647 // An example of what is generated for the following code:
2648 //
2649 // #pragma omp simd collapse(2)
2650 // for (i = 0; i < NI; ++i)
2651 // for (j = J0; j < NJ; j+=2) {
2652 // <loop body>
2653 // }
2654 //
2655 // We generate the code below.
2656 // Note: the loop body may be outlined in CodeGen.
2657 // Note: some counters may be C++ classes, operator- is used to find number of
2658 // iterations and operator+= to calculate counter value.
2659 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2660 // or i64 is currently supported).
2661 //
2662 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2663 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2664 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2665 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2666 // // similar updates for vars in clauses (e.g. 'linear')
2667 // <loop body (using local i and j)>
2668 // }
2669 // i = NI; // assign final values of counters
2670 // j = NJ;
2671 //
2672
2673 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2674 // the iteration counts of the collapsed for loops.
2675 auto N0 = IterSpaces[0].NumIterations;
2676 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2677 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2678
2679 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2680 return NestedLoopCount;
2681
2682 auto &C = SemaRef.Context;
2683 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2684
2685 Scope *CurScope = DSA.getCurScope();
2686 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2687 auto N = IterSpaces[Cnt].NumIterations;
2688 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2689 if (LastIteration32.isUsable())
2690 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2691 LastIteration32.get(), N);
2692 if (LastIteration64.isUsable())
2693 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2694 LastIteration64.get(), N);
2695 }
2696
2697 // Choose either the 32-bit or 64-bit version.
2698 ExprResult LastIteration = LastIteration64;
2699 if (LastIteration32.isUsable() &&
2700 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2701 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2702 FitsInto(
2703 32 /* Bits */,
2704 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2705 LastIteration64.get(), SemaRef)))
2706 LastIteration = LastIteration32;
2707
2708 if (!LastIteration.isUsable())
2709 return 0;
2710
2711 // Save the number of iterations.
2712 ExprResult NumIterations = LastIteration;
2713 {
2714 LastIteration = SemaRef.BuildBinOp(
2715 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2716 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2717 if (!LastIteration.isUsable())
2718 return 0;
2719 }
2720
2721 // Calculate the last iteration number beforehand instead of doing this on
2722 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2723 llvm::APSInt Result;
2724 bool IsConstant =
2725 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2726 ExprResult CalcLastIteration;
2727 if (!IsConstant) {
2728 SourceLocation SaveLoc;
2729 VarDecl *SaveVar =
2730 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2731 ".omp.last.iteration");
2732 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2733 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2734 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2735 SaveRef.get(), LastIteration.get());
2736 LastIteration = SaveRef;
2737
2738 // Prepare SaveRef + 1.
2739 NumIterations = SemaRef.BuildBinOp(
2740 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2741 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2742 if (!NumIterations.isUsable())
2743 return 0;
2744 }
2745
2746 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2747
2748 // Precondition tests if there is at least one iteration (LastIteration > 0).
2749 ExprResult PreCond = SemaRef.BuildBinOp(
2750 CurScope, InitLoc, BO_GT, LastIteration.get(),
2751 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2752
Alexander Musmanc6388682014-12-15 07:07:06 +00002753 QualType VType = LastIteration.get()->getType();
2754 // Build variables passed into runtime, nesessary for worksharing directives.
2755 ExprResult LB, UB, IL, ST, EUB;
2756 if (isOpenMPWorksharingDirective(DKind)) {
2757 // Lower bound variable, initialized with zero.
2758 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2759 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2760 SemaRef.AddInitializerToDecl(
2761 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2762 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2763
2764 // Upper bound variable, initialized with last iteration number.
2765 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2766 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2767 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2768 /*DirectInit*/ false,
2769 /*TypeMayContainAuto*/ false);
2770
2771 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2772 // This will be used to implement clause 'lastprivate'.
2773 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2774 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2775 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2776 SemaRef.AddInitializerToDecl(
2777 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2778 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2779
2780 // Stride variable returned by runtime (we initialize it to 1 by default).
2781 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2782 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2783 SemaRef.AddInitializerToDecl(
2784 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2785 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2786
2787 // Build expression: UB = min(UB, LastIteration)
2788 // It is nesessary for CodeGen of directives with static scheduling.
2789 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2790 UB.get(), LastIteration.get());
2791 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2792 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2793 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2794 CondOp.get());
2795 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2796 }
2797
2798 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002799 ExprResult IV;
2800 ExprResult Init;
2801 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002802 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2803 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2804 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2805 ? LB.get()
2806 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2807 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2808 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002809 }
2810
Alexander Musmanc6388682014-12-15 07:07:06 +00002811 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002812 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002813 ExprResult Cond =
2814 isOpenMPWorksharingDirective(DKind)
2815 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2816 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2817 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002818 // Loop condition with 1 iteration separated (IV < LastIteration)
2819 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2820 IV.get(), LastIteration.get());
2821
2822 // Loop increment (IV = IV + 1)
2823 SourceLocation IncLoc;
2824 ExprResult Inc =
2825 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2826 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2827 if (!Inc.isUsable())
2828 return 0;
2829 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002830 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2831 if (!Inc.isUsable())
2832 return 0;
2833
2834 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2835 // Used for directives with static scheduling.
2836 ExprResult NextLB, NextUB;
2837 if (isOpenMPWorksharingDirective(DKind)) {
2838 // LB + ST
2839 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2840 if (!NextLB.isUsable())
2841 return 0;
2842 // LB = LB + ST
2843 NextLB =
2844 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2845 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2846 if (!NextLB.isUsable())
2847 return 0;
2848 // UB + ST
2849 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2850 if (!NextUB.isUsable())
2851 return 0;
2852 // UB = UB + ST
2853 NextUB =
2854 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2855 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2856 if (!NextUB.isUsable())
2857 return 0;
2858 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002859
2860 // Build updates and final values of the loop counters.
2861 bool HasErrors = false;
2862 Built.Counters.resize(NestedLoopCount);
2863 Built.Updates.resize(NestedLoopCount);
2864 Built.Finals.resize(NestedLoopCount);
2865 {
2866 ExprResult Div;
2867 // Go from inner nested loop to outer.
2868 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2869 LoopIterationSpace &IS = IterSpaces[Cnt];
2870 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2871 // Build: Iter = (IV / Div) % IS.NumIters
2872 // where Div is product of previous iterations' IS.NumIters.
2873 ExprResult Iter;
2874 if (Div.isUsable()) {
2875 Iter =
2876 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2877 } else {
2878 Iter = IV;
2879 assert((Cnt == (int)NestedLoopCount - 1) &&
2880 "unusable div expected on first iteration only");
2881 }
2882
2883 if (Cnt != 0 && Iter.isUsable())
2884 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2885 IS.NumIterations);
2886 if (!Iter.isUsable()) {
2887 HasErrors = true;
2888 break;
2889 }
2890
2891 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2892 ExprResult Update =
2893 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2894 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2895 if (!Update.isUsable()) {
2896 HasErrors = true;
2897 break;
2898 }
2899
2900 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2901 ExprResult Final = BuildCounterUpdate(
2902 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2903 IS.NumIterations, IS.CounterStep, IS.Subtract);
2904 if (!Final.isUsable()) {
2905 HasErrors = true;
2906 break;
2907 }
2908
2909 // Build Div for the next iteration: Div <- Div * IS.NumIters
2910 if (Cnt != 0) {
2911 if (Div.isUnset())
2912 Div = IS.NumIterations;
2913 else
2914 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2915 IS.NumIterations);
2916
2917 // Add parentheses (for debugging purposes only).
2918 if (Div.isUsable())
2919 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2920 if (!Div.isUsable()) {
2921 HasErrors = true;
2922 break;
2923 }
2924 }
2925 if (!Update.isUsable() || !Final.isUsable()) {
2926 HasErrors = true;
2927 break;
2928 }
2929 // Save results
2930 Built.Counters[Cnt] = IS.CounterVar;
2931 Built.Updates[Cnt] = Update.get();
2932 Built.Finals[Cnt] = Final.get();
2933 }
2934 }
2935
2936 if (HasErrors)
2937 return 0;
2938
2939 // Save results
2940 Built.IterationVarRef = IV.get();
2941 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00002942 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002943 Built.CalcLastIteration = CalcLastIteration.get();
2944 Built.PreCond = PreCond.get();
2945 Built.Cond = Cond.get();
2946 Built.SeparatedCond = SeparatedCond.get();
2947 Built.Init = Init.get();
2948 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00002949 Built.LB = LB.get();
2950 Built.UB = UB.get();
2951 Built.IL = IL.get();
2952 Built.ST = ST.get();
2953 Built.EUB = EUB.get();
2954 Built.NLB = NextLB.get();
2955 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002956
Alexey Bataevabfc0692014-06-25 06:52:00 +00002957 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002958}
2959
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002960static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002961 auto CollapseFilter = [](const OMPClause *C) -> bool {
2962 return C->getClauseKind() == OMPC_collapse;
2963 };
2964 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2965 Clauses, CollapseFilter);
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002966 if (I)
2967 return cast<OMPCollapseClause>(*I)->getNumForLoops();
2968 return nullptr;
2969}
2970
Alexey Bataev4acb8592014-07-07 13:01:15 +00002971StmtResult Sema::ActOnOpenMPSimdDirective(
2972 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2973 SourceLocation EndLoc,
2974 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002975 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002976 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002977 unsigned NestedLoopCount =
2978 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002979 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00002980 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002981 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002982
Alexander Musmana5f070a2014-10-01 06:03:56 +00002983 assert((CurContext->isDependentContext() || B.builtAll()) &&
2984 "omp simd loop exprs were not built");
2985
Alexander Musman3276a272015-03-21 10:12:56 +00002986 if (!CurContext->isDependentContext()) {
2987 // Finalize the clauses that need pre-built expressions for CodeGen.
2988 for (auto C : Clauses) {
2989 if (auto LC = dyn_cast<OMPLinearClause>(C))
2990 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
2991 B.NumIterations, *this, CurScope))
2992 return StmtError();
2993 }
2994 }
2995
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002996 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00002997 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2998 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002999}
3000
Alexey Bataev4acb8592014-07-07 13:01:15 +00003001StmtResult Sema::ActOnOpenMPForDirective(
3002 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3003 SourceLocation EndLoc,
3004 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003005 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003006 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003007 unsigned NestedLoopCount =
3008 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003009 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003010 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003011 return StmtError();
3012
Alexander Musmana5f070a2014-10-01 06:03:56 +00003013 assert((CurContext->isDependentContext() || B.builtAll()) &&
3014 "omp for loop exprs were not built");
3015
Alexey Bataevf29276e2014-06-18 04:14:57 +00003016 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003017 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3018 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003019}
3020
Alexander Musmanf82886e2014-09-18 05:12:34 +00003021StmtResult Sema::ActOnOpenMPForSimdDirective(
3022 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3023 SourceLocation EndLoc,
3024 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003025 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003026 // In presence of clause 'collapse', it will define the nested loops number.
3027 unsigned NestedLoopCount =
3028 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003029 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003030 if (NestedLoopCount == 0)
3031 return StmtError();
3032
Alexander Musmanc6388682014-12-15 07:07:06 +00003033 assert((CurContext->isDependentContext() || B.builtAll()) &&
3034 "omp for simd loop exprs were not built");
3035
Alexander Musmanf82886e2014-09-18 05:12:34 +00003036 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003037 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3038 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003039}
3040
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003041StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3042 Stmt *AStmt,
3043 SourceLocation StartLoc,
3044 SourceLocation EndLoc) {
3045 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3046 auto BaseStmt = AStmt;
3047 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3048 BaseStmt = CS->getCapturedStmt();
3049 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3050 auto S = C->children();
3051 if (!S)
3052 return StmtError();
3053 // All associated statements must be '#pragma omp section' except for
3054 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003055 for (++S; S; ++S) {
3056 auto SectionStmt = *S;
3057 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3058 if (SectionStmt)
3059 Diag(SectionStmt->getLocStart(),
3060 diag::err_omp_sections_substmt_not_section);
3061 return StmtError();
3062 }
3063 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003064 } else {
3065 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3066 return StmtError();
3067 }
3068
3069 getCurFunction()->setHasBranchProtectedScope();
3070
3071 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3072 AStmt);
3073}
3074
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003075StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3076 SourceLocation StartLoc,
3077 SourceLocation EndLoc) {
3078 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3079
3080 getCurFunction()->setHasBranchProtectedScope();
3081
3082 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3083}
3084
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003085StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3086 Stmt *AStmt,
3087 SourceLocation StartLoc,
3088 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003089 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3090
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003091 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003092
Alexey Bataev3255bf32015-01-19 05:20:46 +00003093 // OpenMP [2.7.3, single Construct, Restrictions]
3094 // The copyprivate clause must not be used with the nowait clause.
3095 OMPClause *Nowait = nullptr;
3096 OMPClause *Copyprivate = nullptr;
3097 for (auto *Clause : Clauses) {
3098 if (Clause->getClauseKind() == OMPC_nowait)
3099 Nowait = Clause;
3100 else if (Clause->getClauseKind() == OMPC_copyprivate)
3101 Copyprivate = Clause;
3102 if (Copyprivate && Nowait) {
3103 Diag(Copyprivate->getLocStart(),
3104 diag::err_omp_single_copyprivate_with_nowait);
3105 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3106 return StmtError();
3107 }
3108 }
3109
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003110 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3111}
3112
Alexander Musman80c22892014-07-17 08:54:58 +00003113StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3114 SourceLocation StartLoc,
3115 SourceLocation EndLoc) {
3116 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3117
3118 getCurFunction()->setHasBranchProtectedScope();
3119
3120 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3121}
3122
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003123StmtResult
3124Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3125 Stmt *AStmt, SourceLocation StartLoc,
3126 SourceLocation EndLoc) {
3127 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3128
3129 getCurFunction()->setHasBranchProtectedScope();
3130
3131 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3132 AStmt);
3133}
3134
Alexey Bataev4acb8592014-07-07 13:01:15 +00003135StmtResult Sema::ActOnOpenMPParallelForDirective(
3136 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3137 SourceLocation EndLoc,
3138 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3139 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3140 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3141 // 1.2.2 OpenMP Language Terminology
3142 // Structured block - An executable statement with a single entry at the
3143 // top and a single exit at the bottom.
3144 // The point of exit cannot be a branch out of the structured block.
3145 // longjmp() and throw() must not violate the entry/exit criteria.
3146 CS->getCapturedDecl()->setNothrow();
3147
Alexander Musmanc6388682014-12-15 07:07:06 +00003148 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003149 // In presence of clause 'collapse', it will define the nested loops number.
3150 unsigned NestedLoopCount =
3151 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003152 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003153 if (NestedLoopCount == 0)
3154 return StmtError();
3155
Alexander Musmana5f070a2014-10-01 06:03:56 +00003156 assert((CurContext->isDependentContext() || B.builtAll()) &&
3157 "omp parallel for loop exprs were not built");
3158
Alexey Bataev4acb8592014-07-07 13:01:15 +00003159 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003160 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3161 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003162}
3163
Alexander Musmane4e893b2014-09-23 09:33:00 +00003164StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3165 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3166 SourceLocation EndLoc,
3167 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3168 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3169 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3170 // 1.2.2 OpenMP Language Terminology
3171 // Structured block - An executable statement with a single entry at the
3172 // top and a single exit at the bottom.
3173 // The point of exit cannot be a branch out of the structured block.
3174 // longjmp() and throw() must not violate the entry/exit criteria.
3175 CS->getCapturedDecl()->setNothrow();
3176
Alexander Musmanc6388682014-12-15 07:07:06 +00003177 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003178 // In presence of clause 'collapse', it will define the nested loops number.
3179 unsigned NestedLoopCount =
3180 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003181 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003182 if (NestedLoopCount == 0)
3183 return StmtError();
3184
3185 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003186 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003187 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003188}
3189
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003190StmtResult
3191Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3192 Stmt *AStmt, SourceLocation StartLoc,
3193 SourceLocation EndLoc) {
3194 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3195 auto BaseStmt = AStmt;
3196 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3197 BaseStmt = CS->getCapturedStmt();
3198 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3199 auto S = C->children();
3200 if (!S)
3201 return StmtError();
3202 // All associated statements must be '#pragma omp section' except for
3203 // the first one.
3204 for (++S; S; ++S) {
3205 auto SectionStmt = *S;
3206 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3207 if (SectionStmt)
3208 Diag(SectionStmt->getLocStart(),
3209 diag::err_omp_parallel_sections_substmt_not_section);
3210 return StmtError();
3211 }
3212 }
3213 } else {
3214 Diag(AStmt->getLocStart(),
3215 diag::err_omp_parallel_sections_not_compound_stmt);
3216 return StmtError();
3217 }
3218
3219 getCurFunction()->setHasBranchProtectedScope();
3220
3221 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3222 Clauses, AStmt);
3223}
3224
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003225StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3226 Stmt *AStmt, SourceLocation StartLoc,
3227 SourceLocation EndLoc) {
3228 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3229 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3230 // 1.2.2 OpenMP Language Terminology
3231 // Structured block - An executable statement with a single entry at the
3232 // top and a single exit at the bottom.
3233 // The point of exit cannot be a branch out of the structured block.
3234 // longjmp() and throw() must not violate the entry/exit criteria.
3235 CS->getCapturedDecl()->setNothrow();
3236
3237 getCurFunction()->setHasBranchProtectedScope();
3238
3239 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3240}
3241
Alexey Bataev68446b72014-07-18 07:47:19 +00003242StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3243 SourceLocation EndLoc) {
3244 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3245}
3246
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003247StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3248 SourceLocation EndLoc) {
3249 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3250}
3251
Alexey Bataev2df347a2014-07-18 10:17:07 +00003252StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3253 SourceLocation EndLoc) {
3254 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3255}
3256
Alexey Bataev6125da92014-07-21 11:26:11 +00003257StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3258 SourceLocation StartLoc,
3259 SourceLocation EndLoc) {
3260 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3261 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3262}
3263
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003264StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3265 SourceLocation StartLoc,
3266 SourceLocation EndLoc) {
3267 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3268
3269 getCurFunction()->setHasBranchProtectedScope();
3270
3271 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3272}
3273
Alexey Bataev1d160b12015-03-13 12:27:31 +00003274namespace {
3275/// \brief Helper class for checking expression in 'omp atomic [update]'
3276/// construct.
3277class OpenMPAtomicUpdateChecker {
3278 /// \brief Error results for atomic update expressions.
3279 enum ExprAnalysisErrorCode {
3280 /// \brief A statement is not an expression statement.
3281 NotAnExpression,
3282 /// \brief Expression is not builtin binary or unary operation.
3283 NotABinaryOrUnaryExpression,
3284 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3285 NotAnUnaryIncDecExpression,
3286 /// \brief An expression is not of scalar type.
3287 NotAScalarType,
3288 /// \brief A binary operation is not an assignment operation.
3289 NotAnAssignmentOp,
3290 /// \brief RHS part of the binary operation is not a binary expression.
3291 NotABinaryExpression,
3292 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3293 /// expression.
3294 NotABinaryOperator,
3295 /// \brief RHS binary operation does not have reference to the updated LHS
3296 /// part.
3297 NotAnUpdateExpression,
3298 /// \brief No errors is found.
3299 NoError
3300 };
3301 /// \brief Reference to Sema.
3302 Sema &SemaRef;
3303 /// \brief A location for note diagnostics (when error is found).
3304 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003305 /// \brief 'x' lvalue part of the source atomic expression.
3306 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003307 /// \brief 'expr' rvalue part of the source atomic expression.
3308 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003309 /// \brief Helper expression of the form
3310 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3311 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3312 Expr *UpdateExpr;
3313 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3314 /// important for non-associative operations.
3315 bool IsXLHSInRHSPart;
3316 BinaryOperatorKind Op;
3317 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003318 /// \brief true if the source expression is a postfix unary operation, false
3319 /// if it is a prefix unary operation.
3320 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003321
3322public:
3323 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003324 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003325 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003326 /// \brief Check specified statement that it is suitable for 'atomic update'
3327 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003328 /// expression. If DiagId and NoteId == 0, then only check is performed
3329 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003330 /// \param DiagId Diagnostic which should be emitted if error is found.
3331 /// \param NoteId Diagnostic note for the main error message.
3332 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003333 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003334 /// \brief Return the 'x' lvalue part of the source atomic expression.
3335 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003336 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3337 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003338 /// \brief Return the update expression used in calculation of the updated
3339 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3340 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3341 Expr *getUpdateExpr() const { return UpdateExpr; }
3342 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3343 /// false otherwise.
3344 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3345
Alexey Bataevb78ca832015-04-01 03:33:17 +00003346 /// \brief true if the source expression is a postfix unary operation, false
3347 /// if it is a prefix unary operation.
3348 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3349
Alexey Bataev1d160b12015-03-13 12:27:31 +00003350private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003351 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3352 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003353};
3354} // namespace
3355
3356bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3357 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3358 ExprAnalysisErrorCode ErrorFound = NoError;
3359 SourceLocation ErrorLoc, NoteLoc;
3360 SourceRange ErrorRange, NoteRange;
3361 // Allowed constructs are:
3362 // x = x binop expr;
3363 // x = expr binop x;
3364 if (AtomicBinOp->getOpcode() == BO_Assign) {
3365 X = AtomicBinOp->getLHS();
3366 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3367 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3368 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3369 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3370 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003371 Op = AtomicInnerBinOp->getOpcode();
3372 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003373 auto *LHS = AtomicInnerBinOp->getLHS();
3374 auto *RHS = AtomicInnerBinOp->getRHS();
3375 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3376 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3377 /*Canonical=*/true);
3378 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3379 /*Canonical=*/true);
3380 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3381 /*Canonical=*/true);
3382 if (XId == LHSId) {
3383 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003384 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003385 } else if (XId == RHSId) {
3386 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003387 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003388 } else {
3389 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3390 ErrorRange = AtomicInnerBinOp->getSourceRange();
3391 NoteLoc = X->getExprLoc();
3392 NoteRange = X->getSourceRange();
3393 ErrorFound = NotAnUpdateExpression;
3394 }
3395 } else {
3396 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3397 ErrorRange = AtomicInnerBinOp->getSourceRange();
3398 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3399 NoteRange = SourceRange(NoteLoc, NoteLoc);
3400 ErrorFound = NotABinaryOperator;
3401 }
3402 } else {
3403 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3404 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3405 ErrorFound = NotABinaryExpression;
3406 }
3407 } else {
3408 ErrorLoc = AtomicBinOp->getExprLoc();
3409 ErrorRange = AtomicBinOp->getSourceRange();
3410 NoteLoc = AtomicBinOp->getOperatorLoc();
3411 NoteRange = SourceRange(NoteLoc, NoteLoc);
3412 ErrorFound = NotAnAssignmentOp;
3413 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003414 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003415 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3416 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3417 return true;
3418 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003419 E = X = UpdateExpr = nullptr;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003420 return false;
3421}
3422
3423bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3424 unsigned NoteId) {
3425 ExprAnalysisErrorCode ErrorFound = NoError;
3426 SourceLocation ErrorLoc, NoteLoc;
3427 SourceRange ErrorRange, NoteRange;
3428 // Allowed constructs are:
3429 // x++;
3430 // x--;
3431 // ++x;
3432 // --x;
3433 // x binop= expr;
3434 // x = x binop expr;
3435 // x = expr binop x;
3436 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3437 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3438 if (AtomicBody->getType()->isScalarType() ||
3439 AtomicBody->isInstantiationDependent()) {
3440 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3441 AtomicBody->IgnoreParenImpCasts())) {
3442 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003443 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003444 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003445 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003446 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003447 X = AtomicCompAssignOp->getLHS();
3448 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003449 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3450 AtomicBody->IgnoreParenImpCasts())) {
3451 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003452 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3453 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003454 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003455 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3456 // Check for Unary Operation
3457 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003458 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003459 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3460 OpLoc = AtomicUnaryOp->getOperatorLoc();
3461 X = AtomicUnaryOp->getSubExpr();
3462 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3463 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003464 } else {
3465 ErrorFound = NotAnUnaryIncDecExpression;
3466 ErrorLoc = AtomicUnaryOp->getExprLoc();
3467 ErrorRange = AtomicUnaryOp->getSourceRange();
3468 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3469 NoteRange = SourceRange(NoteLoc, NoteLoc);
3470 }
3471 } else {
3472 ErrorFound = NotABinaryOrUnaryExpression;
3473 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3474 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3475 }
3476 } else {
3477 ErrorFound = NotAScalarType;
3478 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3479 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3480 }
3481 } else {
3482 ErrorFound = NotAnExpression;
3483 NoteLoc = ErrorLoc = S->getLocStart();
3484 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3485 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003486 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003487 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3488 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3489 return true;
3490 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003491 E = X = UpdateExpr = nullptr;
3492 if (E && X) {
3493 // Build an update expression of form 'OpaqueValueExpr(x) binop
3494 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3495 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3496 auto *OVEX = new (SemaRef.getASTContext())
3497 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3498 auto *OVEExpr = new (SemaRef.getASTContext())
3499 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3500 auto Update =
3501 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3502 IsXLHSInRHSPart ? OVEExpr : OVEX);
3503 if (Update.isInvalid())
3504 return true;
3505 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3506 Sema::AA_Casting);
3507 if (Update.isInvalid())
3508 return true;
3509 UpdateExpr = Update.get();
3510 }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003511 return false;
3512}
3513
Alexey Bataev0162e452014-07-22 10:10:35 +00003514StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3515 Stmt *AStmt,
3516 SourceLocation StartLoc,
3517 SourceLocation EndLoc) {
3518 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003519 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003520 // 1.2.2 OpenMP Language Terminology
3521 // Structured block - An executable statement with a single entry at the
3522 // top and a single exit at the bottom.
3523 // The point of exit cannot be a branch out of the structured block.
3524 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003525 OpenMPClauseKind AtomicKind = OMPC_unknown;
3526 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003527 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003528 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003529 C->getClauseKind() == OMPC_update ||
3530 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003531 if (AtomicKind != OMPC_unknown) {
3532 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3533 << SourceRange(C->getLocStart(), C->getLocEnd());
3534 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3535 << getOpenMPClauseName(AtomicKind);
3536 } else {
3537 AtomicKind = C->getClauseKind();
3538 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003539 }
3540 }
3541 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003542
Alexey Bataev459dec02014-07-24 06:46:57 +00003543 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003544 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3545 Body = EWC->getSubExpr();
3546
Alexey Bataev62cec442014-11-18 10:14:22 +00003547 Expr *X = nullptr;
3548 Expr *V = nullptr;
3549 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003550 Expr *UE = nullptr;
3551 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003552 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003553 // OpenMP [2.12.6, atomic Construct]
3554 // In the next expressions:
3555 // * x and v (as applicable) are both l-value expressions with scalar type.
3556 // * During the execution of an atomic region, multiple syntactic
3557 // occurrences of x must designate the same storage location.
3558 // * Neither of v and expr (as applicable) may access the storage location
3559 // designated by x.
3560 // * Neither of x and expr (as applicable) may access the storage location
3561 // designated by v.
3562 // * expr is an expression with scalar type.
3563 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3564 // * binop, binop=, ++, and -- are not overloaded operators.
3565 // * The expression x binop expr must be numerically equivalent to x binop
3566 // (expr). This requirement is satisfied if the operators in expr have
3567 // precedence greater than binop, or by using parentheses around expr or
3568 // subexpressions of expr.
3569 // * The expression expr binop x must be numerically equivalent to (expr)
3570 // binop x. This requirement is satisfied if the operators in expr have
3571 // precedence equal to or greater than binop, or by using parentheses around
3572 // expr or subexpressions of expr.
3573 // * For forms that allow multiple occurrences of x, the number of times
3574 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003575 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003576 enum {
3577 NotAnExpression,
3578 NotAnAssignmentOp,
3579 NotAScalarType,
3580 NotAnLValue,
3581 NoError
3582 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003583 SourceLocation ErrorLoc, NoteLoc;
3584 SourceRange ErrorRange, NoteRange;
3585 // If clause is read:
3586 // v = x;
3587 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3588 auto AtomicBinOp =
3589 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3590 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3591 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3592 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3593 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3594 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3595 if (!X->isLValue() || !V->isLValue()) {
3596 auto NotLValueExpr = X->isLValue() ? V : X;
3597 ErrorFound = NotAnLValue;
3598 ErrorLoc = AtomicBinOp->getExprLoc();
3599 ErrorRange = AtomicBinOp->getSourceRange();
3600 NoteLoc = NotLValueExpr->getExprLoc();
3601 NoteRange = NotLValueExpr->getSourceRange();
3602 }
3603 } else if (!X->isInstantiationDependent() ||
3604 !V->isInstantiationDependent()) {
3605 auto NotScalarExpr =
3606 (X->isInstantiationDependent() || X->getType()->isScalarType())
3607 ? V
3608 : X;
3609 ErrorFound = NotAScalarType;
3610 ErrorLoc = AtomicBinOp->getExprLoc();
3611 ErrorRange = AtomicBinOp->getSourceRange();
3612 NoteLoc = NotScalarExpr->getExprLoc();
3613 NoteRange = NotScalarExpr->getSourceRange();
3614 }
3615 } else {
3616 ErrorFound = NotAnAssignmentOp;
3617 ErrorLoc = AtomicBody->getExprLoc();
3618 ErrorRange = AtomicBody->getSourceRange();
3619 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3620 : AtomicBody->getExprLoc();
3621 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3622 : AtomicBody->getSourceRange();
3623 }
3624 } else {
3625 ErrorFound = NotAnExpression;
3626 NoteLoc = ErrorLoc = Body->getLocStart();
3627 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003628 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003629 if (ErrorFound != NoError) {
3630 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3631 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003632 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3633 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003634 return StmtError();
3635 } else if (CurContext->isDependentContext())
3636 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003637 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003638 enum {
3639 NotAnExpression,
3640 NotAnAssignmentOp,
3641 NotAScalarType,
3642 NotAnLValue,
3643 NoError
3644 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003645 SourceLocation ErrorLoc, NoteLoc;
3646 SourceRange ErrorRange, NoteRange;
3647 // If clause is write:
3648 // x = expr;
3649 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3650 auto AtomicBinOp =
3651 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3652 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003653 X = AtomicBinOp->getLHS();
3654 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003655 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3656 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3657 if (!X->isLValue()) {
3658 ErrorFound = NotAnLValue;
3659 ErrorLoc = AtomicBinOp->getExprLoc();
3660 ErrorRange = AtomicBinOp->getSourceRange();
3661 NoteLoc = X->getExprLoc();
3662 NoteRange = X->getSourceRange();
3663 }
3664 } else if (!X->isInstantiationDependent() ||
3665 !E->isInstantiationDependent()) {
3666 auto NotScalarExpr =
3667 (X->isInstantiationDependent() || X->getType()->isScalarType())
3668 ? E
3669 : X;
3670 ErrorFound = NotAScalarType;
3671 ErrorLoc = AtomicBinOp->getExprLoc();
3672 ErrorRange = AtomicBinOp->getSourceRange();
3673 NoteLoc = NotScalarExpr->getExprLoc();
3674 NoteRange = NotScalarExpr->getSourceRange();
3675 }
3676 } else {
3677 ErrorFound = NotAnAssignmentOp;
3678 ErrorLoc = AtomicBody->getExprLoc();
3679 ErrorRange = AtomicBody->getSourceRange();
3680 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3681 : AtomicBody->getExprLoc();
3682 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3683 : AtomicBody->getSourceRange();
3684 }
3685 } else {
3686 ErrorFound = NotAnExpression;
3687 NoteLoc = ErrorLoc = Body->getLocStart();
3688 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003689 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003690 if (ErrorFound != NoError) {
3691 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3692 << ErrorRange;
3693 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3694 << NoteRange;
3695 return StmtError();
3696 } else if (CurContext->isDependentContext())
3697 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003698 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003699 // If clause is update:
3700 // x++;
3701 // x--;
3702 // ++x;
3703 // --x;
3704 // x binop= expr;
3705 // x = x binop expr;
3706 // x = expr binop x;
3707 OpenMPAtomicUpdateChecker Checker(*this);
3708 if (Checker.checkStatement(
3709 Body, (AtomicKind == OMPC_update)
3710 ? diag::err_omp_atomic_update_not_expression_statement
3711 : diag::err_omp_atomic_not_expression_statement,
3712 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003713 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003714 if (!CurContext->isDependentContext()) {
3715 E = Checker.getExpr();
3716 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003717 UE = Checker.getUpdateExpr();
3718 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003719 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003720 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003721 enum {
3722 NotAnAssignmentOp,
3723 NotACompoundStatement,
3724 NotTwoSubstatements,
3725 NotASpecificExpression,
3726 NoError
3727 } ErrorFound = NoError;
3728 SourceLocation ErrorLoc, NoteLoc;
3729 SourceRange ErrorRange, NoteRange;
3730 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3731 // If clause is a capture:
3732 // v = x++;
3733 // v = x--;
3734 // v = ++x;
3735 // v = --x;
3736 // v = x binop= expr;
3737 // v = x = x binop expr;
3738 // v = x = expr binop x;
3739 auto *AtomicBinOp =
3740 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3741 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3742 V = AtomicBinOp->getLHS();
3743 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3744 OpenMPAtomicUpdateChecker Checker(*this);
3745 if (Checker.checkStatement(
3746 Body, diag::err_omp_atomic_capture_not_expression_statement,
3747 diag::note_omp_atomic_update))
3748 return StmtError();
3749 E = Checker.getExpr();
3750 X = Checker.getX();
3751 UE = Checker.getUpdateExpr();
3752 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3753 IsPostfixUpdate = Checker.isPostfixUpdate();
3754 } else {
3755 ErrorLoc = AtomicBody->getExprLoc();
3756 ErrorRange = AtomicBody->getSourceRange();
3757 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3758 : AtomicBody->getExprLoc();
3759 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3760 : AtomicBody->getSourceRange();
3761 ErrorFound = NotAnAssignmentOp;
3762 }
3763 if (ErrorFound != NoError) {
3764 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3765 << ErrorRange;
3766 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3767 return StmtError();
3768 } else if (CurContext->isDependentContext()) {
3769 UE = V = E = X = nullptr;
3770 }
3771 } else {
3772 // If clause is a capture:
3773 // { v = x; x = expr; }
3774 // { v = x; x++; }
3775 // { v = x; x--; }
3776 // { v = x; ++x; }
3777 // { v = x; --x; }
3778 // { v = x; x binop= expr; }
3779 // { v = x; x = x binop expr; }
3780 // { v = x; x = expr binop x; }
3781 // { x++; v = x; }
3782 // { x--; v = x; }
3783 // { ++x; v = x; }
3784 // { --x; v = x; }
3785 // { x binop= expr; v = x; }
3786 // { x = x binop expr; v = x; }
3787 // { x = expr binop x; v = x; }
3788 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3789 // Check that this is { expr1; expr2; }
3790 if (CS->size() == 2) {
3791 auto *First = CS->body_front();
3792 auto *Second = CS->body_back();
3793 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3794 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3795 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3796 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3797 // Need to find what subexpression is 'v' and what is 'x'.
3798 OpenMPAtomicUpdateChecker Checker(*this);
3799 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3800 BinaryOperator *BinOp = nullptr;
3801 if (IsUpdateExprFound) {
3802 BinOp = dyn_cast<BinaryOperator>(First);
3803 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3804 }
3805 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3806 // { v = x; x++; }
3807 // { v = x; x--; }
3808 // { v = x; ++x; }
3809 // { v = x; --x; }
3810 // { v = x; x binop= expr; }
3811 // { v = x; x = x binop expr; }
3812 // { v = x; x = expr binop x; }
3813 // Check that the first expression has form v = x.
3814 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3815 llvm::FoldingSetNodeID XId, PossibleXId;
3816 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3817 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3818 IsUpdateExprFound = XId == PossibleXId;
3819 if (IsUpdateExprFound) {
3820 V = BinOp->getLHS();
3821 X = Checker.getX();
3822 E = Checker.getExpr();
3823 UE = Checker.getUpdateExpr();
3824 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3825 IsPostfixUpdate = Checker.isPostfixUpdate();
3826 }
3827 }
3828 if (!IsUpdateExprFound) {
3829 IsUpdateExprFound = !Checker.checkStatement(First);
3830 BinOp = nullptr;
3831 if (IsUpdateExprFound) {
3832 BinOp = dyn_cast<BinaryOperator>(Second);
3833 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3834 }
3835 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3836 // { x++; v = x; }
3837 // { x--; v = x; }
3838 // { ++x; v = x; }
3839 // { --x; v = x; }
3840 // { x binop= expr; v = x; }
3841 // { x = x binop expr; v = x; }
3842 // { x = expr binop x; v = x; }
3843 // Check that the second expression has form v = x.
3844 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3845 llvm::FoldingSetNodeID XId, PossibleXId;
3846 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3847 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3848 IsUpdateExprFound = XId == PossibleXId;
3849 if (IsUpdateExprFound) {
3850 V = BinOp->getLHS();
3851 X = Checker.getX();
3852 E = Checker.getExpr();
3853 UE = Checker.getUpdateExpr();
3854 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3855 IsPostfixUpdate = Checker.isPostfixUpdate();
3856 }
3857 }
3858 }
3859 if (!IsUpdateExprFound) {
3860 // { v = x; x = expr; }
3861 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3862 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3863 ErrorFound = NotAnAssignmentOp;
3864 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3865 : First->getLocStart();
3866 NoteRange = ErrorRange = FirstBinOp
3867 ? FirstBinOp->getSourceRange()
3868 : SourceRange(ErrorLoc, ErrorLoc);
3869 } else {
3870 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3871 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3872 ErrorFound = NotAnAssignmentOp;
3873 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3874 : Second->getLocStart();
3875 NoteRange = ErrorRange = SecondBinOp
3876 ? SecondBinOp->getSourceRange()
3877 : SourceRange(ErrorLoc, ErrorLoc);
3878 } else {
3879 auto *PossibleXRHSInFirst =
3880 FirstBinOp->getRHS()->IgnoreParenImpCasts();
3881 auto *PossibleXLHSInSecond =
3882 SecondBinOp->getLHS()->IgnoreParenImpCasts();
3883 llvm::FoldingSetNodeID X1Id, X2Id;
3884 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
3885 PossibleXLHSInSecond->Profile(X2Id, Context,
3886 /*Canonical=*/true);
3887 IsUpdateExprFound = X1Id == X2Id;
3888 if (IsUpdateExprFound) {
3889 V = FirstBinOp->getLHS();
3890 X = SecondBinOp->getLHS();
3891 E = SecondBinOp->getRHS();
3892 UE = nullptr;
3893 IsXLHSInRHSPart = false;
3894 IsPostfixUpdate = true;
3895 } else {
3896 ErrorFound = NotASpecificExpression;
3897 ErrorLoc = FirstBinOp->getExprLoc();
3898 ErrorRange = FirstBinOp->getSourceRange();
3899 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
3900 NoteRange = SecondBinOp->getRHS()->getSourceRange();
3901 }
3902 }
3903 }
3904 }
3905 } else {
3906 NoteLoc = ErrorLoc = Body->getLocStart();
3907 NoteRange = ErrorRange =
3908 SourceRange(Body->getLocStart(), Body->getLocStart());
3909 ErrorFound = NotTwoSubstatements;
3910 }
3911 } else {
3912 NoteLoc = ErrorLoc = Body->getLocStart();
3913 NoteRange = ErrorRange =
3914 SourceRange(Body->getLocStart(), Body->getLocStart());
3915 ErrorFound = NotACompoundStatement;
3916 }
3917 if (ErrorFound != NoError) {
3918 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
3919 << ErrorRange;
3920 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3921 return StmtError();
3922 } else if (CurContext->isDependentContext()) {
3923 UE = V = E = X = nullptr;
3924 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003925 }
Alexey Bataevdea47612014-07-23 07:46:59 +00003926 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003927
3928 getCurFunction()->setHasBranchProtectedScope();
3929
Alexey Bataev62cec442014-11-18 10:14:22 +00003930 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00003931 X, V, E, UE, IsXLHSInRHSPart,
3932 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00003933}
3934
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003935StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3936 Stmt *AStmt,
3937 SourceLocation StartLoc,
3938 SourceLocation EndLoc) {
3939 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3940
Alexey Bataev13314bf2014-10-09 04:18:56 +00003941 // OpenMP [2.16, Nesting of Regions]
3942 // If specified, a teams construct must be contained within a target
3943 // construct. That target construct must contain no statements or directives
3944 // outside of the teams construct.
3945 if (DSAStack->hasInnerTeamsRegion()) {
3946 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3947 bool OMPTeamsFound = true;
3948 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3949 auto I = CS->body_begin();
3950 while (I != CS->body_end()) {
3951 auto OED = dyn_cast<OMPExecutableDirective>(*I);
3952 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3953 OMPTeamsFound = false;
3954 break;
3955 }
3956 ++I;
3957 }
3958 assert(I != CS->body_end() && "Not found statement");
3959 S = *I;
3960 }
3961 if (!OMPTeamsFound) {
3962 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
3963 Diag(DSAStack->getInnerTeamsRegionLoc(),
3964 diag::note_omp_nested_teams_construct_here);
3965 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
3966 << isa<OMPExecutableDirective>(S);
3967 return StmtError();
3968 }
3969 }
3970
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003971 getCurFunction()->setHasBranchProtectedScope();
3972
3973 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3974}
3975
Alexey Bataev13314bf2014-10-09 04:18:56 +00003976StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
3977 Stmt *AStmt, SourceLocation StartLoc,
3978 SourceLocation EndLoc) {
3979 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3980 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3981 // 1.2.2 OpenMP Language Terminology
3982 // Structured block - An executable statement with a single entry at the
3983 // top and a single exit at the bottom.
3984 // The point of exit cannot be a branch out of the structured block.
3985 // longjmp() and throw() must not violate the entry/exit criteria.
3986 CS->getCapturedDecl()->setNothrow();
3987
3988 getCurFunction()->setHasBranchProtectedScope();
3989
3990 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3991}
3992
Alexey Bataeved09d242014-05-28 05:53:51 +00003993OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003994 SourceLocation StartLoc,
3995 SourceLocation LParenLoc,
3996 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003997 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003998 switch (Kind) {
3999 case OMPC_if:
4000 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4001 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004002 case OMPC_final:
4003 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4004 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004005 case OMPC_num_threads:
4006 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4007 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004008 case OMPC_safelen:
4009 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4010 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004011 case OMPC_collapse:
4012 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4013 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004014 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004015 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004016 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004017 case OMPC_private:
4018 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004019 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004020 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004021 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004022 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004023 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004024 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004025 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004026 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004027 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004028 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004029 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004030 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004031 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004032 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004033 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004034 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004035 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004036 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004037 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004038 llvm_unreachable("Clause is not allowed.");
4039 }
4040 return Res;
4041}
4042
Alexey Bataeved09d242014-05-28 05:53:51 +00004043OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004044 SourceLocation LParenLoc,
4045 SourceLocation EndLoc) {
4046 Expr *ValExpr = Condition;
4047 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4048 !Condition->isInstantiationDependent() &&
4049 !Condition->containsUnexpandedParameterPack()) {
4050 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004051 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004052 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004053 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004054
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004055 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004056 }
4057
4058 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4059}
4060
Alexey Bataev3778b602014-07-17 07:32:53 +00004061OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4062 SourceLocation StartLoc,
4063 SourceLocation LParenLoc,
4064 SourceLocation EndLoc) {
4065 Expr *ValExpr = Condition;
4066 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4067 !Condition->isInstantiationDependent() &&
4068 !Condition->containsUnexpandedParameterPack()) {
4069 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4070 Condition->getExprLoc(), Condition);
4071 if (Val.isInvalid())
4072 return nullptr;
4073
4074 ValExpr = Val.get();
4075 }
4076
4077 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4078}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004079ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4080 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004081 if (!Op)
4082 return ExprError();
4083
4084 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4085 public:
4086 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004087 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004088 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4089 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004090 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4091 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004092 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4093 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004094 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4095 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004096 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4097 QualType T,
4098 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004099 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4100 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004101 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4102 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004103 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004104 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004105 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004106 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4107 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004108 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4109 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004110 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4111 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004112 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004113 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004114 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004115 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4116 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004117 llvm_unreachable("conversion functions are permitted");
4118 }
4119 } ConvertDiagnoser;
4120 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4121}
4122
4123OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4124 SourceLocation StartLoc,
4125 SourceLocation LParenLoc,
4126 SourceLocation EndLoc) {
4127 Expr *ValExpr = NumThreads;
4128 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004129 !NumThreads->containsUnexpandedParameterPack()) {
4130 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4131 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004132 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004133 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004134 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004135
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004136 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004137
4138 // OpenMP [2.5, Restrictions]
4139 // The num_threads expression must evaluate to a positive integer value.
4140 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004141 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4142 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004143 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4144 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004145 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004146 }
4147 }
4148
Alexey Bataeved09d242014-05-28 05:53:51 +00004149 return new (Context)
4150 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004151}
4152
Alexey Bataev62c87d22014-03-21 04:51:18 +00004153ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4154 OpenMPClauseKind CKind) {
4155 if (!E)
4156 return ExprError();
4157 if (E->isValueDependent() || E->isTypeDependent() ||
4158 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004159 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004160 llvm::APSInt Result;
4161 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4162 if (ICE.isInvalid())
4163 return ExprError();
4164 if (!Result.isStrictlyPositive()) {
4165 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4166 << getOpenMPClauseName(CKind) << E->getSourceRange();
4167 return ExprError();
4168 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004169 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4170 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4171 << E->getSourceRange();
4172 return ExprError();
4173 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004174 return ICE;
4175}
4176
4177OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4178 SourceLocation LParenLoc,
4179 SourceLocation EndLoc) {
4180 // OpenMP [2.8.1, simd construct, Description]
4181 // The parameter of the safelen clause must be a constant
4182 // positive integer expression.
4183 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4184 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004185 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004186 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004187 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004188}
4189
Alexander Musman64d33f12014-06-04 07:53:32 +00004190OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4191 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004192 SourceLocation LParenLoc,
4193 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004194 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004195 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004196 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004197 // The parameter of the collapse clause must be a constant
4198 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004199 ExprResult NumForLoopsResult =
4200 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4201 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004202 return nullptr;
4203 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004204 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004205}
4206
Alexey Bataeved09d242014-05-28 05:53:51 +00004207OMPClause *Sema::ActOnOpenMPSimpleClause(
4208 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4209 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004210 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004211 switch (Kind) {
4212 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004213 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004214 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4215 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004216 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004217 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004218 Res = ActOnOpenMPProcBindClause(
4219 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4220 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004221 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004222 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004223 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004224 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004225 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004226 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004227 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004228 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004229 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004230 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004231 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004232 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004233 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004234 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004235 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004236 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004237 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004238 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004239 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004240 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004241 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004242 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004243 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004244 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004245 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004246 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004247 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004248 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004249 llvm_unreachable("Clause is not allowed.");
4250 }
4251 return Res;
4252}
4253
4254OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4255 SourceLocation KindKwLoc,
4256 SourceLocation StartLoc,
4257 SourceLocation LParenLoc,
4258 SourceLocation EndLoc) {
4259 if (Kind == OMPC_DEFAULT_unknown) {
4260 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004261 static_assert(OMPC_DEFAULT_unknown > 0,
4262 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004263 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004264 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004265 Values += "'";
4266 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4267 Values += "'";
4268 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004269 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004270 Values += " or ";
4271 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004272 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004273 break;
4274 default:
4275 Values += Sep;
4276 break;
4277 }
4278 }
4279 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004280 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004281 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004282 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004283 switch (Kind) {
4284 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004285 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004286 break;
4287 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004288 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004289 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004290 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004291 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004292 break;
4293 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004294 return new (Context)
4295 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004296}
4297
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004298OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4299 SourceLocation KindKwLoc,
4300 SourceLocation StartLoc,
4301 SourceLocation LParenLoc,
4302 SourceLocation EndLoc) {
4303 if (Kind == OMPC_PROC_BIND_unknown) {
4304 std::string Values;
4305 std::string Sep(", ");
4306 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4307 Values += "'";
4308 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4309 Values += "'";
4310 switch (i) {
4311 case OMPC_PROC_BIND_unknown - 2:
4312 Values += " or ";
4313 break;
4314 case OMPC_PROC_BIND_unknown - 1:
4315 break;
4316 default:
4317 Values += Sep;
4318 break;
4319 }
4320 }
4321 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004322 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004323 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004324 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004325 return new (Context)
4326 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004327}
4328
Alexey Bataev56dafe82014-06-20 07:16:17 +00004329OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4330 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4331 SourceLocation StartLoc, SourceLocation LParenLoc,
4332 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4333 SourceLocation EndLoc) {
4334 OMPClause *Res = nullptr;
4335 switch (Kind) {
4336 case OMPC_schedule:
4337 Res = ActOnOpenMPScheduleClause(
4338 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4339 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4340 break;
4341 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004342 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004343 case OMPC_num_threads:
4344 case OMPC_safelen:
4345 case OMPC_collapse:
4346 case OMPC_default:
4347 case OMPC_proc_bind:
4348 case OMPC_private:
4349 case OMPC_firstprivate:
4350 case OMPC_lastprivate:
4351 case OMPC_shared:
4352 case OMPC_reduction:
4353 case OMPC_linear:
4354 case OMPC_aligned:
4355 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004356 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004357 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004358 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004359 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004360 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004361 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004362 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004363 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004364 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004365 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004366 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004367 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004368 case OMPC_unknown:
4369 llvm_unreachable("Clause is not allowed.");
4370 }
4371 return Res;
4372}
4373
4374OMPClause *Sema::ActOnOpenMPScheduleClause(
4375 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4376 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4377 SourceLocation EndLoc) {
4378 if (Kind == OMPC_SCHEDULE_unknown) {
4379 std::string Values;
4380 std::string Sep(", ");
4381 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4382 Values += "'";
4383 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4384 Values += "'";
4385 switch (i) {
4386 case OMPC_SCHEDULE_unknown - 2:
4387 Values += " or ";
4388 break;
4389 case OMPC_SCHEDULE_unknown - 1:
4390 break;
4391 default:
4392 Values += Sep;
4393 break;
4394 }
4395 }
4396 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4397 << Values << getOpenMPClauseName(OMPC_schedule);
4398 return nullptr;
4399 }
4400 Expr *ValExpr = ChunkSize;
4401 if (ChunkSize) {
4402 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4403 !ChunkSize->isInstantiationDependent() &&
4404 !ChunkSize->containsUnexpandedParameterPack()) {
4405 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4406 ExprResult Val =
4407 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4408 if (Val.isInvalid())
4409 return nullptr;
4410
4411 ValExpr = Val.get();
4412
4413 // OpenMP [2.7.1, Restrictions]
4414 // chunk_size must be a loop invariant integer expression with a positive
4415 // value.
4416 llvm::APSInt Result;
4417 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
4418 Result.isSigned() && !Result.isStrictlyPositive()) {
4419 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4420 << "schedule" << ChunkSize->getSourceRange();
4421 return nullptr;
4422 }
4423 }
4424 }
4425
4426 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4427 EndLoc, Kind, ValExpr);
4428}
4429
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004430OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4431 SourceLocation StartLoc,
4432 SourceLocation EndLoc) {
4433 OMPClause *Res = nullptr;
4434 switch (Kind) {
4435 case OMPC_ordered:
4436 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4437 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004438 case OMPC_nowait:
4439 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4440 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004441 case OMPC_untied:
4442 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4443 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004444 case OMPC_mergeable:
4445 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4446 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004447 case OMPC_read:
4448 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4449 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004450 case OMPC_write:
4451 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4452 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004453 case OMPC_update:
4454 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4455 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004456 case OMPC_capture:
4457 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4458 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004459 case OMPC_seq_cst:
4460 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4461 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004462 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004463 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004464 case OMPC_num_threads:
4465 case OMPC_safelen:
4466 case OMPC_collapse:
4467 case OMPC_schedule:
4468 case OMPC_private:
4469 case OMPC_firstprivate:
4470 case OMPC_lastprivate:
4471 case OMPC_shared:
4472 case OMPC_reduction:
4473 case OMPC_linear:
4474 case OMPC_aligned:
4475 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004476 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004477 case OMPC_default:
4478 case OMPC_proc_bind:
4479 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004480 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004481 case OMPC_unknown:
4482 llvm_unreachable("Clause is not allowed.");
4483 }
4484 return Res;
4485}
4486
4487OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4488 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004489 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004490 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4491}
4492
Alexey Bataev236070f2014-06-20 11:19:47 +00004493OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4494 SourceLocation EndLoc) {
4495 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4496}
4497
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004498OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4499 SourceLocation EndLoc) {
4500 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4501}
4502
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004503OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4504 SourceLocation EndLoc) {
4505 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4506}
4507
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004508OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4509 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004510 return new (Context) OMPReadClause(StartLoc, EndLoc);
4511}
4512
Alexey Bataevdea47612014-07-23 07:46:59 +00004513OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4514 SourceLocation EndLoc) {
4515 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4516}
4517
Alexey Bataev67a4f222014-07-23 10:25:33 +00004518OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4519 SourceLocation EndLoc) {
4520 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4521}
4522
Alexey Bataev459dec02014-07-24 06:46:57 +00004523OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4524 SourceLocation EndLoc) {
4525 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4526}
4527
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004528OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4529 SourceLocation EndLoc) {
4530 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4531}
4532
Alexey Bataevc5e02582014-06-16 07:08:35 +00004533OMPClause *Sema::ActOnOpenMPVarListClause(
4534 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4535 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4536 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4537 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004538 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004539 switch (Kind) {
4540 case OMPC_private:
4541 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4542 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004543 case OMPC_firstprivate:
4544 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4545 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004546 case OMPC_lastprivate:
4547 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4548 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004549 case OMPC_shared:
4550 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4551 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004552 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004553 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4554 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004555 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004556 case OMPC_linear:
4557 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4558 ColonLoc, EndLoc);
4559 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004560 case OMPC_aligned:
4561 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4562 ColonLoc, EndLoc);
4563 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004564 case OMPC_copyin:
4565 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4566 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004567 case OMPC_copyprivate:
4568 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4569 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004570 case OMPC_flush:
4571 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4572 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004573 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004574 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004575 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004576 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004577 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004578 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004579 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004580 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004581 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004582 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004583 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004584 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004585 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004586 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004587 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004588 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004589 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004590 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004591 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004592 llvm_unreachable("Clause is not allowed.");
4593 }
4594 return Res;
4595}
4596
4597OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4598 SourceLocation StartLoc,
4599 SourceLocation LParenLoc,
4600 SourceLocation EndLoc) {
4601 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004602 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004603 for (auto &RefExpr : VarList) {
4604 assert(RefExpr && "NULL expr in OpenMP private clause.");
4605 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004606 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004607 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004608 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004609 continue;
4610 }
4611
Alexey Bataeved09d242014-05-28 05:53:51 +00004612 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004613 // OpenMP [2.1, C/C++]
4614 // A list item is a variable name.
4615 // OpenMP [2.9.3.3, Restrictions, p.1]
4616 // A variable that is part of another variable (as an array or
4617 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004618 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004619 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004620 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004621 continue;
4622 }
4623 Decl *D = DE->getDecl();
4624 VarDecl *VD = cast<VarDecl>(D);
4625
4626 QualType Type = VD->getType();
4627 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4628 // It will be analyzed later.
4629 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004630 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004631 continue;
4632 }
4633
4634 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4635 // A variable that appears in a private clause must not have an incomplete
4636 // type or a reference type.
4637 if (RequireCompleteType(ELoc, Type,
4638 diag::err_omp_private_incomplete_type)) {
4639 continue;
4640 }
4641 if (Type->isReferenceType()) {
4642 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004643 << getOpenMPClauseName(OMPC_private) << Type;
4644 bool IsDecl =
4645 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4646 Diag(VD->getLocation(),
4647 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4648 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004649 continue;
4650 }
4651
4652 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4653 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004654 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004655 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004656 while (Type->isArrayType()) {
4657 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004658 }
4659
Alexey Bataev758e55e2013-09-06 18:03:48 +00004660 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4661 // in a Construct]
4662 // Variables with the predetermined data-sharing attributes may not be
4663 // listed in data-sharing attributes clauses, except for the cases
4664 // listed below. For these exceptions only, listing a predetermined
4665 // variable in a data-sharing attribute clause is allowed and overrides
4666 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004667 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004668 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004669 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4670 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004671 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004672 continue;
4673 }
4674
Alexey Bataev03b340a2014-10-21 03:16:40 +00004675 // Generate helper private variable and initialize it with the default
4676 // value. The address of the original variable is replaced by the address of
4677 // the new private variable in CodeGen. This new variable is not added to
4678 // IdResolver, so the code in the OpenMP region uses original variable for
4679 // proper diagnostics.
4680 auto VDPrivate =
4681 VarDecl::Create(Context, CurContext, DE->getLocStart(),
4682 DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
4683 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4684 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4685 if (VDPrivate->isInvalidDecl())
4686 continue;
4687 CurContext->addDecl(VDPrivate);
Alexey Bataev07649fb2014-12-16 08:01:48 +00004688 auto VDPrivateRefExpr =
4689 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4690 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004691 /*RefersToEnclosingVariableOrCapture*/ false,
Alexey Bataev07649fb2014-12-16 08:01:48 +00004692 /*NameLoc*/ SourceLocation(), DE->getType(),
4693 /*VK*/ VK_LValue);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004694
Alexey Bataev758e55e2013-09-06 18:03:48 +00004695 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004696 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004697 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004698 }
4699
Alexey Bataeved09d242014-05-28 05:53:51 +00004700 if (Vars.empty())
4701 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004702
Alexey Bataev03b340a2014-10-21 03:16:40 +00004703 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4704 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004705}
4706
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004707namespace {
4708class DiagsUninitializedSeveretyRAII {
4709private:
4710 DiagnosticsEngine &Diags;
4711 SourceLocation SavedLoc;
4712 bool IsIgnored;
4713
4714public:
4715 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4716 bool IsIgnored)
4717 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4718 if (!IsIgnored) {
4719 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4720 /*Map*/ diag::Severity::Ignored, Loc);
4721 }
4722 }
4723 ~DiagsUninitializedSeveretyRAII() {
4724 if (!IsIgnored)
4725 Diags.popMappings(SavedLoc);
4726 }
4727};
4728}
4729
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004730OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4731 SourceLocation StartLoc,
4732 SourceLocation LParenLoc,
4733 SourceLocation EndLoc) {
4734 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004735 SmallVector<Expr *, 8> PrivateCopies;
4736 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004737 bool IsImplicitClause =
4738 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4739 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4740
Alexey Bataeved09d242014-05-28 05:53:51 +00004741 for (auto &RefExpr : VarList) {
4742 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4743 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004744 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004745 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004746 PrivateCopies.push_back(nullptr);
4747 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004748 continue;
4749 }
4750
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004751 SourceLocation ELoc =
4752 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004753 // OpenMP [2.1, C/C++]
4754 // A list item is a variable name.
4755 // OpenMP [2.9.3.3, Restrictions, p.1]
4756 // A variable that is part of another variable (as an array or
4757 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004758 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004759 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004760 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004761 continue;
4762 }
4763 Decl *D = DE->getDecl();
4764 VarDecl *VD = cast<VarDecl>(D);
4765
4766 QualType Type = VD->getType();
4767 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4768 // It will be analyzed later.
4769 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004770 PrivateCopies.push_back(nullptr);
4771 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004772 continue;
4773 }
4774
4775 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4776 // A variable that appears in a private clause must not have an incomplete
4777 // type or a reference type.
4778 if (RequireCompleteType(ELoc, Type,
4779 diag::err_omp_firstprivate_incomplete_type)) {
4780 continue;
4781 }
4782 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004783 if (IsImplicitClause) {
4784 Diag(ImplicitClauseLoc,
4785 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4786 << Type;
4787 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4788 } else {
4789 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4790 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4791 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004792 bool IsDecl =
4793 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4794 Diag(VD->getLocation(),
4795 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4796 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004797 continue;
4798 }
4799
4800 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4801 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004802 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004803 // class type.
4804 Type = Context.getBaseElementType(Type);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004805
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004806 // If an implicit firstprivate variable found it was checked already.
4807 if (!IsImplicitClause) {
4808 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004809 Type = Type.getNonReferenceType().getCanonicalType();
4810 bool IsConstant = Type.isConstant(Context);
4811 Type = Context.getBaseElementType(Type);
4812 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4813 // A list item that specifies a given variable may not appear in more
4814 // than one clause on the same directive, except that a variable may be
4815 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004816 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004817 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004818 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004819 << getOpenMPClauseName(DVar.CKind)
4820 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004821 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004822 continue;
4823 }
4824
4825 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4826 // in a Construct]
4827 // Variables with the predetermined data-sharing attributes may not be
4828 // listed in data-sharing attributes clauses, except for the cases
4829 // listed below. For these exceptions only, listing a predetermined
4830 // variable in a data-sharing attribute clause is allowed and overrides
4831 // the variable's predetermined data-sharing attributes.
4832 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4833 // in a Construct, C/C++, p.2]
4834 // Variables with const-qualified type having no mutable member may be
4835 // listed in a firstprivate clause, even if they are static data members.
4836 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4837 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4838 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004839 << getOpenMPClauseName(DVar.CKind)
4840 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004841 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004842 continue;
4843 }
4844
Alexey Bataevf29276e2014-06-18 04:14:57 +00004845 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004846 // OpenMP [2.9.3.4, Restrictions, p.2]
4847 // A list item that is private within a parallel region must not appear
4848 // in a firstprivate clause on a worksharing construct if any of the
4849 // worksharing regions arising from the worksharing construct ever bind
4850 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004851 if (isOpenMPWorksharingDirective(CurrDir) &&
4852 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004853 DVar = DSAStack->getImplicitDSA(VD, true);
4854 if (DVar.CKind != OMPC_shared &&
4855 (isOpenMPParallelDirective(DVar.DKind) ||
4856 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004857 Diag(ELoc, diag::err_omp_required_access)
4858 << getOpenMPClauseName(OMPC_firstprivate)
4859 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004860 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004861 continue;
4862 }
4863 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004864 // OpenMP [2.9.3.4, Restrictions, p.3]
4865 // A list item that appears in a reduction clause of a parallel construct
4866 // must not appear in a firstprivate clause on a worksharing or task
4867 // construct if any of the worksharing or task regions arising from the
4868 // worksharing or task construct ever bind to any of the parallel regions
4869 // arising from the parallel construct.
4870 // OpenMP [2.9.3.4, Restrictions, p.4]
4871 // A list item that appears in a reduction clause in worksharing
4872 // construct must not appear in a firstprivate clause in a task construct
4873 // encountered during execution of any of the worksharing regions arising
4874 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004875 if (CurrDir == OMPD_task) {
4876 DVar =
4877 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4878 [](OpenMPDirectiveKind K) -> bool {
4879 return isOpenMPParallelDirective(K) ||
4880 isOpenMPWorksharingDirective(K);
4881 },
4882 false);
4883 if (DVar.CKind == OMPC_reduction &&
4884 (isOpenMPParallelDirective(DVar.DKind) ||
4885 isOpenMPWorksharingDirective(DVar.DKind))) {
4886 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4887 << getOpenMPDirectiveName(DVar.DKind);
4888 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4889 continue;
4890 }
4891 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004892 }
4893
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004894 Type = Type.getUnqualifiedType();
4895 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4896 ELoc, VD->getIdentifier(), VD->getType(),
4897 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4898 // Generate helper private variable and initialize it with the value of the
4899 // original variable. The address of the original variable is replaced by
4900 // the address of the new private variable in the CodeGen. This new variable
4901 // is not added to IdResolver, so the code in the OpenMP region uses
4902 // original variable for proper diagnostics and variable capturing.
4903 Expr *VDInitRefExpr = nullptr;
4904 // For arrays generate initializer for single element and replace it by the
4905 // original array element in CodeGen.
4906 if (DE->getType()->isArrayType()) {
4907 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4908 ELoc, VD->getIdentifier(), Type,
4909 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4910 CurContext->addHiddenDecl(VDInit);
4911 VDInitRefExpr = DeclRefExpr::Create(
4912 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4913 /*TemplateKWLoc*/ SourceLocation(), VDInit,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004914 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004915 /*VK*/ VK_LValue);
4916 VDInit->setIsUsed();
4917 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
4918 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit);
4919 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4920
4921 InitializationSequence InitSeq(*this, Entity, Kind, Init);
4922 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4923 if (Result.isInvalid())
4924 VDPrivate->setInvalidDecl();
4925 else
4926 VDPrivate->setInit(Result.getAs<Expr>());
4927 } else {
Alexey Bataevf841bd92014-12-16 07:00:22 +00004928 AddInitializerToDecl(
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004929 VDPrivate,
4930 DefaultLvalueConversion(
4931 DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
4932 SourceLocation(), DE->getDecl(),
4933 /*RefersToEnclosingVariableOrCapture=*/true,
4934 DE->getExprLoc(), DE->getType(),
4935 /*VK=*/VK_LValue)).get(),
Alexey Bataevf841bd92014-12-16 07:00:22 +00004936 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004937 }
4938 if (VDPrivate->isInvalidDecl()) {
4939 if (IsImplicitClause) {
4940 Diag(DE->getExprLoc(),
4941 diag::note_omp_task_predetermined_firstprivate_here);
4942 }
4943 continue;
4944 }
4945 CurContext->addDecl(VDPrivate);
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004946 auto VDPrivateRefExpr =
4947 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4948 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4949 /*RefersToEnclosingVariableOrCapture*/ false,
4950 DE->getLocStart(), DE->getType(),
4951 /*VK*/ VK_LValue);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004952 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4953 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004954 PrivateCopies.push_back(VDPrivateRefExpr);
4955 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004956 }
4957
Alexey Bataeved09d242014-05-28 05:53:51 +00004958 if (Vars.empty())
4959 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004960
4961 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004962 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004963}
4964
Alexander Musman1bb328c2014-06-04 13:06:39 +00004965OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
4966 SourceLocation StartLoc,
4967 SourceLocation LParenLoc,
4968 SourceLocation EndLoc) {
4969 SmallVector<Expr *, 8> Vars;
4970 for (auto &RefExpr : VarList) {
4971 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
4972 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4973 // It will be analyzed later.
4974 Vars.push_back(RefExpr);
4975 continue;
4976 }
4977
4978 SourceLocation ELoc = RefExpr->getExprLoc();
4979 // OpenMP [2.1, C/C++]
4980 // A list item is a variable name.
4981 // OpenMP [2.14.3.5, Restrictions, p.1]
4982 // A variable that is part of another variable (as an array or structure
4983 // element) cannot appear in a lastprivate clause.
4984 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4985 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4986 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4987 continue;
4988 }
4989 Decl *D = DE->getDecl();
4990 VarDecl *VD = cast<VarDecl>(D);
4991
4992 QualType Type = VD->getType();
4993 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4994 // It will be analyzed later.
4995 Vars.push_back(DE);
4996 continue;
4997 }
4998
4999 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5000 // A variable that appears in a lastprivate clause must not have an
5001 // incomplete type or a reference type.
5002 if (RequireCompleteType(ELoc, Type,
5003 diag::err_omp_lastprivate_incomplete_type)) {
5004 continue;
5005 }
5006 if (Type->isReferenceType()) {
5007 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5008 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5009 bool IsDecl =
5010 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5011 Diag(VD->getLocation(),
5012 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5013 << VD;
5014 continue;
5015 }
5016
5017 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5018 // in a Construct]
5019 // Variables with the predetermined data-sharing attributes may not be
5020 // listed in data-sharing attributes clauses, except for the cases
5021 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005022 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005023 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5024 DVar.CKind != OMPC_firstprivate &&
5025 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5026 Diag(ELoc, diag::err_omp_wrong_dsa)
5027 << getOpenMPClauseName(DVar.CKind)
5028 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005029 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005030 continue;
5031 }
5032
Alexey Bataevf29276e2014-06-18 04:14:57 +00005033 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5034 // OpenMP [2.14.3.5, Restrictions, p.2]
5035 // A list item that is private within a parallel region, or that appears in
5036 // the reduction clause of a parallel construct, must not appear in a
5037 // lastprivate clause on a worksharing construct if any of the corresponding
5038 // worksharing regions ever binds to any of the corresponding parallel
5039 // regions.
Alexey Bataev549210e2014-06-24 04:39:47 +00005040 if (isOpenMPWorksharingDirective(CurrDir) &&
5041 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005042 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005043 if (DVar.CKind != OMPC_shared) {
5044 Diag(ELoc, diag::err_omp_required_access)
5045 << getOpenMPClauseName(OMPC_lastprivate)
5046 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005047 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005048 continue;
5049 }
5050 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005051 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005052 // A variable of class type (or array thereof) that appears in a
5053 // lastprivate clause requires an accessible, unambiguous default
5054 // constructor for the class type, unless the list item is also specified
5055 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005056 // A variable of class type (or array thereof) that appears in a
5057 // lastprivate clause requires an accessible, unambiguous copy assignment
5058 // operator for the class type.
5059 while (Type.getNonReferenceType()->isArrayType())
5060 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
5061 ->getElementType();
5062 CXXRecordDecl *RD = getLangOpts().CPlusPlus
5063 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
5064 : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005065 // FIXME This code must be replaced by actual copying and destructing of the
5066 // lastprivate variable.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005067 if (RD) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00005068 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5069 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005070 if (MD) {
5071 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5072 MD->isDeleted()) {
5073 Diag(ELoc, diag::err_omp_required_method)
5074 << getOpenMPClauseName(OMPC_lastprivate) << 2;
5075 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5076 VarDecl::DeclarationOnly;
5077 Diag(VD->getLocation(),
5078 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5079 << VD;
5080 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5081 continue;
5082 }
5083 MarkFunctionReferenced(ELoc, MD);
5084 DiagnoseUseOfDecl(MD, ELoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005085 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005086
5087 CXXDestructorDecl *DD = RD->getDestructor();
5088 if (DD) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005089 PartialDiagnostic PD =
5090 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005091 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
5092 DD->isDeleted()) {
5093 Diag(ELoc, diag::err_omp_required_method)
5094 << getOpenMPClauseName(OMPC_lastprivate) << 4;
5095 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5096 VarDecl::DeclarationOnly;
5097 Diag(VD->getLocation(),
5098 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5099 << VD;
5100 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5101 continue;
5102 }
5103 MarkFunctionReferenced(ELoc, DD);
5104 DiagnoseUseOfDecl(DD, ELoc);
5105 }
5106 }
5107
Alexey Bataevf29276e2014-06-18 04:14:57 +00005108 if (DVar.CKind != OMPC_firstprivate)
5109 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005110 Vars.push_back(DE);
5111 }
5112
5113 if (Vars.empty())
5114 return nullptr;
5115
5116 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5117 Vars);
5118}
5119
Alexey Bataev758e55e2013-09-06 18:03:48 +00005120OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5121 SourceLocation StartLoc,
5122 SourceLocation LParenLoc,
5123 SourceLocation EndLoc) {
5124 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005125 for (auto &RefExpr : VarList) {
5126 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5127 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005128 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005129 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005130 continue;
5131 }
5132
Alexey Bataeved09d242014-05-28 05:53:51 +00005133 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005134 // OpenMP [2.1, C/C++]
5135 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005136 // OpenMP [2.14.3.2, Restrictions, p.1]
5137 // A variable that is part of another variable (as an array or structure
5138 // element) cannot appear in a shared unless it is a static data member
5139 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005140 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005141 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005142 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005143 continue;
5144 }
5145 Decl *D = DE->getDecl();
5146 VarDecl *VD = cast<VarDecl>(D);
5147
5148 QualType Type = VD->getType();
5149 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5150 // It will be analyzed later.
5151 Vars.push_back(DE);
5152 continue;
5153 }
5154
5155 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5156 // in a Construct]
5157 // Variables with the predetermined data-sharing attributes may not be
5158 // listed in data-sharing attributes clauses, except for the cases
5159 // listed below. For these exceptions only, listing a predetermined
5160 // variable in a data-sharing attribute clause is allowed and overrides
5161 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005162 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005163 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5164 DVar.RefExpr) {
5165 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5166 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005167 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005168 continue;
5169 }
5170
5171 DSAStack->addDSA(VD, DE, OMPC_shared);
5172 Vars.push_back(DE);
5173 }
5174
Alexey Bataeved09d242014-05-28 05:53:51 +00005175 if (Vars.empty())
5176 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005177
5178 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5179}
5180
Alexey Bataevc5e02582014-06-16 07:08:35 +00005181namespace {
5182class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5183 DSAStackTy *Stack;
5184
5185public:
5186 bool VisitDeclRefExpr(DeclRefExpr *E) {
5187 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005188 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005189 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5190 return false;
5191 if (DVar.CKind != OMPC_unknown)
5192 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005193 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005194 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005195 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005196 return true;
5197 return false;
5198 }
5199 return false;
5200 }
5201 bool VisitStmt(Stmt *S) {
5202 for (auto Child : S->children()) {
5203 if (Child && Visit(Child))
5204 return true;
5205 }
5206 return false;
5207 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005208 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005209};
Alexey Bataev23b69422014-06-18 07:08:49 +00005210} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005211
5212OMPClause *Sema::ActOnOpenMPReductionClause(
5213 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5214 SourceLocation ColonLoc, SourceLocation EndLoc,
5215 CXXScopeSpec &ReductionIdScopeSpec,
5216 const DeclarationNameInfo &ReductionId) {
5217 // TODO: Allow scope specification search when 'declare reduction' is
5218 // supported.
5219 assert(ReductionIdScopeSpec.isEmpty() &&
5220 "No support for scoped reduction identifiers yet.");
5221
5222 auto DN = ReductionId.getName();
5223 auto OOK = DN.getCXXOverloadedOperator();
5224 BinaryOperatorKind BOK = BO_Comma;
5225
5226 // OpenMP [2.14.3.6, reduction clause]
5227 // C
5228 // reduction-identifier is either an identifier or one of the following
5229 // operators: +, -, *, &, |, ^, && and ||
5230 // C++
5231 // reduction-identifier is either an id-expression or one of the following
5232 // operators: +, -, *, &, |, ^, && and ||
5233 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5234 switch (OOK) {
5235 case OO_Plus:
5236 case OO_Minus:
5237 BOK = BO_AddAssign;
5238 break;
5239 case OO_Star:
5240 BOK = BO_MulAssign;
5241 break;
5242 case OO_Amp:
5243 BOK = BO_AndAssign;
5244 break;
5245 case OO_Pipe:
5246 BOK = BO_OrAssign;
5247 break;
5248 case OO_Caret:
5249 BOK = BO_XorAssign;
5250 break;
5251 case OO_AmpAmp:
5252 BOK = BO_LAnd;
5253 break;
5254 case OO_PipePipe:
5255 BOK = BO_LOr;
5256 break;
5257 default:
5258 if (auto II = DN.getAsIdentifierInfo()) {
5259 if (II->isStr("max"))
5260 BOK = BO_GT;
5261 else if (II->isStr("min"))
5262 BOK = BO_LT;
5263 }
5264 break;
5265 }
5266 SourceRange ReductionIdRange;
5267 if (ReductionIdScopeSpec.isValid()) {
5268 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5269 }
5270 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5271 if (BOK == BO_Comma) {
5272 // Not allowed reduction identifier is found.
5273 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5274 << ReductionIdRange;
5275 return nullptr;
5276 }
5277
5278 SmallVector<Expr *, 8> Vars;
5279 for (auto RefExpr : VarList) {
5280 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5281 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5282 // It will be analyzed later.
5283 Vars.push_back(RefExpr);
5284 continue;
5285 }
5286
5287 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5288 RefExpr->isInstantiationDependent() ||
5289 RefExpr->containsUnexpandedParameterPack()) {
5290 // It will be analyzed later.
5291 Vars.push_back(RefExpr);
5292 continue;
5293 }
5294
5295 auto ELoc = RefExpr->getExprLoc();
5296 auto ERange = RefExpr->getSourceRange();
5297 // OpenMP [2.1, C/C++]
5298 // A list item is a variable or array section, subject to the restrictions
5299 // specified in Section 2.4 on page 42 and in each of the sections
5300 // describing clauses and directives for which a list appears.
5301 // OpenMP [2.14.3.3, Restrictions, p.1]
5302 // A variable that is part of another variable (as an array or
5303 // structure element) cannot appear in a private clause.
5304 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5305 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5306 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5307 continue;
5308 }
5309 auto D = DE->getDecl();
5310 auto VD = cast<VarDecl>(D);
5311 auto Type = VD->getType();
5312 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5313 // A variable that appears in a private clause must not have an incomplete
5314 // type or a reference type.
5315 if (RequireCompleteType(ELoc, Type,
5316 diag::err_omp_reduction_incomplete_type))
5317 continue;
5318 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5319 // Arrays may not appear in a reduction clause.
5320 if (Type.getNonReferenceType()->isArrayType()) {
5321 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5322 bool IsDecl =
5323 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5324 Diag(VD->getLocation(),
5325 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5326 << VD;
5327 continue;
5328 }
5329 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5330 // A list item that appears in a reduction clause must not be
5331 // const-qualified.
5332 if (Type.getNonReferenceType().isConstant(Context)) {
5333 Diag(ELoc, diag::err_omp_const_variable)
5334 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5335 bool IsDecl =
5336 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5337 Diag(VD->getLocation(),
5338 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5339 << VD;
5340 continue;
5341 }
5342 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5343 // If a list-item is a reference type then it must bind to the same object
5344 // for all threads of the team.
5345 VarDecl *VDDef = VD->getDefinition();
5346 if (Type->isReferenceType() && VDDef) {
5347 DSARefChecker Check(DSAStack);
5348 if (Check.Visit(VDDef->getInit())) {
5349 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5350 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5351 continue;
5352 }
5353 }
5354 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5355 // The type of a list item that appears in a reduction clause must be valid
5356 // for the reduction-identifier. For a max or min reduction in C, the type
5357 // of the list item must be an allowed arithmetic data type: char, int,
5358 // float, double, or _Bool, possibly modified with long, short, signed, or
5359 // unsigned. For a max or min reduction in C++, the type of the list item
5360 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5361 // double, or bool, possibly modified with long, short, signed, or unsigned.
5362 if ((BOK == BO_GT || BOK == BO_LT) &&
5363 !(Type->isScalarType() ||
5364 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5365 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5366 << getLangOpts().CPlusPlus;
5367 bool IsDecl =
5368 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5369 Diag(VD->getLocation(),
5370 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5371 << VD;
5372 continue;
5373 }
5374 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5375 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5376 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5377 bool IsDecl =
5378 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5379 Diag(VD->getLocation(),
5380 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5381 << VD;
5382 continue;
5383 }
5384 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
5385 getDiagnostics().setSuppressAllDiagnostics(true);
5386 ExprResult ReductionOp =
5387 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5388 RefExpr, RefExpr);
5389 getDiagnostics().setSuppressAllDiagnostics(Suppress);
5390 if (ReductionOp.isInvalid()) {
5391 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
Alexey Bataev23b69422014-06-18 07:08:49 +00005392 << ReductionIdRange;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005393 bool IsDecl =
5394 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5395 Diag(VD->getLocation(),
5396 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5397 << VD;
5398 continue;
5399 }
5400
5401 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5402 // in a Construct]
5403 // Variables with the predetermined data-sharing attributes may not be
5404 // listed in data-sharing attributes clauses, except for the cases
5405 // listed below. For these exceptions only, listing a predetermined
5406 // variable in a data-sharing attribute clause is allowed and overrides
5407 // the variable's predetermined data-sharing attributes.
5408 // OpenMP [2.14.3.6, Restrictions, p.3]
5409 // Any number of reduction clauses can be specified on the directive,
5410 // but a list item can appear only once in the reduction clauses for that
5411 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005412 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005413 if (DVar.CKind == OMPC_reduction) {
5414 Diag(ELoc, diag::err_omp_once_referenced)
5415 << getOpenMPClauseName(OMPC_reduction);
5416 if (DVar.RefExpr) {
5417 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5418 }
5419 } else if (DVar.CKind != OMPC_unknown) {
5420 Diag(ELoc, diag::err_omp_wrong_dsa)
5421 << getOpenMPClauseName(DVar.CKind)
5422 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005423 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005424 continue;
5425 }
5426
5427 // OpenMP [2.14.3.6, Restrictions, p.1]
5428 // A list item that appears in a reduction clause of a worksharing
5429 // construct must be shared in the parallel regions to which any of the
5430 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005431 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005432 if (isOpenMPWorksharingDirective(CurrDir) &&
5433 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005434 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005435 if (DVar.CKind != OMPC_shared) {
5436 Diag(ELoc, diag::err_omp_required_access)
5437 << getOpenMPClauseName(OMPC_reduction)
5438 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005439 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005440 continue;
5441 }
5442 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005443
5444 CXXRecordDecl *RD = getLangOpts().CPlusPlus
5445 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
5446 : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005447 // FIXME This code must be replaced by actual constructing/destructing of
5448 // the reduction variable.
Alexey Bataevc5e02582014-06-16 07:08:35 +00005449 if (RD) {
5450 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
5451 PartialDiagnostic PD =
5452 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
Alexey Bataev23b69422014-06-18 07:08:49 +00005453 if (!CD ||
5454 CheckConstructorAccess(ELoc, CD,
5455 InitializedEntity::InitializeTemporary(Type),
5456 CD->getAccess(), PD) == AR_inaccessible ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00005457 CD->isDeleted()) {
5458 Diag(ELoc, diag::err_omp_required_method)
5459 << getOpenMPClauseName(OMPC_reduction) << 0;
5460 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5461 VarDecl::DeclarationOnly;
5462 Diag(VD->getLocation(),
5463 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5464 << VD;
5465 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5466 continue;
5467 }
5468 MarkFunctionReferenced(ELoc, CD);
5469 DiagnoseUseOfDecl(CD, ELoc);
5470
5471 CXXDestructorDecl *DD = RD->getDestructor();
5472 if (DD) {
5473 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
5474 DD->isDeleted()) {
5475 Diag(ELoc, diag::err_omp_required_method)
5476 << getOpenMPClauseName(OMPC_reduction) << 4;
5477 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5478 VarDecl::DeclarationOnly;
5479 Diag(VD->getLocation(),
5480 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5481 << VD;
5482 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5483 continue;
5484 }
5485 MarkFunctionReferenced(ELoc, DD);
5486 DiagnoseUseOfDecl(DD, ELoc);
5487 }
5488 }
5489
5490 DSAStack->addDSA(VD, DE, OMPC_reduction);
5491 Vars.push_back(DE);
5492 }
5493
5494 if (Vars.empty())
5495 return nullptr;
5496
5497 return OMPReductionClause::Create(
5498 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
5499 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
5500}
5501
Alexander Musman8dba6642014-04-22 13:09:42 +00005502OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5503 SourceLocation StartLoc,
5504 SourceLocation LParenLoc,
5505 SourceLocation ColonLoc,
5506 SourceLocation EndLoc) {
5507 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005508 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005509 for (auto &RefExpr : VarList) {
5510 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5511 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005512 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005513 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005514 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005515 continue;
5516 }
5517
5518 // OpenMP [2.14.3.7, linear clause]
5519 // A list item that appears in a linear clause is subject to the private
5520 // clause semantics described in Section 2.14.3.3 on page 159 except as
5521 // noted. In addition, the value of the new list item on each iteration
5522 // of the associated loop(s) corresponds to the value of the original
5523 // list item before entering the construct plus the logical number of
5524 // the iteration times linear-step.
5525
Alexey Bataeved09d242014-05-28 05:53:51 +00005526 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005527 // OpenMP [2.1, C/C++]
5528 // A list item is a variable name.
5529 // OpenMP [2.14.3.3, Restrictions, p.1]
5530 // A variable that is part of another variable (as an array or
5531 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005532 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005533 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005534 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005535 continue;
5536 }
5537
5538 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5539
5540 // OpenMP [2.14.3.7, linear clause]
5541 // A list-item cannot appear in more than one linear clause.
5542 // A list-item that appears in a linear clause cannot appear in any
5543 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005544 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005545 if (DVar.RefExpr) {
5546 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5547 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005548 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005549 continue;
5550 }
5551
5552 QualType QType = VD->getType();
5553 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5554 // It will be analyzed later.
5555 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005556 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005557 continue;
5558 }
5559
5560 // A variable must not have an incomplete type or a reference type.
5561 if (RequireCompleteType(ELoc, QType,
5562 diag::err_omp_linear_incomplete_type)) {
5563 continue;
5564 }
5565 if (QType->isReferenceType()) {
5566 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5567 << getOpenMPClauseName(OMPC_linear) << QType;
5568 bool IsDecl =
5569 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5570 Diag(VD->getLocation(),
5571 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5572 << VD;
5573 continue;
5574 }
5575
5576 // A list item must not be const-qualified.
5577 if (QType.isConstant(Context)) {
5578 Diag(ELoc, diag::err_omp_const_variable)
5579 << getOpenMPClauseName(OMPC_linear);
5580 bool IsDecl =
5581 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5582 Diag(VD->getLocation(),
5583 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5584 << VD;
5585 continue;
5586 }
5587
5588 // A list item must be of integral or pointer type.
5589 QType = QType.getUnqualifiedType().getCanonicalType();
5590 const Type *Ty = QType.getTypePtrOrNull();
5591 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5592 !Ty->isPointerType())) {
5593 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5594 bool IsDecl =
5595 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5596 Diag(VD->getLocation(),
5597 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5598 << VD;
5599 continue;
5600 }
5601
Alexander Musman3276a272015-03-21 10:12:56 +00005602 // Build var to save initial value.
5603 VarDecl *Init = BuildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
5604 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5605 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5606 CurContext->addDecl(Init);
5607 Init->setIsUsed();
5608 auto InitRef = DeclRefExpr::Create(
5609 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5610 /*TemplateKWLoc*/ SourceLocation(), Init,
5611 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
5612 /*VK*/ VK_LValue);
Alexander Musman8dba6642014-04-22 13:09:42 +00005613 DSAStack->addDSA(VD, DE, OMPC_linear);
5614 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005615 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005616 }
5617
5618 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005619 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005620
5621 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005622 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005623 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5624 !Step->isInstantiationDependent() &&
5625 !Step->containsUnexpandedParameterPack()) {
5626 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005627 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005628 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005629 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005630 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005631
Alexander Musman3276a272015-03-21 10:12:56 +00005632 // Build var to save the step value.
5633 VarDecl *SaveVar =
5634 BuildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5635 CurContext->addDecl(SaveVar);
5636 SaveVar->setIsUsed();
5637 ExprResult SaveRef =
5638 BuildDeclRefExpr(SaveVar, StepExpr->getType(), VK_LValue, StepLoc);
5639 ExprResult CalcStep =
5640 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5641
Alexander Musman8dba6642014-04-22 13:09:42 +00005642 // Warn about zero linear step (it would be probably better specified as
5643 // making corresponding variables 'const').
5644 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005645 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5646 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005647 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5648 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005649 if (!IsConstant && CalcStep.isUsable()) {
5650 // Calculate the step beforehand instead of doing this on each iteration.
5651 // (This is not used if the number of iterations may be kfold-ed).
5652 CalcStepExpr = CalcStep.get();
5653 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005654 }
5655
5656 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005657 Vars, Inits, StepExpr, CalcStepExpr);
5658}
5659
5660static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5661 Expr *NumIterations, Sema &SemaRef,
5662 Scope *S) {
5663 // Walk the vars and build update/final expressions for the CodeGen.
5664 SmallVector<Expr *, 8> Updates;
5665 SmallVector<Expr *, 8> Finals;
5666 Expr *Step = Clause.getStep();
5667 Expr *CalcStep = Clause.getCalcStep();
5668 // OpenMP [2.14.3.7, linear clause]
5669 // If linear-step is not specified it is assumed to be 1.
5670 if (Step == nullptr)
5671 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5672 else if (CalcStep)
5673 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5674 bool HasErrors = false;
5675 auto CurInit = Clause.inits().begin();
5676 for (auto &RefExpr : Clause.varlists()) {
5677 Expr *InitExpr = *CurInit;
5678
5679 // Build privatized reference to the current linear var.
5680 auto DE = cast<DeclRefExpr>(RefExpr);
5681 auto PrivateRef = DeclRefExpr::Create(
5682 SemaRef.Context, /*QualifierLoc*/ DE->getQualifierLoc(),
5683 /*TemplateKWLoc*/ SourceLocation(), DE->getDecl(),
5684 /* RefersToEnclosingVariableOrCapture */ true, DE->getLocStart(),
5685 DE->getType(), /*VK*/ VK_LValue);
5686
5687 // Build update: Var = InitExpr + IV * Step
5688 ExprResult Update =
5689 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5690 InitExpr, IV, Step, /* Subtract */ false);
5691 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5692
5693 // Build final: Var = InitExpr + NumIterations * Step
5694 ExprResult Final =
5695 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), RefExpr, InitExpr,
5696 NumIterations, Step, /* Subtract */ false);
5697 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5698 if (!Update.isUsable() || !Final.isUsable()) {
5699 Updates.push_back(nullptr);
5700 Finals.push_back(nullptr);
5701 HasErrors = true;
5702 } else {
5703 Updates.push_back(Update.get());
5704 Finals.push_back(Final.get());
5705 }
5706 ++CurInit;
5707 }
5708 Clause.setUpdates(Updates);
5709 Clause.setFinals(Finals);
5710 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005711}
5712
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005713OMPClause *Sema::ActOnOpenMPAlignedClause(
5714 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5715 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5716
5717 SmallVector<Expr *, 8> Vars;
5718 for (auto &RefExpr : VarList) {
5719 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5720 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5721 // It will be analyzed later.
5722 Vars.push_back(RefExpr);
5723 continue;
5724 }
5725
5726 SourceLocation ELoc = RefExpr->getExprLoc();
5727 // OpenMP [2.1, C/C++]
5728 // A list item is a variable name.
5729 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5730 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5731 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5732 continue;
5733 }
5734
5735 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5736
5737 // OpenMP [2.8.1, simd construct, Restrictions]
5738 // The type of list items appearing in the aligned clause must be
5739 // array, pointer, reference to array, or reference to pointer.
5740 QualType QType = DE->getType()
5741 .getNonReferenceType()
5742 .getUnqualifiedType()
5743 .getCanonicalType();
5744 const Type *Ty = QType.getTypePtrOrNull();
5745 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5746 !Ty->isPointerType())) {
5747 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5748 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5749 bool IsDecl =
5750 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5751 Diag(VD->getLocation(),
5752 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5753 << VD;
5754 continue;
5755 }
5756
5757 // OpenMP [2.8.1, simd construct, Restrictions]
5758 // A list-item cannot appear in more than one aligned clause.
5759 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5760 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5761 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5762 << getOpenMPClauseName(OMPC_aligned);
5763 continue;
5764 }
5765
5766 Vars.push_back(DE);
5767 }
5768
5769 // OpenMP [2.8.1, simd construct, Description]
5770 // The parameter of the aligned clause, alignment, must be a constant
5771 // positive integer expression.
5772 // If no optional parameter is specified, implementation-defined default
5773 // alignments for SIMD instructions on the target platforms are assumed.
5774 if (Alignment != nullptr) {
5775 ExprResult AlignResult =
5776 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5777 if (AlignResult.isInvalid())
5778 return nullptr;
5779 Alignment = AlignResult.get();
5780 }
5781 if (Vars.empty())
5782 return nullptr;
5783
5784 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5785 EndLoc, Vars, Alignment);
5786}
5787
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005788OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5789 SourceLocation StartLoc,
5790 SourceLocation LParenLoc,
5791 SourceLocation EndLoc) {
5792 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005793 for (auto &RefExpr : VarList) {
5794 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5795 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005796 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005797 Vars.push_back(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005798 continue;
5799 }
5800
Alexey Bataeved09d242014-05-28 05:53:51 +00005801 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005802 // OpenMP [2.1, C/C++]
5803 // A list item is a variable name.
5804 // OpenMP [2.14.4.1, Restrictions, p.1]
5805 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00005806 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005807 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005808 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005809 continue;
5810 }
5811
5812 Decl *D = DE->getDecl();
5813 VarDecl *VD = cast<VarDecl>(D);
5814
5815 QualType Type = VD->getType();
5816 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5817 // It will be analyzed later.
5818 Vars.push_back(DE);
5819 continue;
5820 }
5821
5822 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5823 // A list item that appears in a copyin clause must be threadprivate.
5824 if (!DSAStack->isThreadPrivate(VD)) {
5825 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00005826 << getOpenMPClauseName(OMPC_copyin)
5827 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005828 continue;
5829 }
5830
5831 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5832 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00005833 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005834 // operator for the class type.
5835 Type = Context.getBaseElementType(Type);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005836 CXXRecordDecl *RD =
5837 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005838 // FIXME This code must be replaced by actual assignment of the
5839 // threadprivate variable.
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005840 if (RD) {
5841 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5842 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005843 if (MD) {
5844 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5845 MD->isDeleted()) {
5846 Diag(ELoc, diag::err_omp_required_method)
5847 << getOpenMPClauseName(OMPC_copyin) << 2;
5848 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5849 VarDecl::DeclarationOnly;
5850 Diag(VD->getLocation(),
5851 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5852 << VD;
5853 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5854 continue;
5855 }
5856 MarkFunctionReferenced(ELoc, MD);
5857 DiagnoseUseOfDecl(MD, ELoc);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005858 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005859 }
5860
5861 DSAStack->addDSA(VD, DE, OMPC_copyin);
5862 Vars.push_back(DE);
5863 }
5864
Alexey Bataeved09d242014-05-28 05:53:51 +00005865 if (Vars.empty())
5866 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005867
5868 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5869}
5870
Alexey Bataevbae9a792014-06-27 10:37:06 +00005871OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
5872 SourceLocation StartLoc,
5873 SourceLocation LParenLoc,
5874 SourceLocation EndLoc) {
5875 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00005876 SmallVector<Expr *, 8> SrcExprs;
5877 SmallVector<Expr *, 8> DstExprs;
5878 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005879 for (auto &RefExpr : VarList) {
5880 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
5881 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5882 // It will be analyzed later.
5883 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00005884 SrcExprs.push_back(nullptr);
5885 DstExprs.push_back(nullptr);
5886 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005887 continue;
5888 }
5889
5890 SourceLocation ELoc = RefExpr->getExprLoc();
5891 // OpenMP [2.1, C/C++]
5892 // A list item is a variable name.
5893 // OpenMP [2.14.4.1, Restrictions, p.1]
5894 // A list item that appears in a copyin clause must be threadprivate.
5895 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5896 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5897 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5898 continue;
5899 }
5900
5901 Decl *D = DE->getDecl();
5902 VarDecl *VD = cast<VarDecl>(D);
5903
5904 QualType Type = VD->getType();
5905 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5906 // It will be analyzed later.
5907 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00005908 SrcExprs.push_back(nullptr);
5909 DstExprs.push_back(nullptr);
5910 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005911 continue;
5912 }
5913
5914 // OpenMP [2.14.4.2, Restrictions, p.2]
5915 // A list item that appears in a copyprivate clause may not appear in a
5916 // private or firstprivate clause on the single construct.
5917 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005918 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00005919 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
5920 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00005921 Diag(ELoc, diag::err_omp_wrong_dsa)
5922 << getOpenMPClauseName(DVar.CKind)
5923 << getOpenMPClauseName(OMPC_copyprivate);
5924 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5925 continue;
5926 }
5927
5928 // OpenMP [2.11.4.2, Restrictions, p.1]
5929 // All list items that appear in a copyprivate clause must be either
5930 // threadprivate or private in the enclosing context.
5931 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005932 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005933 if (DVar.CKind == OMPC_shared) {
5934 Diag(ELoc, diag::err_omp_required_access)
5935 << getOpenMPClauseName(OMPC_copyprivate)
5936 << "threadprivate or private in the enclosing context";
5937 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5938 continue;
5939 }
5940 }
5941 }
5942
5943 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5944 // A variable of class type (or array thereof) that appears in a
5945 // copyin clause requires an accessible, unambiguous copy assignment
5946 // operator for the class type.
Alexey Bataeva63048e2015-03-23 06:18:07 +00005947 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(), VD->getType(),
5948 ".copyprivate.src");
5949 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, DE->getType(), VK_LValue,
5950 DE->getExprLoc()).get();
5951 auto *DstVD = BuildVarDecl(*this, DE->getLocStart(), VD->getType(),
5952 ".copyprivate.dst");
5953 auto *PseudoDstExpr = BuildDeclRefExpr(DstVD, DE->getType(), VK_LValue,
5954 DE->getExprLoc()).get();
5955 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5956 PseudoDstExpr, PseudoSrcExpr);
5957 if (AssignmentOp.isInvalid())
5958 continue;
5959 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5960 /*DiscardedValue=*/true);
5961 if (AssignmentOp.isInvalid())
5962 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005963
5964 // No need to mark vars as copyprivate, they are already threadprivate or
5965 // implicitly private.
5966 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00005967 SrcExprs.push_back(PseudoSrcExpr);
5968 DstExprs.push_back(PseudoDstExpr);
5969 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00005970 }
5971
5972 if (Vars.empty())
5973 return nullptr;
5974
Alexey Bataeva63048e2015-03-23 06:18:07 +00005975 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5976 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005977}
5978
Alexey Bataev6125da92014-07-21 11:26:11 +00005979OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
5980 SourceLocation StartLoc,
5981 SourceLocation LParenLoc,
5982 SourceLocation EndLoc) {
5983 if (VarList.empty())
5984 return nullptr;
5985
5986 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
5987}
Alexey Bataevdea47612014-07-23 07:46:59 +00005988