blob: 80ca072e2dd5e5d11a2db5dd3bd5f2bab7a8ed4e [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
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001190static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1191 OpenMPDirectiveKind CurrentRegion,
1192 const DeclarationNameInfo &CurrentName,
1193 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001194 // Allowed nesting of constructs
1195 // +------------------+-----------------+------------------------------------+
1196 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1197 // +------------------+-----------------+------------------------------------+
1198 // | parallel | parallel | * |
1199 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001200 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001201 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001202 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001203 // | parallel | simd | * |
1204 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001205 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001206 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001207 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001208 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001209 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001210 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001211 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001212 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001213 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001214 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001215 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001216 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001217 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001218 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001219 // +------------------+-----------------+------------------------------------+
1220 // | for | parallel | * |
1221 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001222 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001223 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001224 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001225 // | for | simd | * |
1226 // | for | sections | + |
1227 // | for | section | + |
1228 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001229 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001230 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001231 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001232 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001233 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001234 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001235 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001236 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001237 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001238 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001239 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001240 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001241 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001242 // | master | parallel | * |
1243 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001244 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001245 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001246 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001247 // | master | simd | * |
1248 // | master | sections | + |
1249 // | master | section | + |
1250 // | master | single | + |
1251 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001252 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001253 // | master |parallel sections| * |
1254 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001255 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001256 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001257 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001258 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001259 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001260 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001261 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001262 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001263 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001264 // | critical | parallel | * |
1265 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001266 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001267 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001268 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001269 // | critical | simd | * |
1270 // | critical | sections | + |
1271 // | critical | section | + |
1272 // | critical | single | + |
1273 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001274 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001275 // | critical |parallel sections| * |
1276 // | critical | task | * |
1277 // | critical | taskyield | * |
1278 // | critical | barrier | + |
1279 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001280 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001281 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001282 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001283 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001284 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001285 // | simd | parallel | |
1286 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001287 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001288 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001289 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001290 // | simd | simd | |
1291 // | simd | sections | |
1292 // | simd | section | |
1293 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001294 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001295 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001296 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001297 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001298 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001299 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001300 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001301 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001302 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001303 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001304 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001305 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001306 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001307 // | for simd | parallel | |
1308 // | for simd | for | |
1309 // | for simd | for simd | |
1310 // | for simd | master | |
1311 // | for simd | critical | |
1312 // | for simd | simd | |
1313 // | for simd | sections | |
1314 // | for simd | section | |
1315 // | for simd | single | |
1316 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001317 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001318 // | for simd |parallel sections| |
1319 // | for simd | task | |
1320 // | for simd | taskyield | |
1321 // | for simd | barrier | |
1322 // | for simd | taskwait | |
1323 // | for simd | flush | |
1324 // | for simd | ordered | |
1325 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001326 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001327 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001328 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001329 // | parallel for simd| parallel | |
1330 // | parallel for simd| for | |
1331 // | parallel for simd| for simd | |
1332 // | parallel for simd| master | |
1333 // | parallel for simd| critical | |
1334 // | parallel for simd| simd | |
1335 // | parallel for simd| sections | |
1336 // | parallel for simd| section | |
1337 // | parallel for simd| single | |
1338 // | parallel for simd| parallel for | |
1339 // | parallel for simd|parallel for simd| |
1340 // | parallel for simd|parallel sections| |
1341 // | parallel for simd| task | |
1342 // | parallel for simd| taskyield | |
1343 // | parallel for simd| barrier | |
1344 // | parallel for simd| taskwait | |
1345 // | parallel for simd| flush | |
1346 // | parallel for simd| ordered | |
1347 // | parallel for simd| atomic | |
1348 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001349 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001350 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001351 // | sections | parallel | * |
1352 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001353 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001354 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001355 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001356 // | sections | simd | * |
1357 // | sections | sections | + |
1358 // | sections | section | * |
1359 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001360 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001361 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001362 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001363 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001364 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001365 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001366 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001367 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001368 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001369 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001370 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001371 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001372 // +------------------+-----------------+------------------------------------+
1373 // | section | parallel | * |
1374 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001375 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001376 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001377 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001378 // | section | simd | * |
1379 // | section | sections | + |
1380 // | section | section | + |
1381 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001382 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001383 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001384 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001385 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001386 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001387 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001388 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001389 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001390 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001391 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001392 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001393 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001394 // +------------------+-----------------+------------------------------------+
1395 // | single | parallel | * |
1396 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001397 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001398 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001399 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001400 // | single | simd | * |
1401 // | single | sections | + |
1402 // | single | section | + |
1403 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001404 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001405 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001406 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001407 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001408 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001409 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001410 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001411 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001412 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001413 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001414 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001415 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001416 // +------------------+-----------------+------------------------------------+
1417 // | parallel for | parallel | * |
1418 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001419 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001420 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001421 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001422 // | parallel for | simd | * |
1423 // | parallel for | sections | + |
1424 // | parallel for | section | + |
1425 // | parallel for | single | + |
1426 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001427 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001428 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001429 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001430 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001431 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001432 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001433 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001434 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001435 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001436 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001437 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001438 // +------------------+-----------------+------------------------------------+
1439 // | parallel sections| parallel | * |
1440 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001441 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001442 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001443 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001444 // | parallel sections| simd | * |
1445 // | parallel sections| sections | + |
1446 // | parallel sections| section | * |
1447 // | parallel sections| single | + |
1448 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001449 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001450 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001451 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001452 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001453 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001454 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001455 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001456 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001457 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001458 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001459 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001460 // +------------------+-----------------+------------------------------------+
1461 // | task | parallel | * |
1462 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001463 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001464 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001465 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001466 // | task | simd | * |
1467 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001468 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001469 // | task | single | + |
1470 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001471 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 // | task |parallel sections| * |
1473 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001474 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001475 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001476 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001477 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001478 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001479 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001480 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001481 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001482 // +------------------+-----------------+------------------------------------+
1483 // | ordered | parallel | * |
1484 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001485 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001486 // | ordered | master | * |
1487 // | ordered | critical | * |
1488 // | ordered | simd | * |
1489 // | ordered | sections | + |
1490 // | ordered | section | + |
1491 // | ordered | single | + |
1492 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001493 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001494 // | ordered |parallel sections| * |
1495 // | ordered | task | * |
1496 // | ordered | taskyield | * |
1497 // | ordered | barrier | + |
1498 // | ordered | taskwait | * |
1499 // | ordered | flush | * |
1500 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001501 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001502 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001503 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001504 // +------------------+-----------------+------------------------------------+
1505 // | atomic | parallel | |
1506 // | atomic | for | |
1507 // | atomic | for simd | |
1508 // | atomic | master | |
1509 // | atomic | critical | |
1510 // | atomic | simd | |
1511 // | atomic | sections | |
1512 // | atomic | section | |
1513 // | atomic | single | |
1514 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001515 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001516 // | atomic |parallel sections| |
1517 // | atomic | task | |
1518 // | atomic | taskyield | |
1519 // | atomic | barrier | |
1520 // | atomic | taskwait | |
1521 // | atomic | flush | |
1522 // | atomic | ordered | |
1523 // | atomic | atomic | |
1524 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001525 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001526 // +------------------+-----------------+------------------------------------+
1527 // | target | parallel | * |
1528 // | target | for | * |
1529 // | target | for simd | * |
1530 // | target | master | * |
1531 // | target | critical | * |
1532 // | target | simd | * |
1533 // | target | sections | * |
1534 // | target | section | * |
1535 // | target | single | * |
1536 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001537 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001538 // | target |parallel sections| * |
1539 // | target | task | * |
1540 // | target | taskyield | * |
1541 // | target | barrier | * |
1542 // | target | taskwait | * |
1543 // | target | flush | * |
1544 // | target | ordered | * |
1545 // | target | atomic | * |
1546 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001547 // | target | teams | * |
1548 // +------------------+-----------------+------------------------------------+
1549 // | teams | parallel | * |
1550 // | teams | for | + |
1551 // | teams | for simd | + |
1552 // | teams | master | + |
1553 // | teams | critical | + |
1554 // | teams | simd | + |
1555 // | teams | sections | + |
1556 // | teams | section | + |
1557 // | teams | single | + |
1558 // | teams | parallel for | * |
1559 // | teams |parallel for simd| * |
1560 // | teams |parallel sections| * |
1561 // | teams | task | + |
1562 // | teams | taskyield | + |
1563 // | teams | barrier | + |
1564 // | teams | taskwait | + |
1565 // | teams | flush | + |
1566 // | teams | ordered | + |
1567 // | teams | atomic | + |
1568 // | teams | target | + |
1569 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001570 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001571 if (Stack->getCurScope()) {
1572 auto ParentRegion = Stack->getParentDirective();
1573 bool NestingProhibited = false;
1574 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001575 enum {
1576 NoRecommend,
1577 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001578 ShouldBeInOrderedRegion,
1579 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001580 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001581 if (isOpenMPSimdDirective(ParentRegion)) {
1582 // OpenMP [2.16, Nesting of Regions]
1583 // OpenMP constructs may not be nested inside a simd region.
1584 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1585 return true;
1586 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001587 if (ParentRegion == OMPD_atomic) {
1588 // OpenMP [2.16, Nesting of Regions]
1589 // OpenMP constructs may not be nested inside an atomic region.
1590 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1591 return true;
1592 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001593 if (CurrentRegion == OMPD_section) {
1594 // OpenMP [2.7.2, sections Construct, Restrictions]
1595 // Orphaned section directives are prohibited. That is, the section
1596 // directives must appear within the sections construct and must not be
1597 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001598 if (ParentRegion != OMPD_sections &&
1599 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001600 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1601 << (ParentRegion != OMPD_unknown)
1602 << getOpenMPDirectiveName(ParentRegion);
1603 return true;
1604 }
1605 return false;
1606 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001607 // Allow some constructs to be orphaned (they could be used in functions,
1608 // called from OpenMP regions with the required preconditions).
1609 if (ParentRegion == OMPD_unknown)
1610 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001611 if (CurrentRegion == OMPD_master) {
1612 // OpenMP [2.16, Nesting of Regions]
1613 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001614 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001615 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1616 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001617 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1618 // OpenMP [2.16, Nesting of Regions]
1619 // A critical region may not be nested (closely or otherwise) inside a
1620 // critical region with the same name. Note that this restriction is not
1621 // sufficient to prevent deadlock.
1622 SourceLocation PreviousCriticalLoc;
1623 bool DeadLock =
1624 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1625 OpenMPDirectiveKind K,
1626 const DeclarationNameInfo &DNI,
1627 SourceLocation Loc)
1628 ->bool {
1629 if (K == OMPD_critical &&
1630 DNI.getName() == CurrentName.getName()) {
1631 PreviousCriticalLoc = Loc;
1632 return true;
1633 } else
1634 return false;
1635 },
1636 false /* skip top directive */);
1637 if (DeadLock) {
1638 SemaRef.Diag(StartLoc,
1639 diag::err_omp_prohibited_region_critical_same_name)
1640 << CurrentName.getName();
1641 if (PreviousCriticalLoc.isValid())
1642 SemaRef.Diag(PreviousCriticalLoc,
1643 diag::note_omp_previous_critical_region);
1644 return true;
1645 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001646 } else if (CurrentRegion == OMPD_barrier) {
1647 // OpenMP [2.16, Nesting of Regions]
1648 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001649 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001650 NestingProhibited =
1651 isOpenMPWorksharingDirective(ParentRegion) ||
1652 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1653 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001654 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001655 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001656 // OpenMP [2.16, Nesting of Regions]
1657 // A worksharing region may not be closely nested inside a worksharing,
1658 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001659 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001660 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001661 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1662 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1663 Recommend = ShouldBeInParallelRegion;
1664 } else if (CurrentRegion == OMPD_ordered) {
1665 // OpenMP [2.16, Nesting of Regions]
1666 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001667 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001668 // An ordered region must be closely nested inside a loop region (or
1669 // parallel loop region) with an ordered clause.
1670 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001671 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001672 !Stack->isParentOrderedRegion();
1673 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001674 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1675 // OpenMP [2.16, Nesting of Regions]
1676 // If specified, a teams construct must be contained within a target
1677 // construct.
1678 NestingProhibited = ParentRegion != OMPD_target;
1679 Recommend = ShouldBeInTargetRegion;
1680 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1681 }
1682 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1683 // OpenMP [2.16, Nesting of Regions]
1684 // distribute, parallel, parallel sections, parallel workshare, and the
1685 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1686 // constructs that can be closely nested in the teams region.
1687 // TODO: add distribute directive.
1688 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1689 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001690 }
1691 if (NestingProhibited) {
1692 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001693 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1694 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001695 return true;
1696 }
1697 }
1698 return false;
1699}
1700
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001701StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001702 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001703 ArrayRef<OMPClause *> Clauses,
1704 Stmt *AStmt,
1705 SourceLocation StartLoc,
1706 SourceLocation EndLoc) {
1707 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001708 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001709 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001710
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001711 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001712 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001713 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001714 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001715 if (AStmt) {
1716 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1717
1718 // Check default data sharing attributes for referenced variables.
1719 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1720 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1721 if (DSAChecker.isErrorFound())
1722 return StmtError();
1723 // Generate list of implicitly defined firstprivate variables.
1724 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001725
1726 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1727 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1728 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1729 SourceLocation(), SourceLocation())) {
1730 ClausesWithImplicit.push_back(Implicit);
1731 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1732 DSAChecker.getImplicitFirstprivate().size();
1733 } else
1734 ErrorFound = true;
1735 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001736 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001737
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001738 switch (Kind) {
1739 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001740 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1741 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001742 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001743 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001744 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1745 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001746 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001747 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001748 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1749 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001750 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001751 case OMPD_for_simd:
1752 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1753 EndLoc, VarsWithInheritedDSA);
1754 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001755 case OMPD_sections:
1756 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1757 EndLoc);
1758 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001759 case OMPD_section:
1760 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001761 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001762 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1763 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001764 case OMPD_single:
1765 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1766 EndLoc);
1767 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001768 case OMPD_master:
1769 assert(ClausesWithImplicit.empty() &&
1770 "No clauses are allowed for 'omp master' directive");
1771 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1772 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001773 case OMPD_critical:
1774 assert(ClausesWithImplicit.empty() &&
1775 "No clauses are allowed for 'omp critical' directive");
1776 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1777 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001778 case OMPD_parallel_for:
1779 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1780 EndLoc, VarsWithInheritedDSA);
1781 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001782 case OMPD_parallel_for_simd:
1783 Res = ActOnOpenMPParallelForSimdDirective(
1784 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1785 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001786 case OMPD_parallel_sections:
1787 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1788 StartLoc, EndLoc);
1789 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001790 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001791 Res =
1792 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1793 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001794 case OMPD_taskyield:
1795 assert(ClausesWithImplicit.empty() &&
1796 "No clauses are allowed for 'omp taskyield' directive");
1797 assert(AStmt == nullptr &&
1798 "No associated statement allowed for 'omp taskyield' directive");
1799 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1800 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001801 case OMPD_barrier:
1802 assert(ClausesWithImplicit.empty() &&
1803 "No clauses are allowed for 'omp barrier' directive");
1804 assert(AStmt == nullptr &&
1805 "No associated statement allowed for 'omp barrier' directive");
1806 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1807 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001808 case OMPD_taskwait:
1809 assert(ClausesWithImplicit.empty() &&
1810 "No clauses are allowed for 'omp taskwait' directive");
1811 assert(AStmt == nullptr &&
1812 "No associated statement allowed for 'omp taskwait' directive");
1813 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1814 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001815 case OMPD_flush:
1816 assert(AStmt == nullptr &&
1817 "No associated statement allowed for 'omp flush' directive");
1818 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1819 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001820 case OMPD_ordered:
1821 assert(ClausesWithImplicit.empty() &&
1822 "No clauses are allowed for 'omp ordered' directive");
1823 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1824 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001825 case OMPD_atomic:
1826 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1827 EndLoc);
1828 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001829 case OMPD_teams:
1830 Res =
1831 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1832 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001833 case OMPD_target:
1834 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1835 EndLoc);
1836 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001837 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001838 llvm_unreachable("OpenMP Directive is not allowed");
1839 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001840 llvm_unreachable("Unknown OpenMP directive");
1841 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001842
Alexey Bataev4acb8592014-07-07 13:01:15 +00001843 for (auto P : VarsWithInheritedDSA) {
1844 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1845 << P.first << P.second->getSourceRange();
1846 }
1847 if (!VarsWithInheritedDSA.empty())
1848 return StmtError();
1849
Alexey Bataeved09d242014-05-28 05:53:51 +00001850 if (ErrorFound)
1851 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001852 return Res;
1853}
1854
1855StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1856 Stmt *AStmt,
1857 SourceLocation StartLoc,
1858 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001859 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1860 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1861 // 1.2.2 OpenMP Language Terminology
1862 // Structured block - An executable statement with a single entry at the
1863 // top and a single exit at the bottom.
1864 // The point of exit cannot be a branch out of the structured block.
1865 // longjmp() and throw() must not violate the entry/exit criteria.
1866 CS->getCapturedDecl()->setNothrow();
1867
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001868 getCurFunction()->setHasBranchProtectedScope();
1869
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001870 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1871 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001872}
1873
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001874namespace {
1875/// \brief Helper class for checking canonical form of the OpenMP loops and
1876/// extracting iteration space of each loop in the loop nest, that will be used
1877/// for IR generation.
1878class OpenMPIterationSpaceChecker {
1879 /// \brief Reference to Sema.
1880 Sema &SemaRef;
1881 /// \brief A location for diagnostics (when there is no some better location).
1882 SourceLocation DefaultLoc;
1883 /// \brief A location for diagnostics (when increment is not compatible).
1884 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001885 /// \brief A source location for referring to loop init later.
1886 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001887 /// \brief A source location for referring to condition later.
1888 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001889 /// \brief A source location for referring to increment later.
1890 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001891 /// \brief Loop variable.
1892 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001893 /// \brief Reference to loop variable.
1894 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001895 /// \brief Lower bound (initializer for the var).
1896 Expr *LB;
1897 /// \brief Upper bound.
1898 Expr *UB;
1899 /// \brief Loop step (increment).
1900 Expr *Step;
1901 /// \brief This flag is true when condition is one of:
1902 /// Var < UB
1903 /// Var <= UB
1904 /// UB > Var
1905 /// UB >= Var
1906 bool TestIsLessOp;
1907 /// \brief This flag is true when condition is strict ( < or > ).
1908 bool TestIsStrictOp;
1909 /// \brief This flag is true when step is subtracted on each iteration.
1910 bool SubtractStep;
1911
1912public:
1913 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1914 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00001915 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1916 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001917 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1918 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001919 /// \brief Check init-expr for canonical loop form and save loop counter
1920 /// variable - #Var and its initialization value - #LB.
1921 bool CheckInit(Stmt *S);
1922 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1923 /// for less/greater and for strict/non-strict comparison.
1924 bool CheckCond(Expr *S);
1925 /// \brief Check incr-expr for canonical loop form and return true if it
1926 /// does not conform, otherwise save loop step (#Step).
1927 bool CheckInc(Expr *S);
1928 /// \brief Return the loop counter variable.
1929 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001930 /// \brief Return the reference expression to loop counter variable.
1931 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001932 /// \brief Source range of the loop init.
1933 SourceRange GetInitSrcRange() const { return InitSrcRange; }
1934 /// \brief Source range of the loop condition.
1935 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1936 /// \brief Source range of the loop increment.
1937 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1938 /// \brief True if the step should be subtracted.
1939 bool ShouldSubtractStep() const { return SubtractStep; }
1940 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00001941 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001942 /// \brief Build reference expression to the counter be used for codegen.
1943 Expr *BuildCounterVar() const;
1944 /// \brief Build initization of the counter be used for codegen.
1945 Expr *BuildCounterInit() const;
1946 /// \brief Build step of the counter be used for codegen.
1947 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001948 /// \brief Return true if any expression is dependent.
1949 bool Dependent() const;
1950
1951private:
1952 /// \brief Check the right-hand side of an assignment in the increment
1953 /// expression.
1954 bool CheckIncRHS(Expr *RHS);
1955 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001956 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001957 /// \brief Helper to set upper bound.
1958 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1959 const SourceLocation &SL);
1960 /// \brief Helper to set loop increment.
1961 bool SetStep(Expr *NewStep, bool Subtract);
1962};
1963
1964bool OpenMPIterationSpaceChecker::Dependent() const {
1965 if (!Var) {
1966 assert(!LB && !UB && !Step);
1967 return false;
1968 }
1969 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1970 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1971}
1972
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001973bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
1974 DeclRefExpr *NewVarRefExpr,
1975 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001976 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001977 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
1978 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001979 if (!NewVar || !NewLB)
1980 return true;
1981 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001982 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001983 LB = NewLB;
1984 return false;
1985}
1986
1987bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
1988 const SourceRange &SR,
1989 const SourceLocation &SL) {
1990 // State consistency checking to ensure correct usage.
1991 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
1992 !TestIsLessOp && !TestIsStrictOp);
1993 if (!NewUB)
1994 return true;
1995 UB = NewUB;
1996 TestIsLessOp = LessOp;
1997 TestIsStrictOp = StrictOp;
1998 ConditionSrcRange = SR;
1999 ConditionLoc = SL;
2000 return false;
2001}
2002
2003bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2004 // State consistency checking to ensure correct usage.
2005 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2006 if (!NewStep)
2007 return true;
2008 if (!NewStep->isValueDependent()) {
2009 // Check that the step is integer expression.
2010 SourceLocation StepLoc = NewStep->getLocStart();
2011 ExprResult Val =
2012 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2013 if (Val.isInvalid())
2014 return true;
2015 NewStep = Val.get();
2016
2017 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2018 // If test-expr is of form var relational-op b and relational-op is < or
2019 // <= then incr-expr must cause var to increase on each iteration of the
2020 // loop. If test-expr is of form var relational-op b and relational-op is
2021 // > or >= then incr-expr must cause var to decrease on each iteration of
2022 // the loop.
2023 // If test-expr is of form b relational-op var and relational-op is < or
2024 // <= then incr-expr must cause var to decrease on each iteration of the
2025 // loop. If test-expr is of form b relational-op var and relational-op is
2026 // > or >= then incr-expr must cause var to increase on each iteration of
2027 // the loop.
2028 llvm::APSInt Result;
2029 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2030 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2031 bool IsConstNeg =
2032 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002033 bool IsConstPos =
2034 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002035 bool IsConstZero = IsConstant && !Result.getBoolValue();
2036 if (UB && (IsConstZero ||
2037 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002038 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002039 SemaRef.Diag(NewStep->getExprLoc(),
2040 diag::err_omp_loop_incr_not_compatible)
2041 << Var << TestIsLessOp << NewStep->getSourceRange();
2042 SemaRef.Diag(ConditionLoc,
2043 diag::note_omp_loop_cond_requres_compatible_incr)
2044 << TestIsLessOp << ConditionSrcRange;
2045 return true;
2046 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002047 if (TestIsLessOp == Subtract) {
2048 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2049 NewStep).get();
2050 Subtract = !Subtract;
2051 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002052 }
2053
2054 Step = NewStep;
2055 SubtractStep = Subtract;
2056 return false;
2057}
2058
2059bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2060 // Check init-expr for canonical loop form and save loop counter
2061 // variable - #Var and its initialization value - #LB.
2062 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2063 // var = lb
2064 // integer-type var = lb
2065 // random-access-iterator-type var = lb
2066 // pointer-type var = lb
2067 //
2068 if (!S) {
2069 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2070 return true;
2071 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002072 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002073 if (Expr *E = dyn_cast<Expr>(S))
2074 S = E->IgnoreParens();
2075 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2076 if (BO->getOpcode() == BO_Assign)
2077 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002078 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002079 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002080 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2081 if (DS->isSingleDecl()) {
2082 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2083 if (Var->hasInit()) {
2084 // Accept non-canonical init form here but emit ext. warning.
2085 if (Var->getInitStyle() != VarDecl::CInit)
2086 SemaRef.Diag(S->getLocStart(),
2087 diag::ext_omp_loop_not_canonical_init)
2088 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002089 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002090 }
2091 }
2092 }
2093 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2094 if (CE->getOperator() == OO_Equal)
2095 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002096 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2097 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002098
2099 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2100 << S->getSourceRange();
2101 return true;
2102}
2103
Alexey Bataev23b69422014-06-18 07:08:49 +00002104/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002105/// variable (which may be the loop variable) if possible.
2106static const VarDecl *GetInitVarDecl(const Expr *E) {
2107 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002108 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002109 E = E->IgnoreParenImpCasts();
2110 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2111 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2112 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2113 CE->getArg(0) != nullptr)
2114 E = CE->getArg(0)->IgnoreParenImpCasts();
2115 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2116 if (!DRE)
2117 return nullptr;
2118 return dyn_cast<VarDecl>(DRE->getDecl());
2119}
2120
2121bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2122 // Check test-expr for canonical form, save upper-bound UB, flags for
2123 // less/greater and for strict/non-strict comparison.
2124 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2125 // var relational-op b
2126 // b relational-op var
2127 //
2128 if (!S) {
2129 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2130 return true;
2131 }
2132 S = S->IgnoreParenImpCasts();
2133 SourceLocation CondLoc = S->getLocStart();
2134 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2135 if (BO->isRelationalOp()) {
2136 if (GetInitVarDecl(BO->getLHS()) == Var)
2137 return SetUB(BO->getRHS(),
2138 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2139 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2140 BO->getSourceRange(), BO->getOperatorLoc());
2141 if (GetInitVarDecl(BO->getRHS()) == Var)
2142 return SetUB(BO->getLHS(),
2143 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2144 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2145 BO->getSourceRange(), BO->getOperatorLoc());
2146 }
2147 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2148 if (CE->getNumArgs() == 2) {
2149 auto Op = CE->getOperator();
2150 switch (Op) {
2151 case OO_Greater:
2152 case OO_GreaterEqual:
2153 case OO_Less:
2154 case OO_LessEqual:
2155 if (GetInitVarDecl(CE->getArg(0)) == Var)
2156 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2157 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2158 CE->getOperatorLoc());
2159 if (GetInitVarDecl(CE->getArg(1)) == Var)
2160 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2161 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2162 CE->getOperatorLoc());
2163 break;
2164 default:
2165 break;
2166 }
2167 }
2168 }
2169 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2170 << S->getSourceRange() << Var;
2171 return true;
2172}
2173
2174bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2175 // RHS of canonical loop form increment can be:
2176 // var + incr
2177 // incr + var
2178 // var - incr
2179 //
2180 RHS = RHS->IgnoreParenImpCasts();
2181 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2182 if (BO->isAdditiveOp()) {
2183 bool IsAdd = BO->getOpcode() == BO_Add;
2184 if (GetInitVarDecl(BO->getLHS()) == Var)
2185 return SetStep(BO->getRHS(), !IsAdd);
2186 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2187 return SetStep(BO->getLHS(), false);
2188 }
2189 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2190 bool IsAdd = CE->getOperator() == OO_Plus;
2191 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2192 if (GetInitVarDecl(CE->getArg(0)) == Var)
2193 return SetStep(CE->getArg(1), !IsAdd);
2194 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2195 return SetStep(CE->getArg(0), false);
2196 }
2197 }
2198 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2199 << RHS->getSourceRange() << Var;
2200 return true;
2201}
2202
2203bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2204 // Check incr-expr for canonical loop form and return true if it
2205 // does not conform.
2206 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2207 // ++var
2208 // var++
2209 // --var
2210 // var--
2211 // var += incr
2212 // var -= incr
2213 // var = var + incr
2214 // var = incr + var
2215 // var = var - incr
2216 //
2217 if (!S) {
2218 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2219 return true;
2220 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002221 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002222 S = S->IgnoreParens();
2223 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2224 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2225 return SetStep(
2226 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2227 (UO->isDecrementOp() ? -1 : 1)).get(),
2228 false);
2229 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2230 switch (BO->getOpcode()) {
2231 case BO_AddAssign:
2232 case BO_SubAssign:
2233 if (GetInitVarDecl(BO->getLHS()) == Var)
2234 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2235 break;
2236 case BO_Assign:
2237 if (GetInitVarDecl(BO->getLHS()) == Var)
2238 return CheckIncRHS(BO->getRHS());
2239 break;
2240 default:
2241 break;
2242 }
2243 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2244 switch (CE->getOperator()) {
2245 case OO_PlusPlus:
2246 case OO_MinusMinus:
2247 if (GetInitVarDecl(CE->getArg(0)) == Var)
2248 return SetStep(
2249 SemaRef.ActOnIntegerConstant(
2250 CE->getLocStart(),
2251 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2252 false);
2253 break;
2254 case OO_PlusEqual:
2255 case OO_MinusEqual:
2256 if (GetInitVarDecl(CE->getArg(0)) == Var)
2257 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2258 break;
2259 case OO_Equal:
2260 if (GetInitVarDecl(CE->getArg(0)) == Var)
2261 return CheckIncRHS(CE->getArg(1));
2262 break;
2263 default:
2264 break;
2265 }
2266 }
2267 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2268 << S->getSourceRange() << Var;
2269 return true;
2270}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002271
2272/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002273Expr *
2274OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2275 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002276 ExprResult Diff;
2277 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2278 SemaRef.getLangOpts().CPlusPlus) {
2279 // Upper - Lower
2280 Expr *Upper = TestIsLessOp ? UB : LB;
2281 Expr *Lower = TestIsLessOp ? LB : UB;
2282
2283 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2284
2285 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2286 // BuildBinOp already emitted error, this one is to point user to upper
2287 // and lower bound, and to tell what is passed to 'operator-'.
2288 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2289 << Upper->getSourceRange() << Lower->getSourceRange();
2290 return nullptr;
2291 }
2292 }
2293
2294 if (!Diff.isUsable())
2295 return nullptr;
2296
2297 // Upper - Lower [- 1]
2298 if (TestIsStrictOp)
2299 Diff = SemaRef.BuildBinOp(
2300 S, DefaultLoc, BO_Sub, Diff.get(),
2301 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2302 if (!Diff.isUsable())
2303 return nullptr;
2304
2305 // Upper - Lower [- 1] + Step
2306 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2307 Step->IgnoreImplicit());
2308 if (!Diff.isUsable())
2309 return nullptr;
2310
2311 // Parentheses (for dumping/debugging purposes only).
2312 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2313 if (!Diff.isUsable())
2314 return nullptr;
2315
2316 // (Upper - Lower [- 1] + Step) / Step
2317 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2318 Step->IgnoreImplicit());
2319 if (!Diff.isUsable())
2320 return nullptr;
2321
Alexander Musman174b3ca2014-10-06 11:16:29 +00002322 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2323 if (LimitedType) {
2324 auto &C = SemaRef.Context;
2325 QualType Type = Diff.get()->getType();
2326 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2327 if (NewSize != C.getTypeSize(Type)) {
2328 if (NewSize < C.getTypeSize(Type)) {
2329 assert(NewSize == 64 && "incorrect loop var size");
2330 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2331 << InitSrcRange << ConditionSrcRange;
2332 }
2333 QualType NewType = C.getIntTypeForBitwidth(
2334 NewSize, Type->hasSignedIntegerRepresentation());
2335 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2336 Sema::AA_Converting, true);
2337 if (!Diff.isUsable())
2338 return nullptr;
2339 }
2340 }
2341
Alexander Musmana5f070a2014-10-01 06:03:56 +00002342 return Diff.get();
2343}
2344
2345/// \brief Build reference expression to the counter be used for codegen.
2346Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2347 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2348 GetIncrementSrcRange().getBegin(), Var, false,
2349 DefaultLoc, Var->getType(), VK_LValue);
2350}
2351
2352/// \brief Build initization of the counter be used for codegen.
2353Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2354
2355/// \brief Build step of the counter be used for codegen.
2356Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2357
2358/// \brief Iteration space of a single for loop.
2359struct LoopIterationSpace {
2360 /// \brief This expression calculates the number of iterations in the loop.
2361 /// It is always possible to calculate it before starting the loop.
2362 Expr *NumIterations;
2363 /// \brief The loop counter variable.
2364 Expr *CounterVar;
2365 /// \brief This is initializer for the initial value of #CounterVar.
2366 Expr *CounterInit;
2367 /// \brief This is step for the #CounterVar used to generate its update:
2368 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2369 Expr *CounterStep;
2370 /// \brief Should step be subtracted?
2371 bool Subtract;
2372 /// \brief Source range of the loop init.
2373 SourceRange InitSrcRange;
2374 /// \brief Source range of the loop condition.
2375 SourceRange CondSrcRange;
2376 /// \brief Source range of the loop increment.
2377 SourceRange IncSrcRange;
2378};
2379
Alexey Bataev23b69422014-06-18 07:08:49 +00002380} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002381
2382/// \brief Called on a for stmt to check and extract its iteration space
2383/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002384static bool CheckOpenMPIterationSpace(
2385 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2386 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2387 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002388 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2389 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002390 // OpenMP [2.6, Canonical Loop Form]
2391 // for (init-expr; test-expr; incr-expr) structured-block
2392 auto For = dyn_cast_or_null<ForStmt>(S);
2393 if (!For) {
2394 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002395 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2396 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2397 << CurrentNestedLoopCount;
2398 if (NestedLoopCount > 1)
2399 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2400 diag::note_omp_collapse_expr)
2401 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002402 return true;
2403 }
2404 assert(For->getBody());
2405
2406 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2407
2408 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002409 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002410 if (ISC.CheckInit(Init)) {
2411 return true;
2412 }
2413
2414 bool HasErrors = false;
2415
2416 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002417 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002418
2419 // OpenMP [2.6, Canonical Loop Form]
2420 // Var is one of the following:
2421 // A variable of signed or unsigned integer type.
2422 // For C++, a variable of a random access iterator type.
2423 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002424 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002425 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2426 !VarType->isPointerType() &&
2427 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2428 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2429 << SemaRef.getLangOpts().CPlusPlus;
2430 HasErrors = true;
2431 }
2432
Alexey Bataev4acb8592014-07-07 13:01:15 +00002433 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2434 // Construct
2435 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2436 // parallel for construct is (are) private.
2437 // The loop iteration variable in the associated for-loop of a simd construct
2438 // with just one associated for-loop is linear with a constant-linear-step
2439 // that is the increment of the associated for-loop.
2440 // Exclude loop var from the list of variables with implicitly defined data
2441 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002442 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002443
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002444 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2445 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002446 // The loop iteration variable in the associated for-loop of a simd construct
2447 // with just one associated for-loop may be listed in a linear clause with a
2448 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002449 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2450 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002451 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002452 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2453 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2454 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002455 auto PredeterminedCKind =
2456 isOpenMPSimdDirective(DKind)
2457 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2458 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002459 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002460 DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002461 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2462 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2463 DVar.CKind != OMPC_lastprivate)) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00002464 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002465 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002466 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2467 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002468 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002469 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002470 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002471 // Make the loop iteration variable private (for worksharing constructs),
2472 // linear (for simd directives with the only one associated loop) or
2473 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002474 // FIXME: the next check and error message must be removed once the
2475 // capturing of global variables in loops is fixed.
2476 if (DVar.CKind == OMPC_unknown)
2477 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2478 /*FromParent=*/false);
2479 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2480 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2481 << getOpenMPClauseName(PredeterminedCKind)
2482 << getOpenMPDirectiveName(DKind);
2483 HasErrors = true;
2484 } else
2485 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002486 }
2487
Alexey Bataev7ff55242014-06-19 09:13:45 +00002488 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002489
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002490 // Check test-expr.
2491 HasErrors |= ISC.CheckCond(For->getCond());
2492
2493 // Check incr-expr.
2494 HasErrors |= ISC.CheckInc(For->getInc());
2495
Alexander Musmana5f070a2014-10-01 06:03:56 +00002496 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002497 return HasErrors;
2498
Alexander Musmana5f070a2014-10-01 06:03:56 +00002499 // Build the loop's iteration space representation.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002500 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2501 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002502 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2503 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2504 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2505 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2506 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2507 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2508 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2509
2510 HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
2511 ResultIterSpace.CounterVar == nullptr ||
2512 ResultIterSpace.CounterInit == nullptr ||
2513 ResultIterSpace.CounterStep == nullptr);
2514
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002515 return HasErrors;
2516}
2517
Alexander Musmana5f070a2014-10-01 06:03:56 +00002518/// \brief Build a variable declaration for OpenMP loop iteration variable.
2519static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2520 StringRef Name) {
2521 DeclContext *DC = SemaRef.CurContext;
2522 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2523 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2524 VarDecl *Decl =
2525 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2526 Decl->setImplicit();
2527 return Decl;
2528}
2529
2530/// \brief Build 'VarRef = Start + Iter * Step'.
2531static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2532 SourceLocation Loc, ExprResult VarRef,
2533 ExprResult Start, ExprResult Iter,
2534 ExprResult Step, bool Subtract) {
2535 // Add parentheses (for debugging purposes only).
2536 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2537 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2538 !Step.isUsable())
2539 return ExprError();
2540
2541 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2542 Step.get()->IgnoreImplicit());
2543 if (!Update.isUsable())
2544 return ExprError();
2545
2546 // Build 'VarRef = Start + Iter * Step'.
2547 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2548 Start.get()->IgnoreImplicit(), Update.get());
2549 if (!Update.isUsable())
2550 return ExprError();
2551
2552 Update = SemaRef.PerformImplicitConversion(
2553 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2554 if (!Update.isUsable())
2555 return ExprError();
2556
2557 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2558 return Update;
2559}
2560
2561/// \brief Convert integer expression \a E to make it have at least \a Bits
2562/// bits.
2563static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2564 Sema &SemaRef) {
2565 if (E == nullptr)
2566 return ExprError();
2567 auto &C = SemaRef.Context;
2568 QualType OldType = E->getType();
2569 unsigned HasBits = C.getTypeSize(OldType);
2570 if (HasBits >= Bits)
2571 return ExprResult(E);
2572 // OK to convert to signed, because new type has more bits than old.
2573 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2574 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2575 true);
2576}
2577
2578/// \brief Check if the given expression \a E is a constant integer that fits
2579/// into \a Bits bits.
2580static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2581 if (E == nullptr)
2582 return false;
2583 llvm::APSInt Result;
2584 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2585 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2586 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002587}
2588
2589/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002590/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2591/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002592static unsigned
2593CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2594 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002595 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002596 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002597 unsigned NestedLoopCount = 1;
2598 if (NestedLoopCountExpr) {
2599 // Found 'collapse' clause - calculate collapse number.
2600 llvm::APSInt Result;
2601 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2602 NestedLoopCount = Result.getLimitedValue();
2603 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002604 // This is helper routine for loop directives (e.g., 'for', 'simd',
2605 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002606 SmallVector<LoopIterationSpace, 4> IterSpaces;
2607 IterSpaces.resize(NestedLoopCount);
2608 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002609 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002610 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002611 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002612 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002613 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002614 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002615 // OpenMP [2.8.1, simd construct, Restrictions]
2616 // All loops associated with the construct must be perfectly nested; that
2617 // is, there must be no intervening code nor any OpenMP directive between
2618 // any two loops.
2619 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002620 }
2621
Alexander Musmana5f070a2014-10-01 06:03:56 +00002622 Built.clear(/* size */ NestedLoopCount);
2623
2624 if (SemaRef.CurContext->isDependentContext())
2625 return NestedLoopCount;
2626
2627 // An example of what is generated for the following code:
2628 //
2629 // #pragma omp simd collapse(2)
2630 // for (i = 0; i < NI; ++i)
2631 // for (j = J0; j < NJ; j+=2) {
2632 // <loop body>
2633 // }
2634 //
2635 // We generate the code below.
2636 // Note: the loop body may be outlined in CodeGen.
2637 // Note: some counters may be C++ classes, operator- is used to find number of
2638 // iterations and operator+= to calculate counter value.
2639 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2640 // or i64 is currently supported).
2641 //
2642 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2643 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2644 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2645 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2646 // // similar updates for vars in clauses (e.g. 'linear')
2647 // <loop body (using local i and j)>
2648 // }
2649 // i = NI; // assign final values of counters
2650 // j = NJ;
2651 //
2652
2653 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2654 // the iteration counts of the collapsed for loops.
2655 auto N0 = IterSpaces[0].NumIterations;
2656 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2657 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2658
2659 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2660 return NestedLoopCount;
2661
2662 auto &C = SemaRef.Context;
2663 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2664
2665 Scope *CurScope = DSA.getCurScope();
2666 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2667 auto N = IterSpaces[Cnt].NumIterations;
2668 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2669 if (LastIteration32.isUsable())
2670 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2671 LastIteration32.get(), N);
2672 if (LastIteration64.isUsable())
2673 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2674 LastIteration64.get(), N);
2675 }
2676
2677 // Choose either the 32-bit or 64-bit version.
2678 ExprResult LastIteration = LastIteration64;
2679 if (LastIteration32.isUsable() &&
2680 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2681 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2682 FitsInto(
2683 32 /* Bits */,
2684 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2685 LastIteration64.get(), SemaRef)))
2686 LastIteration = LastIteration32;
2687
2688 if (!LastIteration.isUsable())
2689 return 0;
2690
2691 // Save the number of iterations.
2692 ExprResult NumIterations = LastIteration;
2693 {
2694 LastIteration = SemaRef.BuildBinOp(
2695 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2696 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2697 if (!LastIteration.isUsable())
2698 return 0;
2699 }
2700
2701 // Calculate the last iteration number beforehand instead of doing this on
2702 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2703 llvm::APSInt Result;
2704 bool IsConstant =
2705 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2706 ExprResult CalcLastIteration;
2707 if (!IsConstant) {
2708 SourceLocation SaveLoc;
2709 VarDecl *SaveVar =
2710 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2711 ".omp.last.iteration");
2712 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2713 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2714 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2715 SaveRef.get(), LastIteration.get());
2716 LastIteration = SaveRef;
2717
2718 // Prepare SaveRef + 1.
2719 NumIterations = SemaRef.BuildBinOp(
2720 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2721 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2722 if (!NumIterations.isUsable())
2723 return 0;
2724 }
2725
2726 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2727
2728 // Precondition tests if there is at least one iteration (LastIteration > 0).
2729 ExprResult PreCond = SemaRef.BuildBinOp(
2730 CurScope, InitLoc, BO_GT, LastIteration.get(),
2731 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2732
Alexander Musmanc6388682014-12-15 07:07:06 +00002733 QualType VType = LastIteration.get()->getType();
2734 // Build variables passed into runtime, nesessary for worksharing directives.
2735 ExprResult LB, UB, IL, ST, EUB;
2736 if (isOpenMPWorksharingDirective(DKind)) {
2737 // Lower bound variable, initialized with zero.
2738 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2739 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2740 SemaRef.AddInitializerToDecl(
2741 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2742 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2743
2744 // Upper bound variable, initialized with last iteration number.
2745 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2746 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2747 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2748 /*DirectInit*/ false,
2749 /*TypeMayContainAuto*/ false);
2750
2751 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2752 // This will be used to implement clause 'lastprivate'.
2753 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2754 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2755 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2756 SemaRef.AddInitializerToDecl(
2757 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2758 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2759
2760 // Stride variable returned by runtime (we initialize it to 1 by default).
2761 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2762 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2763 SemaRef.AddInitializerToDecl(
2764 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2765 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2766
2767 // Build expression: UB = min(UB, LastIteration)
2768 // It is nesessary for CodeGen of directives with static scheduling.
2769 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2770 UB.get(), LastIteration.get());
2771 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2772 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2773 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2774 CondOp.get());
2775 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2776 }
2777
2778 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002779 ExprResult IV;
2780 ExprResult Init;
2781 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002782 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2783 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2784 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2785 ? LB.get()
2786 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2787 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2788 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002789 }
2790
Alexander Musmanc6388682014-12-15 07:07:06 +00002791 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002792 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002793 ExprResult Cond =
2794 isOpenMPWorksharingDirective(DKind)
2795 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2796 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2797 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002798 // Loop condition with 1 iteration separated (IV < LastIteration)
2799 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2800 IV.get(), LastIteration.get());
2801
2802 // Loop increment (IV = IV + 1)
2803 SourceLocation IncLoc;
2804 ExprResult Inc =
2805 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2806 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2807 if (!Inc.isUsable())
2808 return 0;
2809 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002810 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2811 if (!Inc.isUsable())
2812 return 0;
2813
2814 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2815 // Used for directives with static scheduling.
2816 ExprResult NextLB, NextUB;
2817 if (isOpenMPWorksharingDirective(DKind)) {
2818 // LB + ST
2819 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2820 if (!NextLB.isUsable())
2821 return 0;
2822 // LB = LB + ST
2823 NextLB =
2824 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2825 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2826 if (!NextLB.isUsable())
2827 return 0;
2828 // UB + ST
2829 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2830 if (!NextUB.isUsable())
2831 return 0;
2832 // UB = UB + ST
2833 NextUB =
2834 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2835 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2836 if (!NextUB.isUsable())
2837 return 0;
2838 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002839
2840 // Build updates and final values of the loop counters.
2841 bool HasErrors = false;
2842 Built.Counters.resize(NestedLoopCount);
2843 Built.Updates.resize(NestedLoopCount);
2844 Built.Finals.resize(NestedLoopCount);
2845 {
2846 ExprResult Div;
2847 // Go from inner nested loop to outer.
2848 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2849 LoopIterationSpace &IS = IterSpaces[Cnt];
2850 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2851 // Build: Iter = (IV / Div) % IS.NumIters
2852 // where Div is product of previous iterations' IS.NumIters.
2853 ExprResult Iter;
2854 if (Div.isUsable()) {
2855 Iter =
2856 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2857 } else {
2858 Iter = IV;
2859 assert((Cnt == (int)NestedLoopCount - 1) &&
2860 "unusable div expected on first iteration only");
2861 }
2862
2863 if (Cnt != 0 && Iter.isUsable())
2864 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2865 IS.NumIterations);
2866 if (!Iter.isUsable()) {
2867 HasErrors = true;
2868 break;
2869 }
2870
2871 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2872 ExprResult Update =
2873 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2874 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2875 if (!Update.isUsable()) {
2876 HasErrors = true;
2877 break;
2878 }
2879
2880 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2881 ExprResult Final = BuildCounterUpdate(
2882 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2883 IS.NumIterations, IS.CounterStep, IS.Subtract);
2884 if (!Final.isUsable()) {
2885 HasErrors = true;
2886 break;
2887 }
2888
2889 // Build Div for the next iteration: Div <- Div * IS.NumIters
2890 if (Cnt != 0) {
2891 if (Div.isUnset())
2892 Div = IS.NumIterations;
2893 else
2894 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2895 IS.NumIterations);
2896
2897 // Add parentheses (for debugging purposes only).
2898 if (Div.isUsable())
2899 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2900 if (!Div.isUsable()) {
2901 HasErrors = true;
2902 break;
2903 }
2904 }
2905 if (!Update.isUsable() || !Final.isUsable()) {
2906 HasErrors = true;
2907 break;
2908 }
2909 // Save results
2910 Built.Counters[Cnt] = IS.CounterVar;
2911 Built.Updates[Cnt] = Update.get();
2912 Built.Finals[Cnt] = Final.get();
2913 }
2914 }
2915
2916 if (HasErrors)
2917 return 0;
2918
2919 // Save results
2920 Built.IterationVarRef = IV.get();
2921 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00002922 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002923 Built.CalcLastIteration = CalcLastIteration.get();
2924 Built.PreCond = PreCond.get();
2925 Built.Cond = Cond.get();
2926 Built.SeparatedCond = SeparatedCond.get();
2927 Built.Init = Init.get();
2928 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00002929 Built.LB = LB.get();
2930 Built.UB = UB.get();
2931 Built.IL = IL.get();
2932 Built.ST = ST.get();
2933 Built.EUB = EUB.get();
2934 Built.NLB = NextLB.get();
2935 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002936
Alexey Bataevabfc0692014-06-25 06:52:00 +00002937 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002938}
2939
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002940static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002941 auto CollapseFilter = [](const OMPClause *C) -> bool {
2942 return C->getClauseKind() == OMPC_collapse;
2943 };
2944 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2945 Clauses, CollapseFilter);
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002946 if (I)
2947 return cast<OMPCollapseClause>(*I)->getNumForLoops();
2948 return nullptr;
2949}
2950
Alexey Bataev4acb8592014-07-07 13:01:15 +00002951StmtResult Sema::ActOnOpenMPSimdDirective(
2952 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2953 SourceLocation EndLoc,
2954 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002955 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002956 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002957 unsigned NestedLoopCount =
2958 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002959 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00002960 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002961 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002962
Alexander Musmana5f070a2014-10-01 06:03:56 +00002963 assert((CurContext->isDependentContext() || B.builtAll()) &&
2964 "omp simd loop exprs were not built");
2965
Alexander Musman3276a272015-03-21 10:12:56 +00002966 if (!CurContext->isDependentContext()) {
2967 // Finalize the clauses that need pre-built expressions for CodeGen.
2968 for (auto C : Clauses) {
2969 if (auto LC = dyn_cast<OMPLinearClause>(C))
2970 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
2971 B.NumIterations, *this, CurScope))
2972 return StmtError();
2973 }
2974 }
2975
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002976 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00002977 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2978 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002979}
2980
Alexey Bataev4acb8592014-07-07 13:01:15 +00002981StmtResult Sema::ActOnOpenMPForDirective(
2982 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2983 SourceLocation EndLoc,
2984 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002985 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002986 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002987 unsigned NestedLoopCount =
2988 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002989 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00002990 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00002991 return StmtError();
2992
Alexander Musmana5f070a2014-10-01 06:03:56 +00002993 assert((CurContext->isDependentContext() || B.builtAll()) &&
2994 "omp for loop exprs were not built");
2995
Alexey Bataevf29276e2014-06-18 04:14:57 +00002996 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00002997 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
2998 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002999}
3000
Alexander Musmanf82886e2014-09-18 05:12:34 +00003001StmtResult Sema::ActOnOpenMPForSimdDirective(
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;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003006 // In presence of clause 'collapse', it will define the nested loops number.
3007 unsigned NestedLoopCount =
3008 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003009 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003010 if (NestedLoopCount == 0)
3011 return StmtError();
3012
Alexander Musmanc6388682014-12-15 07:07:06 +00003013 assert((CurContext->isDependentContext() || B.builtAll()) &&
3014 "omp for simd loop exprs were not built");
3015
Alexander Musmanf82886e2014-09-18 05:12:34 +00003016 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003017 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3018 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003019}
3020
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003021StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3022 Stmt *AStmt,
3023 SourceLocation StartLoc,
3024 SourceLocation EndLoc) {
3025 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3026 auto BaseStmt = AStmt;
3027 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3028 BaseStmt = CS->getCapturedStmt();
3029 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3030 auto S = C->children();
3031 if (!S)
3032 return StmtError();
3033 // All associated statements must be '#pragma omp section' except for
3034 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003035 for (++S; S; ++S) {
3036 auto SectionStmt = *S;
3037 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3038 if (SectionStmt)
3039 Diag(SectionStmt->getLocStart(),
3040 diag::err_omp_sections_substmt_not_section);
3041 return StmtError();
3042 }
3043 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003044 } else {
3045 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3046 return StmtError();
3047 }
3048
3049 getCurFunction()->setHasBranchProtectedScope();
3050
3051 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3052 AStmt);
3053}
3054
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003055StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3056 SourceLocation StartLoc,
3057 SourceLocation EndLoc) {
3058 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3059
3060 getCurFunction()->setHasBranchProtectedScope();
3061
3062 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3063}
3064
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003065StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3066 Stmt *AStmt,
3067 SourceLocation StartLoc,
3068 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003069 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3070
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003071 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003072
Alexey Bataev3255bf32015-01-19 05:20:46 +00003073 // OpenMP [2.7.3, single Construct, Restrictions]
3074 // The copyprivate clause must not be used with the nowait clause.
3075 OMPClause *Nowait = nullptr;
3076 OMPClause *Copyprivate = nullptr;
3077 for (auto *Clause : Clauses) {
3078 if (Clause->getClauseKind() == OMPC_nowait)
3079 Nowait = Clause;
3080 else if (Clause->getClauseKind() == OMPC_copyprivate)
3081 Copyprivate = Clause;
3082 if (Copyprivate && Nowait) {
3083 Diag(Copyprivate->getLocStart(),
3084 diag::err_omp_single_copyprivate_with_nowait);
3085 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3086 return StmtError();
3087 }
3088 }
3089
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003090 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3091}
3092
Alexander Musman80c22892014-07-17 08:54:58 +00003093StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3094 SourceLocation StartLoc,
3095 SourceLocation EndLoc) {
3096 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3097
3098 getCurFunction()->setHasBranchProtectedScope();
3099
3100 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3101}
3102
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003103StmtResult
3104Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3105 Stmt *AStmt, SourceLocation StartLoc,
3106 SourceLocation EndLoc) {
3107 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3108
3109 getCurFunction()->setHasBranchProtectedScope();
3110
3111 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3112 AStmt);
3113}
3114
Alexey Bataev4acb8592014-07-07 13:01:15 +00003115StmtResult Sema::ActOnOpenMPParallelForDirective(
3116 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3117 SourceLocation EndLoc,
3118 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3119 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3120 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3121 // 1.2.2 OpenMP Language Terminology
3122 // Structured block - An executable statement with a single entry at the
3123 // top and a single exit at the bottom.
3124 // The point of exit cannot be a branch out of the structured block.
3125 // longjmp() and throw() must not violate the entry/exit criteria.
3126 CS->getCapturedDecl()->setNothrow();
3127
Alexander Musmanc6388682014-12-15 07:07:06 +00003128 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003129 // In presence of clause 'collapse', it will define the nested loops number.
3130 unsigned NestedLoopCount =
3131 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003132 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003133 if (NestedLoopCount == 0)
3134 return StmtError();
3135
Alexander Musmana5f070a2014-10-01 06:03:56 +00003136 assert((CurContext->isDependentContext() || B.builtAll()) &&
3137 "omp parallel for loop exprs were not built");
3138
Alexey Bataev4acb8592014-07-07 13:01:15 +00003139 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003140 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3141 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003142}
3143
Alexander Musmane4e893b2014-09-23 09:33:00 +00003144StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3145 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3146 SourceLocation EndLoc,
3147 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3148 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3149 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3150 // 1.2.2 OpenMP Language Terminology
3151 // Structured block - An executable statement with a single entry at the
3152 // top and a single exit at the bottom.
3153 // The point of exit cannot be a branch out of the structured block.
3154 // longjmp() and throw() must not violate the entry/exit criteria.
3155 CS->getCapturedDecl()->setNothrow();
3156
Alexander Musmanc6388682014-12-15 07:07:06 +00003157 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003158 // In presence of clause 'collapse', it will define the nested loops number.
3159 unsigned NestedLoopCount =
3160 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003161 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003162 if (NestedLoopCount == 0)
3163 return StmtError();
3164
3165 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003166 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003167 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003168}
3169
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003170StmtResult
3171Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3172 Stmt *AStmt, SourceLocation StartLoc,
3173 SourceLocation EndLoc) {
3174 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3175 auto BaseStmt = AStmt;
3176 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3177 BaseStmt = CS->getCapturedStmt();
3178 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3179 auto S = C->children();
3180 if (!S)
3181 return StmtError();
3182 // All associated statements must be '#pragma omp section' except for
3183 // the first one.
3184 for (++S; S; ++S) {
3185 auto SectionStmt = *S;
3186 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3187 if (SectionStmt)
3188 Diag(SectionStmt->getLocStart(),
3189 diag::err_omp_parallel_sections_substmt_not_section);
3190 return StmtError();
3191 }
3192 }
3193 } else {
3194 Diag(AStmt->getLocStart(),
3195 diag::err_omp_parallel_sections_not_compound_stmt);
3196 return StmtError();
3197 }
3198
3199 getCurFunction()->setHasBranchProtectedScope();
3200
3201 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3202 Clauses, AStmt);
3203}
3204
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003205StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3206 Stmt *AStmt, SourceLocation StartLoc,
3207 SourceLocation EndLoc) {
3208 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3209 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3210 // 1.2.2 OpenMP Language Terminology
3211 // Structured block - An executable statement with a single entry at the
3212 // top and a single exit at the bottom.
3213 // The point of exit cannot be a branch out of the structured block.
3214 // longjmp() and throw() must not violate the entry/exit criteria.
3215 CS->getCapturedDecl()->setNothrow();
3216
3217 getCurFunction()->setHasBranchProtectedScope();
3218
3219 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3220}
3221
Alexey Bataev68446b72014-07-18 07:47:19 +00003222StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3223 SourceLocation EndLoc) {
3224 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3225}
3226
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003227StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3228 SourceLocation EndLoc) {
3229 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3230}
3231
Alexey Bataev2df347a2014-07-18 10:17:07 +00003232StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3233 SourceLocation EndLoc) {
3234 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3235}
3236
Alexey Bataev6125da92014-07-21 11:26:11 +00003237StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3238 SourceLocation StartLoc,
3239 SourceLocation EndLoc) {
3240 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3241 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3242}
3243
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003244StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3245 SourceLocation StartLoc,
3246 SourceLocation EndLoc) {
3247 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3248
3249 getCurFunction()->setHasBranchProtectedScope();
3250
3251 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3252}
3253
Alexey Bataev1d160b12015-03-13 12:27:31 +00003254namespace {
3255/// \brief Helper class for checking expression in 'omp atomic [update]'
3256/// construct.
3257class OpenMPAtomicUpdateChecker {
3258 /// \brief Error results for atomic update expressions.
3259 enum ExprAnalysisErrorCode {
3260 /// \brief A statement is not an expression statement.
3261 NotAnExpression,
3262 /// \brief Expression is not builtin binary or unary operation.
3263 NotABinaryOrUnaryExpression,
3264 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3265 NotAnUnaryIncDecExpression,
3266 /// \brief An expression is not of scalar type.
3267 NotAScalarType,
3268 /// \brief A binary operation is not an assignment operation.
3269 NotAnAssignmentOp,
3270 /// \brief RHS part of the binary operation is not a binary expression.
3271 NotABinaryExpression,
3272 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3273 /// expression.
3274 NotABinaryOperator,
3275 /// \brief RHS binary operation does not have reference to the updated LHS
3276 /// part.
3277 NotAnUpdateExpression,
3278 /// \brief No errors is found.
3279 NoError
3280 };
3281 /// \brief Reference to Sema.
3282 Sema &SemaRef;
3283 /// \brief A location for note diagnostics (when error is found).
3284 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003285 /// \brief 'x' lvalue part of the source atomic expression.
3286 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003287 /// \brief 'expr' rvalue part of the source atomic expression.
3288 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003289 /// \brief Helper expression of the form
3290 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3291 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3292 Expr *UpdateExpr;
3293 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3294 /// important for non-associative operations.
3295 bool IsXLHSInRHSPart;
3296 BinaryOperatorKind Op;
3297 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003298 /// \brief true if the source expression is a postfix unary operation, false
3299 /// if it is a prefix unary operation.
3300 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003301
3302public:
3303 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003304 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003305 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003306 /// \brief Check specified statement that it is suitable for 'atomic update'
3307 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003308 /// expression. If DiagId and NoteId == 0, then only check is performed
3309 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003310 /// \param DiagId Diagnostic which should be emitted if error is found.
3311 /// \param NoteId Diagnostic note for the main error message.
3312 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003313 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003314 /// \brief Return the 'x' lvalue part of the source atomic expression.
3315 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003316 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3317 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003318 /// \brief Return the update expression used in calculation of the updated
3319 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3320 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3321 Expr *getUpdateExpr() const { return UpdateExpr; }
3322 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3323 /// false otherwise.
3324 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3325
Alexey Bataevb78ca832015-04-01 03:33:17 +00003326 /// \brief true if the source expression is a postfix unary operation, false
3327 /// if it is a prefix unary operation.
3328 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3329
Alexey Bataev1d160b12015-03-13 12:27:31 +00003330private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003331 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3332 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003333};
3334} // namespace
3335
3336bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3337 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3338 ExprAnalysisErrorCode ErrorFound = NoError;
3339 SourceLocation ErrorLoc, NoteLoc;
3340 SourceRange ErrorRange, NoteRange;
3341 // Allowed constructs are:
3342 // x = x binop expr;
3343 // x = expr binop x;
3344 if (AtomicBinOp->getOpcode() == BO_Assign) {
3345 X = AtomicBinOp->getLHS();
3346 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3347 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3348 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3349 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3350 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003351 Op = AtomicInnerBinOp->getOpcode();
3352 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003353 auto *LHS = AtomicInnerBinOp->getLHS();
3354 auto *RHS = AtomicInnerBinOp->getRHS();
3355 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3356 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3357 /*Canonical=*/true);
3358 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3359 /*Canonical=*/true);
3360 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3361 /*Canonical=*/true);
3362 if (XId == LHSId) {
3363 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003364 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003365 } else if (XId == RHSId) {
3366 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003367 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003368 } else {
3369 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3370 ErrorRange = AtomicInnerBinOp->getSourceRange();
3371 NoteLoc = X->getExprLoc();
3372 NoteRange = X->getSourceRange();
3373 ErrorFound = NotAnUpdateExpression;
3374 }
3375 } else {
3376 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3377 ErrorRange = AtomicInnerBinOp->getSourceRange();
3378 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3379 NoteRange = SourceRange(NoteLoc, NoteLoc);
3380 ErrorFound = NotABinaryOperator;
3381 }
3382 } else {
3383 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3384 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3385 ErrorFound = NotABinaryExpression;
3386 }
3387 } else {
3388 ErrorLoc = AtomicBinOp->getExprLoc();
3389 ErrorRange = AtomicBinOp->getSourceRange();
3390 NoteLoc = AtomicBinOp->getOperatorLoc();
3391 NoteRange = SourceRange(NoteLoc, NoteLoc);
3392 ErrorFound = NotAnAssignmentOp;
3393 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003394 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003395 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3396 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3397 return true;
3398 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003399 E = X = UpdateExpr = nullptr;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003400 return false;
3401}
3402
3403bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3404 unsigned NoteId) {
3405 ExprAnalysisErrorCode ErrorFound = NoError;
3406 SourceLocation ErrorLoc, NoteLoc;
3407 SourceRange ErrorRange, NoteRange;
3408 // Allowed constructs are:
3409 // x++;
3410 // x--;
3411 // ++x;
3412 // --x;
3413 // x binop= expr;
3414 // x = x binop expr;
3415 // x = expr binop x;
3416 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3417 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3418 if (AtomicBody->getType()->isScalarType() ||
3419 AtomicBody->isInstantiationDependent()) {
3420 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3421 AtomicBody->IgnoreParenImpCasts())) {
3422 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003423 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003424 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003425 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003426 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003427 X = AtomicCompAssignOp->getLHS();
3428 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003429 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3430 AtomicBody->IgnoreParenImpCasts())) {
3431 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003432 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3433 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003434 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003435 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3436 // Check for Unary Operation
3437 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003438 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003439 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3440 OpLoc = AtomicUnaryOp->getOperatorLoc();
3441 X = AtomicUnaryOp->getSubExpr();
3442 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3443 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003444 } else {
3445 ErrorFound = NotAnUnaryIncDecExpression;
3446 ErrorLoc = AtomicUnaryOp->getExprLoc();
3447 ErrorRange = AtomicUnaryOp->getSourceRange();
3448 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3449 NoteRange = SourceRange(NoteLoc, NoteLoc);
3450 }
3451 } else {
3452 ErrorFound = NotABinaryOrUnaryExpression;
3453 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3454 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3455 }
3456 } else {
3457 ErrorFound = NotAScalarType;
3458 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3459 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3460 }
3461 } else {
3462 ErrorFound = NotAnExpression;
3463 NoteLoc = ErrorLoc = S->getLocStart();
3464 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3465 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003466 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003467 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3468 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3469 return true;
3470 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003471 E = X = UpdateExpr = nullptr;
3472 if (E && X) {
3473 // Build an update expression of form 'OpaqueValueExpr(x) binop
3474 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3475 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3476 auto *OVEX = new (SemaRef.getASTContext())
3477 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3478 auto *OVEExpr = new (SemaRef.getASTContext())
3479 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3480 auto Update =
3481 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3482 IsXLHSInRHSPart ? OVEExpr : OVEX);
3483 if (Update.isInvalid())
3484 return true;
3485 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3486 Sema::AA_Casting);
3487 if (Update.isInvalid())
3488 return true;
3489 UpdateExpr = Update.get();
3490 }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003491 return false;
3492}
3493
Alexey Bataev0162e452014-07-22 10:10:35 +00003494StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3495 Stmt *AStmt,
3496 SourceLocation StartLoc,
3497 SourceLocation EndLoc) {
3498 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003499 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003500 // 1.2.2 OpenMP Language Terminology
3501 // Structured block - An executable statement with a single entry at the
3502 // top and a single exit at the bottom.
3503 // The point of exit cannot be a branch out of the structured block.
3504 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003505 OpenMPClauseKind AtomicKind = OMPC_unknown;
3506 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003507 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003508 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003509 C->getClauseKind() == OMPC_update ||
3510 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003511 if (AtomicKind != OMPC_unknown) {
3512 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3513 << SourceRange(C->getLocStart(), C->getLocEnd());
3514 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3515 << getOpenMPClauseName(AtomicKind);
3516 } else {
3517 AtomicKind = C->getClauseKind();
3518 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003519 }
3520 }
3521 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003522
Alexey Bataev459dec02014-07-24 06:46:57 +00003523 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003524 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3525 Body = EWC->getSubExpr();
3526
Alexey Bataev62cec442014-11-18 10:14:22 +00003527 Expr *X = nullptr;
3528 Expr *V = nullptr;
3529 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003530 Expr *UE = nullptr;
3531 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003532 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003533 // OpenMP [2.12.6, atomic Construct]
3534 // In the next expressions:
3535 // * x and v (as applicable) are both l-value expressions with scalar type.
3536 // * During the execution of an atomic region, multiple syntactic
3537 // occurrences of x must designate the same storage location.
3538 // * Neither of v and expr (as applicable) may access the storage location
3539 // designated by x.
3540 // * Neither of x and expr (as applicable) may access the storage location
3541 // designated by v.
3542 // * expr is an expression with scalar type.
3543 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3544 // * binop, binop=, ++, and -- are not overloaded operators.
3545 // * The expression x binop expr must be numerically equivalent to x binop
3546 // (expr). This requirement is satisfied if the operators in expr have
3547 // precedence greater than binop, or by using parentheses around expr or
3548 // subexpressions of expr.
3549 // * The expression expr binop x must be numerically equivalent to (expr)
3550 // binop x. This requirement is satisfied if the operators in expr have
3551 // precedence equal to or greater than binop, or by using parentheses around
3552 // expr or subexpressions of expr.
3553 // * For forms that allow multiple occurrences of x, the number of times
3554 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003555 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003556 enum {
3557 NotAnExpression,
3558 NotAnAssignmentOp,
3559 NotAScalarType,
3560 NotAnLValue,
3561 NoError
3562 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003563 SourceLocation ErrorLoc, NoteLoc;
3564 SourceRange ErrorRange, NoteRange;
3565 // If clause is read:
3566 // v = x;
3567 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3568 auto AtomicBinOp =
3569 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3570 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3571 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3572 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3573 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3574 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3575 if (!X->isLValue() || !V->isLValue()) {
3576 auto NotLValueExpr = X->isLValue() ? V : X;
3577 ErrorFound = NotAnLValue;
3578 ErrorLoc = AtomicBinOp->getExprLoc();
3579 ErrorRange = AtomicBinOp->getSourceRange();
3580 NoteLoc = NotLValueExpr->getExprLoc();
3581 NoteRange = NotLValueExpr->getSourceRange();
3582 }
3583 } else if (!X->isInstantiationDependent() ||
3584 !V->isInstantiationDependent()) {
3585 auto NotScalarExpr =
3586 (X->isInstantiationDependent() || X->getType()->isScalarType())
3587 ? V
3588 : X;
3589 ErrorFound = NotAScalarType;
3590 ErrorLoc = AtomicBinOp->getExprLoc();
3591 ErrorRange = AtomicBinOp->getSourceRange();
3592 NoteLoc = NotScalarExpr->getExprLoc();
3593 NoteRange = NotScalarExpr->getSourceRange();
3594 }
3595 } else {
3596 ErrorFound = NotAnAssignmentOp;
3597 ErrorLoc = AtomicBody->getExprLoc();
3598 ErrorRange = AtomicBody->getSourceRange();
3599 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3600 : AtomicBody->getExprLoc();
3601 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3602 : AtomicBody->getSourceRange();
3603 }
3604 } else {
3605 ErrorFound = NotAnExpression;
3606 NoteLoc = ErrorLoc = Body->getLocStart();
3607 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003608 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003609 if (ErrorFound != NoError) {
3610 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3611 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003612 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3613 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003614 return StmtError();
3615 } else if (CurContext->isDependentContext())
3616 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003617 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003618 enum {
3619 NotAnExpression,
3620 NotAnAssignmentOp,
3621 NotAScalarType,
3622 NotAnLValue,
3623 NoError
3624 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003625 SourceLocation ErrorLoc, NoteLoc;
3626 SourceRange ErrorRange, NoteRange;
3627 // If clause is write:
3628 // x = expr;
3629 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3630 auto AtomicBinOp =
3631 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3632 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003633 X = AtomicBinOp->getLHS();
3634 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003635 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3636 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3637 if (!X->isLValue()) {
3638 ErrorFound = NotAnLValue;
3639 ErrorLoc = AtomicBinOp->getExprLoc();
3640 ErrorRange = AtomicBinOp->getSourceRange();
3641 NoteLoc = X->getExprLoc();
3642 NoteRange = X->getSourceRange();
3643 }
3644 } else if (!X->isInstantiationDependent() ||
3645 !E->isInstantiationDependent()) {
3646 auto NotScalarExpr =
3647 (X->isInstantiationDependent() || X->getType()->isScalarType())
3648 ? E
3649 : X;
3650 ErrorFound = NotAScalarType;
3651 ErrorLoc = AtomicBinOp->getExprLoc();
3652 ErrorRange = AtomicBinOp->getSourceRange();
3653 NoteLoc = NotScalarExpr->getExprLoc();
3654 NoteRange = NotScalarExpr->getSourceRange();
3655 }
3656 } else {
3657 ErrorFound = NotAnAssignmentOp;
3658 ErrorLoc = AtomicBody->getExprLoc();
3659 ErrorRange = AtomicBody->getSourceRange();
3660 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3661 : AtomicBody->getExprLoc();
3662 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3663 : AtomicBody->getSourceRange();
3664 }
3665 } else {
3666 ErrorFound = NotAnExpression;
3667 NoteLoc = ErrorLoc = Body->getLocStart();
3668 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003669 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003670 if (ErrorFound != NoError) {
3671 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3672 << ErrorRange;
3673 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3674 << NoteRange;
3675 return StmtError();
3676 } else if (CurContext->isDependentContext())
3677 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003678 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003679 // If clause is update:
3680 // x++;
3681 // x--;
3682 // ++x;
3683 // --x;
3684 // x binop= expr;
3685 // x = x binop expr;
3686 // x = expr binop x;
3687 OpenMPAtomicUpdateChecker Checker(*this);
3688 if (Checker.checkStatement(
3689 Body, (AtomicKind == OMPC_update)
3690 ? diag::err_omp_atomic_update_not_expression_statement
3691 : diag::err_omp_atomic_not_expression_statement,
3692 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003693 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003694 if (!CurContext->isDependentContext()) {
3695 E = Checker.getExpr();
3696 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003697 UE = Checker.getUpdateExpr();
3698 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003699 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003700 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003701 enum {
3702 NotAnAssignmentOp,
3703 NotACompoundStatement,
3704 NotTwoSubstatements,
3705 NotASpecificExpression,
3706 NoError
3707 } ErrorFound = NoError;
3708 SourceLocation ErrorLoc, NoteLoc;
3709 SourceRange ErrorRange, NoteRange;
3710 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3711 // If clause is a capture:
3712 // v = x++;
3713 // v = x--;
3714 // v = ++x;
3715 // v = --x;
3716 // v = x binop= expr;
3717 // v = x = x binop expr;
3718 // v = x = expr binop x;
3719 auto *AtomicBinOp =
3720 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3721 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3722 V = AtomicBinOp->getLHS();
3723 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3724 OpenMPAtomicUpdateChecker Checker(*this);
3725 if (Checker.checkStatement(
3726 Body, diag::err_omp_atomic_capture_not_expression_statement,
3727 diag::note_omp_atomic_update))
3728 return StmtError();
3729 E = Checker.getExpr();
3730 X = Checker.getX();
3731 UE = Checker.getUpdateExpr();
3732 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3733 IsPostfixUpdate = Checker.isPostfixUpdate();
3734 } else {
3735 ErrorLoc = AtomicBody->getExprLoc();
3736 ErrorRange = AtomicBody->getSourceRange();
3737 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3738 : AtomicBody->getExprLoc();
3739 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3740 : AtomicBody->getSourceRange();
3741 ErrorFound = NotAnAssignmentOp;
3742 }
3743 if (ErrorFound != NoError) {
3744 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3745 << ErrorRange;
3746 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3747 return StmtError();
3748 } else if (CurContext->isDependentContext()) {
3749 UE = V = E = X = nullptr;
3750 }
3751 } else {
3752 // If clause is a capture:
3753 // { v = x; x = expr; }
3754 // { v = x; x++; }
3755 // { v = x; x--; }
3756 // { v = x; ++x; }
3757 // { v = x; --x; }
3758 // { v = x; x binop= expr; }
3759 // { v = x; x = x binop expr; }
3760 // { v = x; x = expr binop x; }
3761 // { x++; v = x; }
3762 // { x--; v = x; }
3763 // { ++x; v = x; }
3764 // { --x; v = x; }
3765 // { x binop= expr; v = x; }
3766 // { x = x binop expr; v = x; }
3767 // { x = expr binop x; v = x; }
3768 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3769 // Check that this is { expr1; expr2; }
3770 if (CS->size() == 2) {
3771 auto *First = CS->body_front();
3772 auto *Second = CS->body_back();
3773 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3774 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3775 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3776 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3777 // Need to find what subexpression is 'v' and what is 'x'.
3778 OpenMPAtomicUpdateChecker Checker(*this);
3779 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3780 BinaryOperator *BinOp = nullptr;
3781 if (IsUpdateExprFound) {
3782 BinOp = dyn_cast<BinaryOperator>(First);
3783 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3784 }
3785 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3786 // { v = x; x++; }
3787 // { v = x; x--; }
3788 // { v = x; ++x; }
3789 // { v = x; --x; }
3790 // { v = x; x binop= expr; }
3791 // { v = x; x = x binop expr; }
3792 // { v = x; x = expr binop x; }
3793 // Check that the first expression has form v = x.
3794 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3795 llvm::FoldingSetNodeID XId, PossibleXId;
3796 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3797 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3798 IsUpdateExprFound = XId == PossibleXId;
3799 if (IsUpdateExprFound) {
3800 V = BinOp->getLHS();
3801 X = Checker.getX();
3802 E = Checker.getExpr();
3803 UE = Checker.getUpdateExpr();
3804 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3805 IsPostfixUpdate = Checker.isPostfixUpdate();
3806 }
3807 }
3808 if (!IsUpdateExprFound) {
3809 IsUpdateExprFound = !Checker.checkStatement(First);
3810 BinOp = nullptr;
3811 if (IsUpdateExprFound) {
3812 BinOp = dyn_cast<BinaryOperator>(Second);
3813 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3814 }
3815 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3816 // { x++; v = x; }
3817 // { x--; v = x; }
3818 // { ++x; v = x; }
3819 // { --x; v = x; }
3820 // { x binop= expr; v = x; }
3821 // { x = x binop expr; v = x; }
3822 // { x = expr binop x; v = x; }
3823 // Check that the second expression has form v = x.
3824 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3825 llvm::FoldingSetNodeID XId, PossibleXId;
3826 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3827 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3828 IsUpdateExprFound = XId == PossibleXId;
3829 if (IsUpdateExprFound) {
3830 V = BinOp->getLHS();
3831 X = Checker.getX();
3832 E = Checker.getExpr();
3833 UE = Checker.getUpdateExpr();
3834 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3835 IsPostfixUpdate = Checker.isPostfixUpdate();
3836 }
3837 }
3838 }
3839 if (!IsUpdateExprFound) {
3840 // { v = x; x = expr; }
3841 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3842 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3843 ErrorFound = NotAnAssignmentOp;
3844 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3845 : First->getLocStart();
3846 NoteRange = ErrorRange = FirstBinOp
3847 ? FirstBinOp->getSourceRange()
3848 : SourceRange(ErrorLoc, ErrorLoc);
3849 } else {
3850 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3851 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3852 ErrorFound = NotAnAssignmentOp;
3853 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3854 : Second->getLocStart();
3855 NoteRange = ErrorRange = SecondBinOp
3856 ? SecondBinOp->getSourceRange()
3857 : SourceRange(ErrorLoc, ErrorLoc);
3858 } else {
3859 auto *PossibleXRHSInFirst =
3860 FirstBinOp->getRHS()->IgnoreParenImpCasts();
3861 auto *PossibleXLHSInSecond =
3862 SecondBinOp->getLHS()->IgnoreParenImpCasts();
3863 llvm::FoldingSetNodeID X1Id, X2Id;
3864 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
3865 PossibleXLHSInSecond->Profile(X2Id, Context,
3866 /*Canonical=*/true);
3867 IsUpdateExprFound = X1Id == X2Id;
3868 if (IsUpdateExprFound) {
3869 V = FirstBinOp->getLHS();
3870 X = SecondBinOp->getLHS();
3871 E = SecondBinOp->getRHS();
3872 UE = nullptr;
3873 IsXLHSInRHSPart = false;
3874 IsPostfixUpdate = true;
3875 } else {
3876 ErrorFound = NotASpecificExpression;
3877 ErrorLoc = FirstBinOp->getExprLoc();
3878 ErrorRange = FirstBinOp->getSourceRange();
3879 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
3880 NoteRange = SecondBinOp->getRHS()->getSourceRange();
3881 }
3882 }
3883 }
3884 }
3885 } else {
3886 NoteLoc = ErrorLoc = Body->getLocStart();
3887 NoteRange = ErrorRange =
3888 SourceRange(Body->getLocStart(), Body->getLocStart());
3889 ErrorFound = NotTwoSubstatements;
3890 }
3891 } else {
3892 NoteLoc = ErrorLoc = Body->getLocStart();
3893 NoteRange = ErrorRange =
3894 SourceRange(Body->getLocStart(), Body->getLocStart());
3895 ErrorFound = NotACompoundStatement;
3896 }
3897 if (ErrorFound != NoError) {
3898 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
3899 << ErrorRange;
3900 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3901 return StmtError();
3902 } else if (CurContext->isDependentContext()) {
3903 UE = V = E = X = nullptr;
3904 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003905 }
Alexey Bataevdea47612014-07-23 07:46:59 +00003906 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003907
3908 getCurFunction()->setHasBranchProtectedScope();
3909
Alexey Bataev62cec442014-11-18 10:14:22 +00003910 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00003911 X, V, E, UE, IsXLHSInRHSPart,
3912 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00003913}
3914
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003915StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3916 Stmt *AStmt,
3917 SourceLocation StartLoc,
3918 SourceLocation EndLoc) {
3919 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3920
Alexey Bataev13314bf2014-10-09 04:18:56 +00003921 // OpenMP [2.16, Nesting of Regions]
3922 // If specified, a teams construct must be contained within a target
3923 // construct. That target construct must contain no statements or directives
3924 // outside of the teams construct.
3925 if (DSAStack->hasInnerTeamsRegion()) {
3926 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3927 bool OMPTeamsFound = true;
3928 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3929 auto I = CS->body_begin();
3930 while (I != CS->body_end()) {
3931 auto OED = dyn_cast<OMPExecutableDirective>(*I);
3932 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3933 OMPTeamsFound = false;
3934 break;
3935 }
3936 ++I;
3937 }
3938 assert(I != CS->body_end() && "Not found statement");
3939 S = *I;
3940 }
3941 if (!OMPTeamsFound) {
3942 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
3943 Diag(DSAStack->getInnerTeamsRegionLoc(),
3944 diag::note_omp_nested_teams_construct_here);
3945 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
3946 << isa<OMPExecutableDirective>(S);
3947 return StmtError();
3948 }
3949 }
3950
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003951 getCurFunction()->setHasBranchProtectedScope();
3952
3953 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3954}
3955
Alexey Bataev13314bf2014-10-09 04:18:56 +00003956StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
3957 Stmt *AStmt, SourceLocation StartLoc,
3958 SourceLocation EndLoc) {
3959 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3960 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3961 // 1.2.2 OpenMP Language Terminology
3962 // Structured block - An executable statement with a single entry at the
3963 // top and a single exit at the bottom.
3964 // The point of exit cannot be a branch out of the structured block.
3965 // longjmp() and throw() must not violate the entry/exit criteria.
3966 CS->getCapturedDecl()->setNothrow();
3967
3968 getCurFunction()->setHasBranchProtectedScope();
3969
3970 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3971}
3972
Alexey Bataeved09d242014-05-28 05:53:51 +00003973OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003974 SourceLocation StartLoc,
3975 SourceLocation LParenLoc,
3976 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00003977 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003978 switch (Kind) {
3979 case OMPC_if:
3980 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
3981 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00003982 case OMPC_final:
3983 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
3984 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00003985 case OMPC_num_threads:
3986 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
3987 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00003988 case OMPC_safelen:
3989 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
3990 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00003991 case OMPC_collapse:
3992 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
3993 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003994 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00003995 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00003996 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00003997 case OMPC_private:
3998 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00003999 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004000 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004001 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004002 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004003 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004004 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004005 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004006 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004007 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004008 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004009 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004010 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004011 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004012 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004013 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004014 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004015 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004016 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004017 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004018 llvm_unreachable("Clause is not allowed.");
4019 }
4020 return Res;
4021}
4022
Alexey Bataeved09d242014-05-28 05:53:51 +00004023OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004024 SourceLocation LParenLoc,
4025 SourceLocation EndLoc) {
4026 Expr *ValExpr = Condition;
4027 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4028 !Condition->isInstantiationDependent() &&
4029 !Condition->containsUnexpandedParameterPack()) {
4030 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004031 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004032 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004033 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004034
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004035 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004036 }
4037
4038 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4039}
4040
Alexey Bataev3778b602014-07-17 07:32:53 +00004041OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4042 SourceLocation StartLoc,
4043 SourceLocation LParenLoc,
4044 SourceLocation EndLoc) {
4045 Expr *ValExpr = Condition;
4046 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4047 !Condition->isInstantiationDependent() &&
4048 !Condition->containsUnexpandedParameterPack()) {
4049 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4050 Condition->getExprLoc(), Condition);
4051 if (Val.isInvalid())
4052 return nullptr;
4053
4054 ValExpr = Val.get();
4055 }
4056
4057 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4058}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004059ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4060 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004061 if (!Op)
4062 return ExprError();
4063
4064 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4065 public:
4066 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004067 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004068 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4069 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004070 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4071 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004072 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4073 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004074 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4075 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004076 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4077 QualType T,
4078 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004079 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4080 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004081 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4082 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004083 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004084 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004085 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004086 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4087 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004088 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4089 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004090 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4091 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004092 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004093 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004094 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004095 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4096 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004097 llvm_unreachable("conversion functions are permitted");
4098 }
4099 } ConvertDiagnoser;
4100 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4101}
4102
4103OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4104 SourceLocation StartLoc,
4105 SourceLocation LParenLoc,
4106 SourceLocation EndLoc) {
4107 Expr *ValExpr = NumThreads;
4108 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004109 !NumThreads->containsUnexpandedParameterPack()) {
4110 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4111 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004112 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004113 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004114 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004115
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004116 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004117
4118 // OpenMP [2.5, Restrictions]
4119 // The num_threads expression must evaluate to a positive integer value.
4120 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004121 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4122 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004123 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4124 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004125 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004126 }
4127 }
4128
Alexey Bataeved09d242014-05-28 05:53:51 +00004129 return new (Context)
4130 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004131}
4132
Alexey Bataev62c87d22014-03-21 04:51:18 +00004133ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4134 OpenMPClauseKind CKind) {
4135 if (!E)
4136 return ExprError();
4137 if (E->isValueDependent() || E->isTypeDependent() ||
4138 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004139 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004140 llvm::APSInt Result;
4141 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4142 if (ICE.isInvalid())
4143 return ExprError();
4144 if (!Result.isStrictlyPositive()) {
4145 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4146 << getOpenMPClauseName(CKind) << E->getSourceRange();
4147 return ExprError();
4148 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004149 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4150 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4151 << E->getSourceRange();
4152 return ExprError();
4153 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004154 return ICE;
4155}
4156
4157OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4158 SourceLocation LParenLoc,
4159 SourceLocation EndLoc) {
4160 // OpenMP [2.8.1, simd construct, Description]
4161 // The parameter of the safelen clause must be a constant
4162 // positive integer expression.
4163 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4164 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004165 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004166 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004167 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004168}
4169
Alexander Musman64d33f12014-06-04 07:53:32 +00004170OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4171 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004172 SourceLocation LParenLoc,
4173 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004174 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004175 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004176 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004177 // The parameter of the collapse clause must be a constant
4178 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004179 ExprResult NumForLoopsResult =
4180 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4181 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004182 return nullptr;
4183 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004184 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004185}
4186
Alexey Bataeved09d242014-05-28 05:53:51 +00004187OMPClause *Sema::ActOnOpenMPSimpleClause(
4188 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4189 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004190 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004191 switch (Kind) {
4192 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004193 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004194 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4195 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004196 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004197 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004198 Res = ActOnOpenMPProcBindClause(
4199 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4200 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004201 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004202 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004203 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004204 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004205 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004206 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004207 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004208 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004209 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004210 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004211 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004212 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004213 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004214 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004215 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004216 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004217 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004218 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004219 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004220 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004221 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004222 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004223 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004224 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004225 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004226 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004227 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004228 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004229 llvm_unreachable("Clause is not allowed.");
4230 }
4231 return Res;
4232}
4233
4234OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4235 SourceLocation KindKwLoc,
4236 SourceLocation StartLoc,
4237 SourceLocation LParenLoc,
4238 SourceLocation EndLoc) {
4239 if (Kind == OMPC_DEFAULT_unknown) {
4240 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004241 static_assert(OMPC_DEFAULT_unknown > 0,
4242 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004243 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004244 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004245 Values += "'";
4246 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4247 Values += "'";
4248 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004249 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004250 Values += " or ";
4251 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004252 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004253 break;
4254 default:
4255 Values += Sep;
4256 break;
4257 }
4258 }
4259 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004260 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004261 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004262 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004263 switch (Kind) {
4264 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004265 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004266 break;
4267 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004268 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004269 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004270 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004271 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004272 break;
4273 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004274 return new (Context)
4275 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004276}
4277
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004278OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4279 SourceLocation KindKwLoc,
4280 SourceLocation StartLoc,
4281 SourceLocation LParenLoc,
4282 SourceLocation EndLoc) {
4283 if (Kind == OMPC_PROC_BIND_unknown) {
4284 std::string Values;
4285 std::string Sep(", ");
4286 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4287 Values += "'";
4288 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4289 Values += "'";
4290 switch (i) {
4291 case OMPC_PROC_BIND_unknown - 2:
4292 Values += " or ";
4293 break;
4294 case OMPC_PROC_BIND_unknown - 1:
4295 break;
4296 default:
4297 Values += Sep;
4298 break;
4299 }
4300 }
4301 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004302 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004303 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004304 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004305 return new (Context)
4306 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004307}
4308
Alexey Bataev56dafe82014-06-20 07:16:17 +00004309OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4310 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4311 SourceLocation StartLoc, SourceLocation LParenLoc,
4312 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4313 SourceLocation EndLoc) {
4314 OMPClause *Res = nullptr;
4315 switch (Kind) {
4316 case OMPC_schedule:
4317 Res = ActOnOpenMPScheduleClause(
4318 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4319 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4320 break;
4321 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004322 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004323 case OMPC_num_threads:
4324 case OMPC_safelen:
4325 case OMPC_collapse:
4326 case OMPC_default:
4327 case OMPC_proc_bind:
4328 case OMPC_private:
4329 case OMPC_firstprivate:
4330 case OMPC_lastprivate:
4331 case OMPC_shared:
4332 case OMPC_reduction:
4333 case OMPC_linear:
4334 case OMPC_aligned:
4335 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004336 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004337 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004338 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004339 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004340 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004341 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004342 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004343 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004344 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004345 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004346 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004347 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004348 case OMPC_unknown:
4349 llvm_unreachable("Clause is not allowed.");
4350 }
4351 return Res;
4352}
4353
4354OMPClause *Sema::ActOnOpenMPScheduleClause(
4355 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4356 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4357 SourceLocation EndLoc) {
4358 if (Kind == OMPC_SCHEDULE_unknown) {
4359 std::string Values;
4360 std::string Sep(", ");
4361 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4362 Values += "'";
4363 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4364 Values += "'";
4365 switch (i) {
4366 case OMPC_SCHEDULE_unknown - 2:
4367 Values += " or ";
4368 break;
4369 case OMPC_SCHEDULE_unknown - 1:
4370 break;
4371 default:
4372 Values += Sep;
4373 break;
4374 }
4375 }
4376 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4377 << Values << getOpenMPClauseName(OMPC_schedule);
4378 return nullptr;
4379 }
4380 Expr *ValExpr = ChunkSize;
4381 if (ChunkSize) {
4382 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4383 !ChunkSize->isInstantiationDependent() &&
4384 !ChunkSize->containsUnexpandedParameterPack()) {
4385 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4386 ExprResult Val =
4387 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4388 if (Val.isInvalid())
4389 return nullptr;
4390
4391 ValExpr = Val.get();
4392
4393 // OpenMP [2.7.1, Restrictions]
4394 // chunk_size must be a loop invariant integer expression with a positive
4395 // value.
4396 llvm::APSInt Result;
4397 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
4398 Result.isSigned() && !Result.isStrictlyPositive()) {
4399 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4400 << "schedule" << ChunkSize->getSourceRange();
4401 return nullptr;
4402 }
4403 }
4404 }
4405
4406 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4407 EndLoc, Kind, ValExpr);
4408}
4409
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004410OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4411 SourceLocation StartLoc,
4412 SourceLocation EndLoc) {
4413 OMPClause *Res = nullptr;
4414 switch (Kind) {
4415 case OMPC_ordered:
4416 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4417 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004418 case OMPC_nowait:
4419 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4420 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004421 case OMPC_untied:
4422 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4423 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004424 case OMPC_mergeable:
4425 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4426 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004427 case OMPC_read:
4428 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4429 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004430 case OMPC_write:
4431 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4432 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004433 case OMPC_update:
4434 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4435 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004436 case OMPC_capture:
4437 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4438 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004439 case OMPC_seq_cst:
4440 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4441 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004442 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004443 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004444 case OMPC_num_threads:
4445 case OMPC_safelen:
4446 case OMPC_collapse:
4447 case OMPC_schedule:
4448 case OMPC_private:
4449 case OMPC_firstprivate:
4450 case OMPC_lastprivate:
4451 case OMPC_shared:
4452 case OMPC_reduction:
4453 case OMPC_linear:
4454 case OMPC_aligned:
4455 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004456 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004457 case OMPC_default:
4458 case OMPC_proc_bind:
4459 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004460 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004461 case OMPC_unknown:
4462 llvm_unreachable("Clause is not allowed.");
4463 }
4464 return Res;
4465}
4466
4467OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4468 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004469 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004470 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4471}
4472
Alexey Bataev236070f2014-06-20 11:19:47 +00004473OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4474 SourceLocation EndLoc) {
4475 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4476}
4477
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004478OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4479 SourceLocation EndLoc) {
4480 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4481}
4482
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004483OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4484 SourceLocation EndLoc) {
4485 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4486}
4487
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004488OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4489 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004490 return new (Context) OMPReadClause(StartLoc, EndLoc);
4491}
4492
Alexey Bataevdea47612014-07-23 07:46:59 +00004493OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4494 SourceLocation EndLoc) {
4495 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4496}
4497
Alexey Bataev67a4f222014-07-23 10:25:33 +00004498OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4499 SourceLocation EndLoc) {
4500 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4501}
4502
Alexey Bataev459dec02014-07-24 06:46:57 +00004503OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4504 SourceLocation EndLoc) {
4505 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4506}
4507
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004508OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4509 SourceLocation EndLoc) {
4510 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4511}
4512
Alexey Bataevc5e02582014-06-16 07:08:35 +00004513OMPClause *Sema::ActOnOpenMPVarListClause(
4514 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4515 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4516 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4517 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004518 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004519 switch (Kind) {
4520 case OMPC_private:
4521 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4522 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004523 case OMPC_firstprivate:
4524 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4525 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004526 case OMPC_lastprivate:
4527 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4528 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004529 case OMPC_shared:
4530 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4531 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004532 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004533 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4534 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004535 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004536 case OMPC_linear:
4537 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4538 ColonLoc, EndLoc);
4539 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004540 case OMPC_aligned:
4541 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4542 ColonLoc, EndLoc);
4543 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004544 case OMPC_copyin:
4545 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4546 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004547 case OMPC_copyprivate:
4548 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4549 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004550 case OMPC_flush:
4551 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4552 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004553 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004554 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004555 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004556 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004557 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004558 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004559 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004560 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004561 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004562 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004563 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004564 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004565 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004566 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004567 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004568 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004569 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004570 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004571 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004572 llvm_unreachable("Clause is not allowed.");
4573 }
4574 return Res;
4575}
4576
4577OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4578 SourceLocation StartLoc,
4579 SourceLocation LParenLoc,
4580 SourceLocation EndLoc) {
4581 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004582 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004583 for (auto &RefExpr : VarList) {
4584 assert(RefExpr && "NULL expr in OpenMP private clause.");
4585 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004586 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004587 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004588 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004589 continue;
4590 }
4591
Alexey Bataeved09d242014-05-28 05:53:51 +00004592 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004593 // OpenMP [2.1, C/C++]
4594 // A list item is a variable name.
4595 // OpenMP [2.9.3.3, Restrictions, p.1]
4596 // A variable that is part of another variable (as an array or
4597 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004598 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004599 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004600 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004601 continue;
4602 }
4603 Decl *D = DE->getDecl();
4604 VarDecl *VD = cast<VarDecl>(D);
4605
4606 QualType Type = VD->getType();
4607 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4608 // It will be analyzed later.
4609 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004610 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004611 continue;
4612 }
4613
4614 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4615 // A variable that appears in a private clause must not have an incomplete
4616 // type or a reference type.
4617 if (RequireCompleteType(ELoc, Type,
4618 diag::err_omp_private_incomplete_type)) {
4619 continue;
4620 }
4621 if (Type->isReferenceType()) {
4622 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004623 << getOpenMPClauseName(OMPC_private) << Type;
4624 bool IsDecl =
4625 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4626 Diag(VD->getLocation(),
4627 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4628 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004629 continue;
4630 }
4631
4632 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4633 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004634 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004635 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004636 while (Type->isArrayType()) {
4637 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004638 }
4639
Alexey Bataev758e55e2013-09-06 18:03:48 +00004640 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4641 // in a Construct]
4642 // Variables with the predetermined data-sharing attributes may not be
4643 // listed in data-sharing attributes clauses, except for the cases
4644 // listed below. For these exceptions only, listing a predetermined
4645 // variable in a data-sharing attribute clause is allowed and overrides
4646 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004647 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004648 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004649 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4650 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004651 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004652 continue;
4653 }
4654
Alexey Bataev03b340a2014-10-21 03:16:40 +00004655 // Generate helper private variable and initialize it with the default
4656 // value. The address of the original variable is replaced by the address of
4657 // the new private variable in CodeGen. This new variable is not added to
4658 // IdResolver, so the code in the OpenMP region uses original variable for
4659 // proper diagnostics.
4660 auto VDPrivate =
4661 VarDecl::Create(Context, CurContext, DE->getLocStart(),
4662 DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
4663 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4664 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4665 if (VDPrivate->isInvalidDecl())
4666 continue;
4667 CurContext->addDecl(VDPrivate);
Alexey Bataev07649fb2014-12-16 08:01:48 +00004668 auto VDPrivateRefExpr =
4669 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4670 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004671 /*RefersToEnclosingVariableOrCapture*/ false,
Alexey Bataev07649fb2014-12-16 08:01:48 +00004672 /*NameLoc*/ SourceLocation(), DE->getType(),
4673 /*VK*/ VK_LValue);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004674
Alexey Bataev758e55e2013-09-06 18:03:48 +00004675 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004676 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004677 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004678 }
4679
Alexey Bataeved09d242014-05-28 05:53:51 +00004680 if (Vars.empty())
4681 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004682
Alexey Bataev03b340a2014-10-21 03:16:40 +00004683 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4684 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004685}
4686
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004687namespace {
4688class DiagsUninitializedSeveretyRAII {
4689private:
4690 DiagnosticsEngine &Diags;
4691 SourceLocation SavedLoc;
4692 bool IsIgnored;
4693
4694public:
4695 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4696 bool IsIgnored)
4697 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4698 if (!IsIgnored) {
4699 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4700 /*Map*/ diag::Severity::Ignored, Loc);
4701 }
4702 }
4703 ~DiagsUninitializedSeveretyRAII() {
4704 if (!IsIgnored)
4705 Diags.popMappings(SavedLoc);
4706 }
4707};
4708}
4709
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004710OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4711 SourceLocation StartLoc,
4712 SourceLocation LParenLoc,
4713 SourceLocation EndLoc) {
4714 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004715 SmallVector<Expr *, 8> PrivateCopies;
4716 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004717 bool IsImplicitClause =
4718 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4719 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4720
Alexey Bataeved09d242014-05-28 05:53:51 +00004721 for (auto &RefExpr : VarList) {
4722 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4723 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004724 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004725 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004726 PrivateCopies.push_back(nullptr);
4727 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004728 continue;
4729 }
4730
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004731 SourceLocation ELoc =
4732 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004733 // OpenMP [2.1, C/C++]
4734 // A list item is a variable name.
4735 // OpenMP [2.9.3.3, Restrictions, p.1]
4736 // A variable that is part of another variable (as an array or
4737 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004738 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004739 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004740 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004741 continue;
4742 }
4743 Decl *D = DE->getDecl();
4744 VarDecl *VD = cast<VarDecl>(D);
4745
4746 QualType Type = VD->getType();
4747 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4748 // It will be analyzed later.
4749 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004750 PrivateCopies.push_back(nullptr);
4751 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004752 continue;
4753 }
4754
4755 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4756 // A variable that appears in a private clause must not have an incomplete
4757 // type or a reference type.
4758 if (RequireCompleteType(ELoc, Type,
4759 diag::err_omp_firstprivate_incomplete_type)) {
4760 continue;
4761 }
4762 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004763 if (IsImplicitClause) {
4764 Diag(ImplicitClauseLoc,
4765 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4766 << Type;
4767 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4768 } else {
4769 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4770 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4771 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004772 bool IsDecl =
4773 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4774 Diag(VD->getLocation(),
4775 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4776 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004777 continue;
4778 }
4779
4780 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4781 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004782 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004783 // class type.
4784 Type = Context.getBaseElementType(Type);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004785
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004786 // If an implicit firstprivate variable found it was checked already.
4787 if (!IsImplicitClause) {
4788 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004789 Type = Type.getNonReferenceType().getCanonicalType();
4790 bool IsConstant = Type.isConstant(Context);
4791 Type = Context.getBaseElementType(Type);
4792 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4793 // A list item that specifies a given variable may not appear in more
4794 // than one clause on the same directive, except that a variable may be
4795 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004796 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004797 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004798 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004799 << getOpenMPClauseName(DVar.CKind)
4800 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004801 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004802 continue;
4803 }
4804
4805 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4806 // in a Construct]
4807 // Variables with the predetermined data-sharing attributes may not be
4808 // listed in data-sharing attributes clauses, except for the cases
4809 // listed below. For these exceptions only, listing a predetermined
4810 // variable in a data-sharing attribute clause is allowed and overrides
4811 // the variable's predetermined data-sharing attributes.
4812 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4813 // in a Construct, C/C++, p.2]
4814 // Variables with const-qualified type having no mutable member may be
4815 // listed in a firstprivate clause, even if they are static data members.
4816 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4817 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4818 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
Alexey Bataevf29276e2014-06-18 04:14:57 +00004825 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004826 // OpenMP [2.9.3.4, Restrictions, p.2]
4827 // A list item that is private within a parallel region must not appear
4828 // in a firstprivate clause on a worksharing construct if any of the
4829 // worksharing regions arising from the worksharing construct ever bind
4830 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004831 if (isOpenMPWorksharingDirective(CurrDir) &&
4832 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004833 DVar = DSAStack->getImplicitDSA(VD, true);
4834 if (DVar.CKind != OMPC_shared &&
4835 (isOpenMPParallelDirective(DVar.DKind) ||
4836 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004837 Diag(ELoc, diag::err_omp_required_access)
4838 << getOpenMPClauseName(OMPC_firstprivate)
4839 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004840 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004841 continue;
4842 }
4843 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004844 // OpenMP [2.9.3.4, Restrictions, p.3]
4845 // A list item that appears in a reduction clause of a parallel construct
4846 // must not appear in a firstprivate clause on a worksharing or task
4847 // construct if any of the worksharing or task regions arising from the
4848 // worksharing or task construct ever bind to any of the parallel regions
4849 // arising from the parallel construct.
4850 // OpenMP [2.9.3.4, Restrictions, p.4]
4851 // A list item that appears in a reduction clause in worksharing
4852 // construct must not appear in a firstprivate clause in a task construct
4853 // encountered during execution of any of the worksharing regions arising
4854 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004855 if (CurrDir == OMPD_task) {
4856 DVar =
4857 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4858 [](OpenMPDirectiveKind K) -> bool {
4859 return isOpenMPParallelDirective(K) ||
4860 isOpenMPWorksharingDirective(K);
4861 },
4862 false);
4863 if (DVar.CKind == OMPC_reduction &&
4864 (isOpenMPParallelDirective(DVar.DKind) ||
4865 isOpenMPWorksharingDirective(DVar.DKind))) {
4866 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4867 << getOpenMPDirectiveName(DVar.DKind);
4868 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4869 continue;
4870 }
4871 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004872 }
4873
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004874 Type = Type.getUnqualifiedType();
4875 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4876 ELoc, VD->getIdentifier(), VD->getType(),
4877 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4878 // Generate helper private variable and initialize it with the value of the
4879 // original variable. The address of the original variable is replaced by
4880 // the address of the new private variable in the CodeGen. This new variable
4881 // is not added to IdResolver, so the code in the OpenMP region uses
4882 // original variable for proper diagnostics and variable capturing.
4883 Expr *VDInitRefExpr = nullptr;
4884 // For arrays generate initializer for single element and replace it by the
4885 // original array element in CodeGen.
4886 if (DE->getType()->isArrayType()) {
4887 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4888 ELoc, VD->getIdentifier(), Type,
4889 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4890 CurContext->addHiddenDecl(VDInit);
4891 VDInitRefExpr = DeclRefExpr::Create(
4892 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4893 /*TemplateKWLoc*/ SourceLocation(), VDInit,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004894 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004895 /*VK*/ VK_LValue);
4896 VDInit->setIsUsed();
4897 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
4898 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDInit);
4899 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4900
4901 InitializationSequence InitSeq(*this, Entity, Kind, Init);
4902 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4903 if (Result.isInvalid())
4904 VDPrivate->setInvalidDecl();
4905 else
4906 VDPrivate->setInit(Result.getAs<Expr>());
4907 } else {
Alexey Bataevf841bd92014-12-16 07:00:22 +00004908 AddInitializerToDecl(
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004909 VDPrivate,
4910 DefaultLvalueConversion(
4911 DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
4912 SourceLocation(), DE->getDecl(),
4913 /*RefersToEnclosingVariableOrCapture=*/true,
4914 DE->getExprLoc(), DE->getType(),
4915 /*VK=*/VK_LValue)).get(),
Alexey Bataevf841bd92014-12-16 07:00:22 +00004916 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004917 }
4918 if (VDPrivate->isInvalidDecl()) {
4919 if (IsImplicitClause) {
4920 Diag(DE->getExprLoc(),
4921 diag::note_omp_task_predetermined_firstprivate_here);
4922 }
4923 continue;
4924 }
4925 CurContext->addDecl(VDPrivate);
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004926 auto VDPrivateRefExpr =
4927 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4928 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4929 /*RefersToEnclosingVariableOrCapture*/ false,
4930 DE->getLocStart(), DE->getType(),
4931 /*VK*/ VK_LValue);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004932 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4933 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004934 PrivateCopies.push_back(VDPrivateRefExpr);
4935 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004936 }
4937
Alexey Bataeved09d242014-05-28 05:53:51 +00004938 if (Vars.empty())
4939 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004940
4941 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004942 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004943}
4944
Alexander Musman1bb328c2014-06-04 13:06:39 +00004945OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
4946 SourceLocation StartLoc,
4947 SourceLocation LParenLoc,
4948 SourceLocation EndLoc) {
4949 SmallVector<Expr *, 8> Vars;
4950 for (auto &RefExpr : VarList) {
4951 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
4952 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4953 // It will be analyzed later.
4954 Vars.push_back(RefExpr);
4955 continue;
4956 }
4957
4958 SourceLocation ELoc = RefExpr->getExprLoc();
4959 // OpenMP [2.1, C/C++]
4960 // A list item is a variable name.
4961 // OpenMP [2.14.3.5, Restrictions, p.1]
4962 // A variable that is part of another variable (as an array or structure
4963 // element) cannot appear in a lastprivate clause.
4964 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4965 if (!DE || !isa<VarDecl>(DE->getDecl())) {
4966 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
4967 continue;
4968 }
4969 Decl *D = DE->getDecl();
4970 VarDecl *VD = cast<VarDecl>(D);
4971
4972 QualType Type = VD->getType();
4973 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4974 // It will be analyzed later.
4975 Vars.push_back(DE);
4976 continue;
4977 }
4978
4979 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
4980 // A variable that appears in a lastprivate clause must not have an
4981 // incomplete type or a reference type.
4982 if (RequireCompleteType(ELoc, Type,
4983 diag::err_omp_lastprivate_incomplete_type)) {
4984 continue;
4985 }
4986 if (Type->isReferenceType()) {
4987 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4988 << getOpenMPClauseName(OMPC_lastprivate) << Type;
4989 bool IsDecl =
4990 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4991 Diag(VD->getLocation(),
4992 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4993 << VD;
4994 continue;
4995 }
4996
4997 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4998 // in a Construct]
4999 // Variables with the predetermined data-sharing attributes may not be
5000 // listed in data-sharing attributes clauses, except for the cases
5001 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005002 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005003 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5004 DVar.CKind != OMPC_firstprivate &&
5005 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5006 Diag(ELoc, diag::err_omp_wrong_dsa)
5007 << getOpenMPClauseName(DVar.CKind)
5008 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005009 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005010 continue;
5011 }
5012
Alexey Bataevf29276e2014-06-18 04:14:57 +00005013 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5014 // OpenMP [2.14.3.5, Restrictions, p.2]
5015 // A list item that is private within a parallel region, or that appears in
5016 // the reduction clause of a parallel construct, must not appear in a
5017 // lastprivate clause on a worksharing construct if any of the corresponding
5018 // worksharing regions ever binds to any of the corresponding parallel
5019 // regions.
Alexey Bataev549210e2014-06-24 04:39:47 +00005020 if (isOpenMPWorksharingDirective(CurrDir) &&
5021 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005022 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005023 if (DVar.CKind != OMPC_shared) {
5024 Diag(ELoc, diag::err_omp_required_access)
5025 << getOpenMPClauseName(OMPC_lastprivate)
5026 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005027 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005028 continue;
5029 }
5030 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005031 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005032 // A variable of class type (or array thereof) that appears in a
5033 // lastprivate clause requires an accessible, unambiguous default
5034 // constructor for the class type, unless the list item is also specified
5035 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005036 // A variable of class type (or array thereof) that appears in a
5037 // lastprivate clause requires an accessible, unambiguous copy assignment
5038 // operator for the class type.
5039 while (Type.getNonReferenceType()->isArrayType())
5040 Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
5041 ->getElementType();
5042 CXXRecordDecl *RD = getLangOpts().CPlusPlus
5043 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
5044 : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005045 // FIXME This code must be replaced by actual copying and destructing of the
5046 // lastprivate variable.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005047 if (RD) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00005048 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5049 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005050 if (MD) {
5051 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5052 MD->isDeleted()) {
5053 Diag(ELoc, diag::err_omp_required_method)
5054 << getOpenMPClauseName(OMPC_lastprivate) << 2;
5055 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5056 VarDecl::DeclarationOnly;
5057 Diag(VD->getLocation(),
5058 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5059 << VD;
5060 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5061 continue;
5062 }
5063 MarkFunctionReferenced(ELoc, MD);
5064 DiagnoseUseOfDecl(MD, ELoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005065 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005066
5067 CXXDestructorDecl *DD = RD->getDestructor();
5068 if (DD) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005069 PartialDiagnostic PD =
5070 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005071 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
5072 DD->isDeleted()) {
5073 Diag(ELoc, diag::err_omp_required_method)
5074 << getOpenMPClauseName(OMPC_lastprivate) << 4;
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, DD);
5084 DiagnoseUseOfDecl(DD, ELoc);
5085 }
5086 }
5087
Alexey Bataevf29276e2014-06-18 04:14:57 +00005088 if (DVar.CKind != OMPC_firstprivate)
5089 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005090 Vars.push_back(DE);
5091 }
5092
5093 if (Vars.empty())
5094 return nullptr;
5095
5096 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5097 Vars);
5098}
5099
Alexey Bataev758e55e2013-09-06 18:03:48 +00005100OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5101 SourceLocation StartLoc,
5102 SourceLocation LParenLoc,
5103 SourceLocation EndLoc) {
5104 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005105 for (auto &RefExpr : VarList) {
5106 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5107 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005108 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005109 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005110 continue;
5111 }
5112
Alexey Bataeved09d242014-05-28 05:53:51 +00005113 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005114 // OpenMP [2.1, C/C++]
5115 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005116 // OpenMP [2.14.3.2, Restrictions, p.1]
5117 // A variable that is part of another variable (as an array or structure
5118 // element) cannot appear in a shared unless it is a static data member
5119 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005120 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005121 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005122 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005123 continue;
5124 }
5125 Decl *D = DE->getDecl();
5126 VarDecl *VD = cast<VarDecl>(D);
5127
5128 QualType Type = VD->getType();
5129 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5130 // It will be analyzed later.
5131 Vars.push_back(DE);
5132 continue;
5133 }
5134
5135 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5136 // in a Construct]
5137 // Variables with the predetermined data-sharing attributes may not be
5138 // listed in data-sharing attributes clauses, except for the cases
5139 // listed below. For these exceptions only, listing a predetermined
5140 // variable in a data-sharing attribute clause is allowed and overrides
5141 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005142 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005143 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5144 DVar.RefExpr) {
5145 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5146 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005147 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005148 continue;
5149 }
5150
5151 DSAStack->addDSA(VD, DE, OMPC_shared);
5152 Vars.push_back(DE);
5153 }
5154
Alexey Bataeved09d242014-05-28 05:53:51 +00005155 if (Vars.empty())
5156 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005157
5158 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5159}
5160
Alexey Bataevc5e02582014-06-16 07:08:35 +00005161namespace {
5162class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5163 DSAStackTy *Stack;
5164
5165public:
5166 bool VisitDeclRefExpr(DeclRefExpr *E) {
5167 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005168 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005169 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5170 return false;
5171 if (DVar.CKind != OMPC_unknown)
5172 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005173 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005174 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005175 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005176 return true;
5177 return false;
5178 }
5179 return false;
5180 }
5181 bool VisitStmt(Stmt *S) {
5182 for (auto Child : S->children()) {
5183 if (Child && Visit(Child))
5184 return true;
5185 }
5186 return false;
5187 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005188 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005189};
Alexey Bataev23b69422014-06-18 07:08:49 +00005190} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005191
5192OMPClause *Sema::ActOnOpenMPReductionClause(
5193 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5194 SourceLocation ColonLoc, SourceLocation EndLoc,
5195 CXXScopeSpec &ReductionIdScopeSpec,
5196 const DeclarationNameInfo &ReductionId) {
5197 // TODO: Allow scope specification search when 'declare reduction' is
5198 // supported.
5199 assert(ReductionIdScopeSpec.isEmpty() &&
5200 "No support for scoped reduction identifiers yet.");
5201
5202 auto DN = ReductionId.getName();
5203 auto OOK = DN.getCXXOverloadedOperator();
5204 BinaryOperatorKind BOK = BO_Comma;
5205
5206 // OpenMP [2.14.3.6, reduction clause]
5207 // C
5208 // reduction-identifier is either an identifier or one of the following
5209 // operators: +, -, *, &, |, ^, && and ||
5210 // C++
5211 // reduction-identifier is either an id-expression or one of the following
5212 // operators: +, -, *, &, |, ^, && and ||
5213 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5214 switch (OOK) {
5215 case OO_Plus:
5216 case OO_Minus:
5217 BOK = BO_AddAssign;
5218 break;
5219 case OO_Star:
5220 BOK = BO_MulAssign;
5221 break;
5222 case OO_Amp:
5223 BOK = BO_AndAssign;
5224 break;
5225 case OO_Pipe:
5226 BOK = BO_OrAssign;
5227 break;
5228 case OO_Caret:
5229 BOK = BO_XorAssign;
5230 break;
5231 case OO_AmpAmp:
5232 BOK = BO_LAnd;
5233 break;
5234 case OO_PipePipe:
5235 BOK = BO_LOr;
5236 break;
5237 default:
5238 if (auto II = DN.getAsIdentifierInfo()) {
5239 if (II->isStr("max"))
5240 BOK = BO_GT;
5241 else if (II->isStr("min"))
5242 BOK = BO_LT;
5243 }
5244 break;
5245 }
5246 SourceRange ReductionIdRange;
5247 if (ReductionIdScopeSpec.isValid()) {
5248 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5249 }
5250 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5251 if (BOK == BO_Comma) {
5252 // Not allowed reduction identifier is found.
5253 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5254 << ReductionIdRange;
5255 return nullptr;
5256 }
5257
5258 SmallVector<Expr *, 8> Vars;
5259 for (auto RefExpr : VarList) {
5260 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5261 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5262 // It will be analyzed later.
5263 Vars.push_back(RefExpr);
5264 continue;
5265 }
5266
5267 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5268 RefExpr->isInstantiationDependent() ||
5269 RefExpr->containsUnexpandedParameterPack()) {
5270 // It will be analyzed later.
5271 Vars.push_back(RefExpr);
5272 continue;
5273 }
5274
5275 auto ELoc = RefExpr->getExprLoc();
5276 auto ERange = RefExpr->getSourceRange();
5277 // OpenMP [2.1, C/C++]
5278 // A list item is a variable or array section, subject to the restrictions
5279 // specified in Section 2.4 on page 42 and in each of the sections
5280 // describing clauses and directives for which a list appears.
5281 // OpenMP [2.14.3.3, Restrictions, p.1]
5282 // A variable that is part of another variable (as an array or
5283 // structure element) cannot appear in a private clause.
5284 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5285 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5286 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5287 continue;
5288 }
5289 auto D = DE->getDecl();
5290 auto VD = cast<VarDecl>(D);
5291 auto Type = VD->getType();
5292 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5293 // A variable that appears in a private clause must not have an incomplete
5294 // type or a reference type.
5295 if (RequireCompleteType(ELoc, Type,
5296 diag::err_omp_reduction_incomplete_type))
5297 continue;
5298 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5299 // Arrays may not appear in a reduction clause.
5300 if (Type.getNonReferenceType()->isArrayType()) {
5301 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5302 bool IsDecl =
5303 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5304 Diag(VD->getLocation(),
5305 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5306 << VD;
5307 continue;
5308 }
5309 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5310 // A list item that appears in a reduction clause must not be
5311 // const-qualified.
5312 if (Type.getNonReferenceType().isConstant(Context)) {
5313 Diag(ELoc, diag::err_omp_const_variable)
5314 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5315 bool IsDecl =
5316 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5317 Diag(VD->getLocation(),
5318 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5319 << VD;
5320 continue;
5321 }
5322 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5323 // If a list-item is a reference type then it must bind to the same object
5324 // for all threads of the team.
5325 VarDecl *VDDef = VD->getDefinition();
5326 if (Type->isReferenceType() && VDDef) {
5327 DSARefChecker Check(DSAStack);
5328 if (Check.Visit(VDDef->getInit())) {
5329 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5330 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5331 continue;
5332 }
5333 }
5334 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5335 // The type of a list item that appears in a reduction clause must be valid
5336 // for the reduction-identifier. For a max or min reduction in C, the type
5337 // of the list item must be an allowed arithmetic data type: char, int,
5338 // float, double, or _Bool, possibly modified with long, short, signed, or
5339 // unsigned. For a max or min reduction in C++, the type of the list item
5340 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5341 // double, or bool, possibly modified with long, short, signed, or unsigned.
5342 if ((BOK == BO_GT || BOK == BO_LT) &&
5343 !(Type->isScalarType() ||
5344 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5345 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5346 << getLangOpts().CPlusPlus;
5347 bool IsDecl =
5348 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5349 Diag(VD->getLocation(),
5350 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5351 << VD;
5352 continue;
5353 }
5354 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5355 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5356 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5357 bool IsDecl =
5358 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5359 Diag(VD->getLocation(),
5360 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5361 << VD;
5362 continue;
5363 }
5364 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
5365 getDiagnostics().setSuppressAllDiagnostics(true);
5366 ExprResult ReductionOp =
5367 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5368 RefExpr, RefExpr);
5369 getDiagnostics().setSuppressAllDiagnostics(Suppress);
5370 if (ReductionOp.isInvalid()) {
5371 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
Alexey Bataev23b69422014-06-18 07:08:49 +00005372 << ReductionIdRange;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005373 bool IsDecl =
5374 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5375 Diag(VD->getLocation(),
5376 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5377 << VD;
5378 continue;
5379 }
5380
5381 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5382 // in a Construct]
5383 // Variables with the predetermined data-sharing attributes may not be
5384 // listed in data-sharing attributes clauses, except for the cases
5385 // listed below. For these exceptions only, listing a predetermined
5386 // variable in a data-sharing attribute clause is allowed and overrides
5387 // the variable's predetermined data-sharing attributes.
5388 // OpenMP [2.14.3.6, Restrictions, p.3]
5389 // Any number of reduction clauses can be specified on the directive,
5390 // but a list item can appear only once in the reduction clauses for that
5391 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005392 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005393 if (DVar.CKind == OMPC_reduction) {
5394 Diag(ELoc, diag::err_omp_once_referenced)
5395 << getOpenMPClauseName(OMPC_reduction);
5396 if (DVar.RefExpr) {
5397 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5398 }
5399 } else if (DVar.CKind != OMPC_unknown) {
5400 Diag(ELoc, diag::err_omp_wrong_dsa)
5401 << getOpenMPClauseName(DVar.CKind)
5402 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005403 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005404 continue;
5405 }
5406
5407 // OpenMP [2.14.3.6, Restrictions, p.1]
5408 // A list item that appears in a reduction clause of a worksharing
5409 // construct must be shared in the parallel regions to which any of the
5410 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005411 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005412 if (isOpenMPWorksharingDirective(CurrDir) &&
5413 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005414 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005415 if (DVar.CKind != OMPC_shared) {
5416 Diag(ELoc, diag::err_omp_required_access)
5417 << getOpenMPClauseName(OMPC_reduction)
5418 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005419 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005420 continue;
5421 }
5422 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005423
5424 CXXRecordDecl *RD = getLangOpts().CPlusPlus
5425 ? Type.getNonReferenceType()->getAsCXXRecordDecl()
5426 : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005427 // FIXME This code must be replaced by actual constructing/destructing of
5428 // the reduction variable.
Alexey Bataevc5e02582014-06-16 07:08:35 +00005429 if (RD) {
5430 CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
5431 PartialDiagnostic PD =
5432 PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
Alexey Bataev23b69422014-06-18 07:08:49 +00005433 if (!CD ||
5434 CheckConstructorAccess(ELoc, CD,
5435 InitializedEntity::InitializeTemporary(Type),
5436 CD->getAccess(), PD) == AR_inaccessible ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00005437 CD->isDeleted()) {
5438 Diag(ELoc, diag::err_omp_required_method)
5439 << getOpenMPClauseName(OMPC_reduction) << 0;
5440 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5441 VarDecl::DeclarationOnly;
5442 Diag(VD->getLocation(),
5443 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5444 << VD;
5445 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5446 continue;
5447 }
5448 MarkFunctionReferenced(ELoc, CD);
5449 DiagnoseUseOfDecl(CD, ELoc);
5450
5451 CXXDestructorDecl *DD = RD->getDestructor();
5452 if (DD) {
5453 if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
5454 DD->isDeleted()) {
5455 Diag(ELoc, diag::err_omp_required_method)
5456 << getOpenMPClauseName(OMPC_reduction) << 4;
5457 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5458 VarDecl::DeclarationOnly;
5459 Diag(VD->getLocation(),
5460 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5461 << VD;
5462 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5463 continue;
5464 }
5465 MarkFunctionReferenced(ELoc, DD);
5466 DiagnoseUseOfDecl(DD, ELoc);
5467 }
5468 }
5469
5470 DSAStack->addDSA(VD, DE, OMPC_reduction);
5471 Vars.push_back(DE);
5472 }
5473
5474 if (Vars.empty())
5475 return nullptr;
5476
5477 return OMPReductionClause::Create(
5478 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
5479 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
5480}
5481
Alexander Musman8dba6642014-04-22 13:09:42 +00005482OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5483 SourceLocation StartLoc,
5484 SourceLocation LParenLoc,
5485 SourceLocation ColonLoc,
5486 SourceLocation EndLoc) {
5487 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005488 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005489 for (auto &RefExpr : VarList) {
5490 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5491 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005492 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005493 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005494 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005495 continue;
5496 }
5497
5498 // OpenMP [2.14.3.7, linear clause]
5499 // A list item that appears in a linear clause is subject to the private
5500 // clause semantics described in Section 2.14.3.3 on page 159 except as
5501 // noted. In addition, the value of the new list item on each iteration
5502 // of the associated loop(s) corresponds to the value of the original
5503 // list item before entering the construct plus the logical number of
5504 // the iteration times linear-step.
5505
Alexey Bataeved09d242014-05-28 05:53:51 +00005506 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005507 // OpenMP [2.1, C/C++]
5508 // A list item is a variable name.
5509 // OpenMP [2.14.3.3, Restrictions, p.1]
5510 // A variable that is part of another variable (as an array or
5511 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005512 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005513 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005514 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005515 continue;
5516 }
5517
5518 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5519
5520 // OpenMP [2.14.3.7, linear clause]
5521 // A list-item cannot appear in more than one linear clause.
5522 // A list-item that appears in a linear clause cannot appear in any
5523 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005524 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005525 if (DVar.RefExpr) {
5526 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5527 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005528 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005529 continue;
5530 }
5531
5532 QualType QType = VD->getType();
5533 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5534 // It will be analyzed later.
5535 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005536 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005537 continue;
5538 }
5539
5540 // A variable must not have an incomplete type or a reference type.
5541 if (RequireCompleteType(ELoc, QType,
5542 diag::err_omp_linear_incomplete_type)) {
5543 continue;
5544 }
5545 if (QType->isReferenceType()) {
5546 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5547 << getOpenMPClauseName(OMPC_linear) << QType;
5548 bool IsDecl =
5549 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5550 Diag(VD->getLocation(),
5551 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5552 << VD;
5553 continue;
5554 }
5555
5556 // A list item must not be const-qualified.
5557 if (QType.isConstant(Context)) {
5558 Diag(ELoc, diag::err_omp_const_variable)
5559 << getOpenMPClauseName(OMPC_linear);
5560 bool IsDecl =
5561 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5562 Diag(VD->getLocation(),
5563 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5564 << VD;
5565 continue;
5566 }
5567
5568 // A list item must be of integral or pointer type.
5569 QType = QType.getUnqualifiedType().getCanonicalType();
5570 const Type *Ty = QType.getTypePtrOrNull();
5571 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5572 !Ty->isPointerType())) {
5573 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5574 bool IsDecl =
5575 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5576 Diag(VD->getLocation(),
5577 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5578 << VD;
5579 continue;
5580 }
5581
Alexander Musman3276a272015-03-21 10:12:56 +00005582 // Build var to save initial value.
5583 VarDecl *Init = BuildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
5584 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5585 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5586 CurContext->addDecl(Init);
5587 Init->setIsUsed();
5588 auto InitRef = DeclRefExpr::Create(
5589 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5590 /*TemplateKWLoc*/ SourceLocation(), Init,
5591 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
5592 /*VK*/ VK_LValue);
Alexander Musman8dba6642014-04-22 13:09:42 +00005593 DSAStack->addDSA(VD, DE, OMPC_linear);
5594 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005595 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005596 }
5597
5598 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005599 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005600
5601 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005602 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005603 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5604 !Step->isInstantiationDependent() &&
5605 !Step->containsUnexpandedParameterPack()) {
5606 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005607 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005608 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005609 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005610 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005611
Alexander Musman3276a272015-03-21 10:12:56 +00005612 // Build var to save the step value.
5613 VarDecl *SaveVar =
5614 BuildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5615 CurContext->addDecl(SaveVar);
5616 SaveVar->setIsUsed();
5617 ExprResult SaveRef =
5618 BuildDeclRefExpr(SaveVar, StepExpr->getType(), VK_LValue, StepLoc);
5619 ExprResult CalcStep =
5620 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5621
Alexander Musman8dba6642014-04-22 13:09:42 +00005622 // Warn about zero linear step (it would be probably better specified as
5623 // making corresponding variables 'const').
5624 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005625 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5626 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005627 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5628 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005629 if (!IsConstant && CalcStep.isUsable()) {
5630 // Calculate the step beforehand instead of doing this on each iteration.
5631 // (This is not used if the number of iterations may be kfold-ed).
5632 CalcStepExpr = CalcStep.get();
5633 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005634 }
5635
5636 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005637 Vars, Inits, StepExpr, CalcStepExpr);
5638}
5639
5640static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5641 Expr *NumIterations, Sema &SemaRef,
5642 Scope *S) {
5643 // Walk the vars and build update/final expressions for the CodeGen.
5644 SmallVector<Expr *, 8> Updates;
5645 SmallVector<Expr *, 8> Finals;
5646 Expr *Step = Clause.getStep();
5647 Expr *CalcStep = Clause.getCalcStep();
5648 // OpenMP [2.14.3.7, linear clause]
5649 // If linear-step is not specified it is assumed to be 1.
5650 if (Step == nullptr)
5651 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5652 else if (CalcStep)
5653 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5654 bool HasErrors = false;
5655 auto CurInit = Clause.inits().begin();
5656 for (auto &RefExpr : Clause.varlists()) {
5657 Expr *InitExpr = *CurInit;
5658
5659 // Build privatized reference to the current linear var.
5660 auto DE = cast<DeclRefExpr>(RefExpr);
5661 auto PrivateRef = DeclRefExpr::Create(
5662 SemaRef.Context, /*QualifierLoc*/ DE->getQualifierLoc(),
5663 /*TemplateKWLoc*/ SourceLocation(), DE->getDecl(),
5664 /* RefersToEnclosingVariableOrCapture */ true, DE->getLocStart(),
5665 DE->getType(), /*VK*/ VK_LValue);
5666
5667 // Build update: Var = InitExpr + IV * Step
5668 ExprResult Update =
5669 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5670 InitExpr, IV, Step, /* Subtract */ false);
5671 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5672
5673 // Build final: Var = InitExpr + NumIterations * Step
5674 ExprResult Final =
5675 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), RefExpr, InitExpr,
5676 NumIterations, Step, /* Subtract */ false);
5677 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5678 if (!Update.isUsable() || !Final.isUsable()) {
5679 Updates.push_back(nullptr);
5680 Finals.push_back(nullptr);
5681 HasErrors = true;
5682 } else {
5683 Updates.push_back(Update.get());
5684 Finals.push_back(Final.get());
5685 }
5686 ++CurInit;
5687 }
5688 Clause.setUpdates(Updates);
5689 Clause.setFinals(Finals);
5690 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005691}
5692
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005693OMPClause *Sema::ActOnOpenMPAlignedClause(
5694 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5695 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5696
5697 SmallVector<Expr *, 8> Vars;
5698 for (auto &RefExpr : VarList) {
5699 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5700 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5701 // It will be analyzed later.
5702 Vars.push_back(RefExpr);
5703 continue;
5704 }
5705
5706 SourceLocation ELoc = RefExpr->getExprLoc();
5707 // OpenMP [2.1, C/C++]
5708 // A list item is a variable name.
5709 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5710 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5711 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5712 continue;
5713 }
5714
5715 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5716
5717 // OpenMP [2.8.1, simd construct, Restrictions]
5718 // The type of list items appearing in the aligned clause must be
5719 // array, pointer, reference to array, or reference to pointer.
5720 QualType QType = DE->getType()
5721 .getNonReferenceType()
5722 .getUnqualifiedType()
5723 .getCanonicalType();
5724 const Type *Ty = QType.getTypePtrOrNull();
5725 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5726 !Ty->isPointerType())) {
5727 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5728 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5729 bool IsDecl =
5730 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5731 Diag(VD->getLocation(),
5732 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5733 << VD;
5734 continue;
5735 }
5736
5737 // OpenMP [2.8.1, simd construct, Restrictions]
5738 // A list-item cannot appear in more than one aligned clause.
5739 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5740 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5741 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5742 << getOpenMPClauseName(OMPC_aligned);
5743 continue;
5744 }
5745
5746 Vars.push_back(DE);
5747 }
5748
5749 // OpenMP [2.8.1, simd construct, Description]
5750 // The parameter of the aligned clause, alignment, must be a constant
5751 // positive integer expression.
5752 // If no optional parameter is specified, implementation-defined default
5753 // alignments for SIMD instructions on the target platforms are assumed.
5754 if (Alignment != nullptr) {
5755 ExprResult AlignResult =
5756 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5757 if (AlignResult.isInvalid())
5758 return nullptr;
5759 Alignment = AlignResult.get();
5760 }
5761 if (Vars.empty())
5762 return nullptr;
5763
5764 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5765 EndLoc, Vars, Alignment);
5766}
5767
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005768OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5769 SourceLocation StartLoc,
5770 SourceLocation LParenLoc,
5771 SourceLocation EndLoc) {
5772 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005773 for (auto &RefExpr : VarList) {
5774 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5775 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005776 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005777 Vars.push_back(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005778 continue;
5779 }
5780
Alexey Bataeved09d242014-05-28 05:53:51 +00005781 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005782 // OpenMP [2.1, C/C++]
5783 // A list item is a variable name.
5784 // OpenMP [2.14.4.1, Restrictions, p.1]
5785 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00005786 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005787 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005788 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005789 continue;
5790 }
5791
5792 Decl *D = DE->getDecl();
5793 VarDecl *VD = cast<VarDecl>(D);
5794
5795 QualType Type = VD->getType();
5796 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5797 // It will be analyzed later.
5798 Vars.push_back(DE);
5799 continue;
5800 }
5801
5802 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5803 // A list item that appears in a copyin clause must be threadprivate.
5804 if (!DSAStack->isThreadPrivate(VD)) {
5805 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00005806 << getOpenMPClauseName(OMPC_copyin)
5807 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005808 continue;
5809 }
5810
5811 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5812 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00005813 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005814 // operator for the class type.
5815 Type = Context.getBaseElementType(Type);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005816 CXXRecordDecl *RD =
5817 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev23b69422014-06-18 07:08:49 +00005818 // FIXME This code must be replaced by actual assignment of the
5819 // threadprivate variable.
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005820 if (RD) {
5821 CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
5822 DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005823 if (MD) {
5824 if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
5825 MD->isDeleted()) {
5826 Diag(ELoc, diag::err_omp_required_method)
5827 << getOpenMPClauseName(OMPC_copyin) << 2;
5828 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
5829 VarDecl::DeclarationOnly;
5830 Diag(VD->getLocation(),
5831 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5832 << VD;
5833 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
5834 continue;
5835 }
5836 MarkFunctionReferenced(ELoc, MD);
5837 DiagnoseUseOfDecl(MD, ELoc);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005838 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005839 }
5840
5841 DSAStack->addDSA(VD, DE, OMPC_copyin);
5842 Vars.push_back(DE);
5843 }
5844
Alexey Bataeved09d242014-05-28 05:53:51 +00005845 if (Vars.empty())
5846 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005847
5848 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5849}
5850
Alexey Bataevbae9a792014-06-27 10:37:06 +00005851OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
5852 SourceLocation StartLoc,
5853 SourceLocation LParenLoc,
5854 SourceLocation EndLoc) {
5855 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00005856 SmallVector<Expr *, 8> SrcExprs;
5857 SmallVector<Expr *, 8> DstExprs;
5858 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005859 for (auto &RefExpr : VarList) {
5860 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
5861 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5862 // It will be analyzed later.
5863 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00005864 SrcExprs.push_back(nullptr);
5865 DstExprs.push_back(nullptr);
5866 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005867 continue;
5868 }
5869
5870 SourceLocation ELoc = RefExpr->getExprLoc();
5871 // OpenMP [2.1, C/C++]
5872 // A list item is a variable name.
5873 // OpenMP [2.14.4.1, Restrictions, p.1]
5874 // A list item that appears in a copyin clause must be threadprivate.
5875 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5876 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5877 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5878 continue;
5879 }
5880
5881 Decl *D = DE->getDecl();
5882 VarDecl *VD = cast<VarDecl>(D);
5883
5884 QualType Type = VD->getType();
5885 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5886 // It will be analyzed later.
5887 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00005888 SrcExprs.push_back(nullptr);
5889 DstExprs.push_back(nullptr);
5890 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005891 continue;
5892 }
5893
5894 // OpenMP [2.14.4.2, Restrictions, p.2]
5895 // A list item that appears in a copyprivate clause may not appear in a
5896 // private or firstprivate clause on the single construct.
5897 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005898 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00005899 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
5900 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00005901 Diag(ELoc, diag::err_omp_wrong_dsa)
5902 << getOpenMPClauseName(DVar.CKind)
5903 << getOpenMPClauseName(OMPC_copyprivate);
5904 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5905 continue;
5906 }
5907
5908 // OpenMP [2.11.4.2, Restrictions, p.1]
5909 // All list items that appear in a copyprivate clause must be either
5910 // threadprivate or private in the enclosing context.
5911 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005912 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005913 if (DVar.CKind == OMPC_shared) {
5914 Diag(ELoc, diag::err_omp_required_access)
5915 << getOpenMPClauseName(OMPC_copyprivate)
5916 << "threadprivate or private in the enclosing context";
5917 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5918 continue;
5919 }
5920 }
5921 }
5922
5923 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5924 // A variable of class type (or array thereof) that appears in a
5925 // copyin clause requires an accessible, unambiguous copy assignment
5926 // operator for the class type.
Alexey Bataeva63048e2015-03-23 06:18:07 +00005927 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(), VD->getType(),
5928 ".copyprivate.src");
5929 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, DE->getType(), VK_LValue,
5930 DE->getExprLoc()).get();
5931 auto *DstVD = BuildVarDecl(*this, DE->getLocStart(), VD->getType(),
5932 ".copyprivate.dst");
5933 auto *PseudoDstExpr = BuildDeclRefExpr(DstVD, DE->getType(), VK_LValue,
5934 DE->getExprLoc()).get();
5935 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5936 PseudoDstExpr, PseudoSrcExpr);
5937 if (AssignmentOp.isInvalid())
5938 continue;
5939 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5940 /*DiscardedValue=*/true);
5941 if (AssignmentOp.isInvalid())
5942 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005943
5944 // No need to mark vars as copyprivate, they are already threadprivate or
5945 // implicitly private.
5946 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00005947 SrcExprs.push_back(PseudoSrcExpr);
5948 DstExprs.push_back(PseudoDstExpr);
5949 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00005950 }
5951
5952 if (Vars.empty())
5953 return nullptr;
5954
Alexey Bataeva63048e2015-03-23 06:18:07 +00005955 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5956 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00005957}
5958
Alexey Bataev6125da92014-07-21 11:26:11 +00005959OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
5960 SourceLocation StartLoc,
5961 SourceLocation LParenLoc,
5962 SourceLocation EndLoc) {
5963 if (VarList.empty())
5964 return nullptr;
5965
5966 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
5967}
Alexey Bataevdea47612014-07-23 07:46:59 +00005968