blob: fed0ac77b8472b0820d3118ef58760967c643e6b [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) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000241 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000242 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000243 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000244 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
245 // in a region but not in construct]
246 // File-scope or namespace-scope variables referenced in called routines
247 // in the region are shared unless they appear in a threadprivate
248 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000249 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000250 DVar.CKind = OMPC_shared;
251
252 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
253 // in a region but not in construct]
254 // Variables with static storage duration that are declared in called
255 // routines in the region are shared.
256 if (D->hasGlobalStorage())
257 DVar.CKind = OMPC_shared;
258
Alexey Bataev758e55e2013-09-06 18:03:48 +0000259 return DVar;
260 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000261
Alexey Bataev758e55e2013-09-06 18:03:48 +0000262 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000263 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
264 // in a Construct, C/C++, predetermined, p.1]
265 // Variables with automatic storage duration that are declared in a scope
266 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000267 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
268 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
269 DVar.CKind = OMPC_private;
270 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000271 }
272
Alexey Bataev758e55e2013-09-06 18:03:48 +0000273 // Explicitly specified attributes and local variables with predetermined
274 // attributes.
275 if (Iter->SharingMap.count(D)) {
276 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
277 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000278 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000279 return DVar;
280 }
281
282 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
283 // in a Construct, C/C++, implicitly determined, p.1]
284 // In a parallel or task construct, the data-sharing attributes of these
285 // variables are determined by the default clause, if present.
286 switch (Iter->DefaultAttr) {
287 case DSA_shared:
288 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000289 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 return DVar;
291 case DSA_none:
292 return DVar;
293 case DSA_unspecified:
294 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
295 // in a Construct, implicitly determined, p.2]
296 // In a parallel construct, if no default clause is present, these
297 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000298 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000299 if (isOpenMPParallelDirective(DVar.DKind) ||
300 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000301 DVar.CKind = OMPC_shared;
302 return DVar;
303 }
304
305 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
306 // in a Construct, implicitly determined, p.4]
307 // In a task construct, if no default clause is present, a variable that in
308 // the enclosing context is determined to be shared by all implicit tasks
309 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000310 if (DVar.DKind == OMPD_task) {
311 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000312 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000313 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000314 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
315 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000316 // in a Construct, implicitly determined, p.6]
317 // In a task construct, if no default clause is present, a variable
318 // whose data-sharing attribute is not determined by the rules above is
319 // firstprivate.
320 DVarTemp = getDSA(I, D);
321 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000322 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000323 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000324 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000325 return DVar;
326 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000327 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000328 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000329 }
330 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000331 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000332 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000333 return DVar;
334 }
335 }
336 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
337 // in a Construct, implicitly determined, p.3]
338 // For constructs other than task, if no default clause is present, these
339 // variables inherit their data-sharing attributes from the enclosing
340 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000341 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000342}
343
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000344DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
345 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000346 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000347 auto It = Stack.back().AlignedMap.find(D);
348 if (It == Stack.back().AlignedMap.end()) {
349 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
350 Stack.back().AlignedMap[D] = NewDE;
351 return nullptr;
352 } else {
353 assert(It->second && "Unexpected nullptr expr in the aligned map");
354 return It->second;
355 }
356 return nullptr;
357}
358
Alexey Bataev758e55e2013-09-06 18:03:48 +0000359void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000360 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000361 if (A == OMPC_threadprivate) {
362 Stack[0].SharingMap[D].Attributes = A;
363 Stack[0].SharingMap[D].RefExpr = E;
364 } else {
365 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
366 Stack.back().SharingMap[D].Attributes = A;
367 Stack.back().SharingMap[D].RefExpr = E;
368 }
369}
370
Alexey Bataeved09d242014-05-28 05:53:51 +0000371bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000372 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000373 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000374 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000375 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000376 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000377 ++I;
378 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000379 if (I == E)
380 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000381 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000382 Scope *CurScope = getCurScope();
383 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000384 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000385 }
386 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000387 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000388 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000389}
390
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000391DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000392 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000393 DSAVarData DVar;
394
395 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
396 // in a Construct, C/C++, predetermined, p.1]
397 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000398 if (D->getTLSKind() != VarDecl::TLS_None ||
399 D->getStorageClass() == SC_Register) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000400 DVar.CKind = OMPC_threadprivate;
401 return DVar;
402 }
403 if (Stack[0].SharingMap.count(D)) {
404 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
405 DVar.CKind = OMPC_threadprivate;
406 return DVar;
407 }
408
409 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
410 // in a Construct, C/C++, predetermined, p.1]
411 // Variables with automatic storage duration that are declared in a scope
412 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000413 OpenMPDirectiveKind Kind =
414 FromParent ? getParentDirective() : getCurrentDirective();
415 auto StartI = std::next(Stack.rbegin());
416 auto EndI = std::prev(Stack.rend());
417 if (FromParent && StartI != EndI) {
418 StartI = std::next(StartI);
419 }
420 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000421 if (isOpenMPLocal(D, StartI) &&
422 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
423 D->getStorageClass() == SC_None)) ||
424 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000425 DVar.CKind = OMPC_private;
426 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000427 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000428
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000429 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
430 // in a Construct, C/C++, predetermined, p.4]
431 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000432 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
433 // in a Construct, C/C++, predetermined, p.7]
434 // Variables with static storage duration that are declared in a scope
435 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000436 if (D->isStaticDataMember() || D->isStaticLocal()) {
437 DSAVarData DVarTemp =
438 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
439 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
440 return DVar;
441
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000442 DVar.CKind = OMPC_shared;
443 return DVar;
444 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000445 }
446
447 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000448 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
Alexey Bataev758e55e2013-09-06 18:03:48 +0000449 while (Type->isArrayType()) {
450 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
451 Type = ElemType.getNonReferenceType().getCanonicalType();
452 }
453 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
454 // in a Construct, C/C++, predetermined, p.6]
455 // Variables with const qualified type having no mutable member are
456 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000457 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000458 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000459 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000460 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000461 // Variables with const-qualified type having no mutable member may be
462 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000463 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
464 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000465 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
466 return DVar;
467
Alexey Bataev758e55e2013-09-06 18:03:48 +0000468 DVar.CKind = OMPC_shared;
469 return DVar;
470 }
471
Alexey Bataev758e55e2013-09-06 18:03:48 +0000472 // Explicitly specified attributes and local variables with predetermined
473 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000474 auto I = std::prev(StartI);
475 if (I->SharingMap.count(D)) {
476 DVar.RefExpr = I->SharingMap[D].RefExpr;
477 DVar.CKind = I->SharingMap[D].Attributes;
478 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000479 }
480
481 return DVar;
482}
483
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000484DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000485 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000486 auto StartI = Stack.rbegin();
487 auto EndI = std::prev(Stack.rend());
488 if (FromParent && StartI != EndI) {
489 StartI = std::next(StartI);
490 }
491 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492}
493
Alexey Bataevf29276e2014-06-18 04:14:57 +0000494template <class ClausesPredicate, class DirectivesPredicate>
495DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000496 DirectivesPredicate DPred,
497 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000498 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000499 auto StartI = std::next(Stack.rbegin());
500 auto EndI = std::prev(Stack.rend());
501 if (FromParent && StartI != EndI) {
502 StartI = std::next(StartI);
503 }
504 for (auto I = StartI, EE = EndI; I != EE; ++I) {
505 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000506 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000507 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000508 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000509 return DVar;
510 }
511 return DSAVarData();
512}
513
Alexey Bataevf29276e2014-06-18 04:14:57 +0000514template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000515DSAStackTy::DSAVarData
516DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
517 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000518 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000519 auto StartI = std::next(Stack.rbegin());
520 auto EndI = std::prev(Stack.rend());
521 if (FromParent && StartI != EndI) {
522 StartI = std::next(StartI);
523 }
524 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000525 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000526 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000527 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000528 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000529 return DVar;
530 return DSAVarData();
531 }
532 return DSAVarData();
533}
534
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000535template <class NamedDirectivesPredicate>
536bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
537 auto StartI = std::next(Stack.rbegin());
538 auto EndI = std::prev(Stack.rend());
539 if (FromParent && StartI != EndI) {
540 StartI = std::next(StartI);
541 }
542 for (auto I = StartI, EE = EndI; I != EE; ++I) {
543 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
544 return true;
545 }
546 return false;
547}
548
Alexey Bataev758e55e2013-09-06 18:03:48 +0000549void Sema::InitDataSharingAttributesStack() {
550 VarDataSharingAttributesStack = new DSAStackTy(*this);
551}
552
553#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
554
Alexey Bataevf841bd92014-12-16 07:00:22 +0000555bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
556 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000557 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000558 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
559 auto DVarPrivate = DSAStack->getTopDSA(VD, /*FromParent=*/false);
560 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
561 return true;
562 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
563 /*FromParent=*/false);
564 return DVarPrivate.CKind != OMPC_unknown;
565 }
566 return false;
567}
568
Alexey Bataeved09d242014-05-28 05:53:51 +0000569void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000570
571void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
572 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000573 Scope *CurScope, SourceLocation Loc) {
574 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000575 PushExpressionEvaluationContext(PotentiallyEvaluated);
576}
577
578void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000579 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
580 // A variable of class type (or array thereof) that appears in a lastprivate
581 // clause requires an accessible, unambiguous default constructor for the
582 // class type, unless the list item is also specified in a firstprivate
583 // clause.
584 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000585 for (auto *C : D->clauses()) {
586 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
587 SmallVector<Expr *, 8> PrivateCopies;
588 for (auto *DE : Clause->varlists()) {
589 if (DE->isValueDependent() || DE->isTypeDependent()) {
590 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000591 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000592 }
593 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000594 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000595 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000596 // Generate helper private variable and initialize it with the
597 // default value. The address of the original variable is replaced
598 // by the address of the new private variable in CodeGen. This new
599 // variable is not added to IdResolver, so the code in the OpenMP
600 // region uses original variable for proper diagnostics.
601 auto *VDPrivate = VarDecl::Create(
602 Context, CurContext, DE->getLocStart(), DE->getExprLoc(),
603 VD->getIdentifier(), VD->getType(), VD->getTypeSourceInfo(),
604 SC_Auto);
605 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
606 if (VDPrivate->isInvalidDecl())
607 continue;
608 CurContext->addDecl(VDPrivate);
609 PrivateCopies.push_back(DeclRefExpr::Create(
610 Context, NestedNameSpecifierLoc(), SourceLocation(), VDPrivate,
611 /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
612 DE->getType(), VK_LValue));
613 } else {
614 // The variable is also a firstprivate, so initialization sequence
615 // for private copy is generated already.
616 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000617 }
618 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000619 // Set initializers to private copies if no errors were found.
620 if (PrivateCopies.size() == Clause->varlist_size()) {
621 Clause->setPrivateCopies(PrivateCopies);
622 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000623 }
624 }
625 }
626
Alexey Bataev758e55e2013-09-06 18:03:48 +0000627 DSAStack->pop();
628 DiscardCleanupsInEvaluationContext();
629 PopExpressionEvaluationContext();
630}
631
Alexander Musman3276a272015-03-21 10:12:56 +0000632static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
633 Expr *NumIterations, Sema &SemaRef,
634 Scope *S);
635
Alexey Bataeva769e072013-03-22 06:34:35 +0000636namespace {
637
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000638class VarDeclFilterCCC : public CorrectionCandidateCallback {
639private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000640 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000641
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000642public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000643 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000644 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000645 NamedDecl *ND = Candidate.getCorrectionDecl();
646 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
647 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000648 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
649 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000650 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000651 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000652 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000653};
Alexey Bataeved09d242014-05-28 05:53:51 +0000654} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000655
656ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
657 CXXScopeSpec &ScopeSpec,
658 const DeclarationNameInfo &Id) {
659 LookupResult Lookup(*this, Id, LookupOrdinaryName);
660 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
661
662 if (Lookup.isAmbiguous())
663 return ExprError();
664
665 VarDecl *VD;
666 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000667 if (TypoCorrection Corrected = CorrectTypo(
668 Id, LookupOrdinaryName, CurScope, nullptr,
669 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000670 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000671 PDiag(Lookup.empty()
672 ? diag::err_undeclared_var_use_suggest
673 : diag::err_omp_expected_var_arg_suggest)
674 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000675 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000676 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000677 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
678 : diag::err_omp_expected_var_arg)
679 << Id.getName();
680 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000681 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000682 } else {
683 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000684 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000685 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
686 return ExprError();
687 }
688 }
689 Lookup.suppressDiagnostics();
690
691 // OpenMP [2.9.2, Syntax, C/C++]
692 // Variables must be file-scope, namespace-scope, or static block-scope.
693 if (!VD->hasGlobalStorage()) {
694 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000695 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
696 bool IsDecl =
697 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000698 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000699 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
700 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000701 return ExprError();
702 }
703
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000704 VarDecl *CanonicalVD = VD->getCanonicalDecl();
705 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000706 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
707 // A threadprivate directive for file-scope variables must appear outside
708 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000709 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
710 !getCurLexicalContext()->isTranslationUnit()) {
711 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000712 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
713 bool IsDecl =
714 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
715 Diag(VD->getLocation(),
716 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
717 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000718 return ExprError();
719 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000720 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
721 // A threadprivate directive for static class member variables must appear
722 // in the class definition, in the same scope in which the member
723 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000724 if (CanonicalVD->isStaticDataMember() &&
725 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
726 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000727 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
728 bool IsDecl =
729 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
730 Diag(VD->getLocation(),
731 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
732 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000733 return ExprError();
734 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000735 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
736 // A threadprivate directive for namespace-scope variables must appear
737 // outside any definition or declaration other than the namespace
738 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000739 if (CanonicalVD->getDeclContext()->isNamespace() &&
740 (!getCurLexicalContext()->isFileContext() ||
741 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
742 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000743 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
744 bool IsDecl =
745 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
746 Diag(VD->getLocation(),
747 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
748 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000749 return ExprError();
750 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000751 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
752 // A threadprivate directive for static block-scope variables must appear
753 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000754 if (CanonicalVD->isStaticLocal() && CurScope &&
755 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000756 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000757 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
758 bool IsDecl =
759 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
760 Diag(VD->getLocation(),
761 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
762 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000763 return ExprError();
764 }
765
766 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
767 // A threadprivate directive must lexically precede all references to any
768 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000769 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000770 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000771 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000772 return ExprError();
773 }
774
775 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataevd178ad42014-03-07 08:03:37 +0000776 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000777 return DE;
778}
779
Alexey Bataeved09d242014-05-28 05:53:51 +0000780Sema::DeclGroupPtrTy
781Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
782 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000783 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000784 CurContext->addDecl(D);
785 return DeclGroupPtrTy::make(DeclGroupRef(D));
786 }
787 return DeclGroupPtrTy();
788}
789
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000790namespace {
791class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
792 Sema &SemaRef;
793
794public:
795 bool VisitDeclRefExpr(const DeclRefExpr *E) {
796 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
797 if (VD->hasLocalStorage()) {
798 SemaRef.Diag(E->getLocStart(),
799 diag::err_omp_local_var_in_threadprivate_init)
800 << E->getSourceRange();
801 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
802 << VD << VD->getSourceRange();
803 return true;
804 }
805 }
806 return false;
807 }
808 bool VisitStmt(const Stmt *S) {
809 for (auto Child : S->children()) {
810 if (Child && Visit(Child))
811 return true;
812 }
813 return false;
814 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000815 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000816};
817} // namespace
818
Alexey Bataeved09d242014-05-28 05:53:51 +0000819OMPThreadPrivateDecl *
820Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000821 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000822 for (auto &RefExpr : VarList) {
823 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000824 VarDecl *VD = cast<VarDecl>(DE->getDecl());
825 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000826
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000827 QualType QType = VD->getType();
828 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
829 // It will be analyzed later.
830 Vars.push_back(DE);
831 continue;
832 }
833
Alexey Bataeva769e072013-03-22 06:34:35 +0000834 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
835 // A threadprivate variable must not have an incomplete type.
836 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000837 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000838 continue;
839 }
840
841 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
842 // A threadprivate variable must not have a reference type.
843 if (VD->getType()->isReferenceType()) {
844 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000845 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
846 bool IsDecl =
847 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
848 Diag(VD->getLocation(),
849 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
850 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000851 continue;
852 }
853
Richard Smithfd3834f2013-04-13 02:43:54 +0000854 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000855 if (VD->getTLSKind() != VarDecl::TLS_None ||
856 VD->getStorageClass() == SC_Register) {
857 Diag(ILoc, diag::err_omp_var_thread_local)
858 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000859 bool IsDecl =
860 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
861 Diag(VD->getLocation(),
862 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
863 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000864 continue;
865 }
866
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000867 // Check if initial value of threadprivate variable reference variable with
868 // local storage (it is not supported by runtime).
869 if (auto Init = VD->getAnyInitializer()) {
870 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000871 if (Checker.Visit(Init))
872 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000873 }
874
Alexey Bataeved09d242014-05-28 05:53:51 +0000875 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000876 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000877 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
878 Context, SourceRange(Loc, Loc)));
879 if (auto *ML = Context.getASTMutationListener())
880 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000881 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000882 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000883 if (!Vars.empty()) {
884 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
885 Vars);
886 D->setAccess(AS_public);
887 }
888 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000889}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000890
Alexey Bataev7ff55242014-06-19 09:13:45 +0000891static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
892 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
893 bool IsLoopIterVar = false) {
894 if (DVar.RefExpr) {
895 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
896 << getOpenMPClauseName(DVar.CKind);
897 return;
898 }
899 enum {
900 PDSA_StaticMemberShared,
901 PDSA_StaticLocalVarShared,
902 PDSA_LoopIterVarPrivate,
903 PDSA_LoopIterVarLinear,
904 PDSA_LoopIterVarLastprivate,
905 PDSA_ConstVarShared,
906 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000907 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000908 PDSA_LocalVarPrivate,
909 PDSA_Implicit
910 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000911 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000912 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000913 if (IsLoopIterVar) {
914 if (DVar.CKind == OMPC_private)
915 Reason = PDSA_LoopIterVarPrivate;
916 else if (DVar.CKind == OMPC_lastprivate)
917 Reason = PDSA_LoopIterVarLastprivate;
918 else
919 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000920 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
921 Reason = PDSA_TaskVarFirstprivate;
922 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000923 } else if (VD->isStaticLocal())
924 Reason = PDSA_StaticLocalVarShared;
925 else if (VD->isStaticDataMember())
926 Reason = PDSA_StaticMemberShared;
927 else if (VD->isFileVarDecl())
928 Reason = PDSA_GlobalVarShared;
929 else if (VD->getType().isConstant(SemaRef.getASTContext()))
930 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000931 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000932 ReportHint = true;
933 Reason = PDSA_LocalVarPrivate;
934 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000935 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000936 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +0000937 << Reason << ReportHint
938 << getOpenMPDirectiveName(Stack->getCurrentDirective());
939 } else if (DVar.ImplicitDSALoc.isValid()) {
940 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
941 << getOpenMPClauseName(DVar.CKind);
942 }
Alexey Bataev7ff55242014-06-19 09:13:45 +0000943}
944
Alexey Bataev758e55e2013-09-06 18:03:48 +0000945namespace {
946class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
947 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000948 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000949 bool ErrorFound;
950 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000951 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +0000952 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +0000953
Alexey Bataev758e55e2013-09-06 18:03:48 +0000954public:
955 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000956 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000957 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +0000958 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
959 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000960
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000961 auto DVar = Stack->getTopDSA(VD, false);
962 // Check if the variable has explicit DSA set and stop analysis if it so.
963 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000964
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000965 auto ELoc = E->getExprLoc();
966 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000967 // The default(none) clause requires that each variable that is referenced
968 // in the construct, and does not have a predetermined data-sharing
969 // attribute, must have its data-sharing attribute explicitly determined
970 // by being listed in a data-sharing attribute clause.
971 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000972 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +0000973 VarsWithInheritedDSA.count(VD) == 0) {
974 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 return;
976 }
977
978 // OpenMP [2.9.3.6, Restrictions, p.2]
979 // A list item that appears in a reduction clause of the innermost
980 // enclosing worksharing or parallel construct may not be accessed in an
981 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000982 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000983 [](OpenMPDirectiveKind K) -> bool {
984 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000985 isOpenMPWorksharingDirective(K) ||
986 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000987 },
988 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000989 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
990 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000991 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
992 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +0000993 return;
994 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000995
996 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000997 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000998 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000999 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001000 }
1001 }
1002 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001003 for (auto *C : S->clauses()) {
1004 // Skip analysis of arguments of implicitly defined firstprivate clause
1005 // for task directives.
1006 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1007 for (auto *CC : C->children()) {
1008 if (CC)
1009 Visit(CC);
1010 }
1011 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001012 }
1013 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001014 for (auto *C : S->children()) {
1015 if (C && !isa<OMPExecutableDirective>(C))
1016 Visit(C);
1017 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001018 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001019
1020 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001021 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001022 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1023 return VarsWithInheritedDSA;
1024 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001025
Alexey Bataev7ff55242014-06-19 09:13:45 +00001026 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1027 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001028};
Alexey Bataeved09d242014-05-28 05:53:51 +00001029} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001030
Alexey Bataevbae9a792014-06-27 10:37:06 +00001031void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001032 switch (DKind) {
1033 case OMPD_parallel: {
1034 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1035 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001036 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001037 std::make_pair(".global_tid.", KmpInt32PtrTy),
1038 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1039 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001040 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001041 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1042 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001043 break;
1044 }
1045 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001046 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001047 std::make_pair(StringRef(), QualType()) // __context with shared vars
1048 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001049 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1050 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001051 break;
1052 }
1053 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001054 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001055 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001056 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001057 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1058 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001059 break;
1060 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001061 case OMPD_for_simd: {
1062 Sema::CapturedParamNameType Params[] = {
1063 std::make_pair(StringRef(), QualType()) // __context with shared vars
1064 };
1065 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1066 Params);
1067 break;
1068 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001069 case OMPD_sections: {
1070 Sema::CapturedParamNameType Params[] = {
1071 std::make_pair(StringRef(), QualType()) // __context with shared vars
1072 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001073 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1074 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001075 break;
1076 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001077 case OMPD_section: {
1078 Sema::CapturedParamNameType Params[] = {
1079 std::make_pair(StringRef(), QualType()) // __context with shared vars
1080 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001081 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1082 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001083 break;
1084 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001085 case OMPD_single: {
1086 Sema::CapturedParamNameType Params[] = {
1087 std::make_pair(StringRef(), QualType()) // __context with shared vars
1088 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001089 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1090 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001091 break;
1092 }
Alexander Musman80c22892014-07-17 08:54:58 +00001093 case OMPD_master: {
1094 Sema::CapturedParamNameType Params[] = {
1095 std::make_pair(StringRef(), QualType()) // __context with shared vars
1096 };
1097 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1098 Params);
1099 break;
1100 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001101 case OMPD_critical: {
1102 Sema::CapturedParamNameType Params[] = {
1103 std::make_pair(StringRef(), QualType()) // __context with shared vars
1104 };
1105 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1106 Params);
1107 break;
1108 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001109 case OMPD_parallel_for: {
1110 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1111 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1112 Sema::CapturedParamNameType Params[] = {
1113 std::make_pair(".global_tid.", KmpInt32PtrTy),
1114 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1115 std::make_pair(StringRef(), QualType()) // __context with shared vars
1116 };
1117 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1118 Params);
1119 break;
1120 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001121 case OMPD_parallel_for_simd: {
1122 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1123 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1124 Sema::CapturedParamNameType Params[] = {
1125 std::make_pair(".global_tid.", KmpInt32PtrTy),
1126 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1127 std::make_pair(StringRef(), QualType()) // __context with shared vars
1128 };
1129 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1130 Params);
1131 break;
1132 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001133 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001134 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1135 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001136 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001137 std::make_pair(".global_tid.", KmpInt32PtrTy),
1138 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001139 std::make_pair(StringRef(), QualType()) // __context with shared vars
1140 };
1141 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1142 Params);
1143 break;
1144 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001145 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001146 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001147 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001148 std::make_pair(".global_tid.", KmpInt32Ty),
1149 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001150 std::make_pair(StringRef(), QualType()) // __context with shared vars
1151 };
1152 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1153 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001154 // Mark this captured region as inlined, because we don't use outlined
1155 // function directly.
1156 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1157 AlwaysInlineAttr::CreateImplicit(
1158 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001159 break;
1160 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001161 case OMPD_ordered: {
1162 Sema::CapturedParamNameType Params[] = {
1163 std::make_pair(StringRef(), QualType()) // __context with shared vars
1164 };
1165 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1166 Params);
1167 break;
1168 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001169 case OMPD_atomic: {
1170 Sema::CapturedParamNameType Params[] = {
1171 std::make_pair(StringRef(), QualType()) // __context with shared vars
1172 };
1173 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1174 Params);
1175 break;
1176 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001177 case OMPD_target: {
1178 Sema::CapturedParamNameType Params[] = {
1179 std::make_pair(StringRef(), QualType()) // __context with shared vars
1180 };
1181 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1182 Params);
1183 break;
1184 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001185 case OMPD_teams: {
1186 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1187 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1188 Sema::CapturedParamNameType Params[] = {
1189 std::make_pair(".global_tid.", KmpInt32PtrTy),
1190 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1191 std::make_pair(StringRef(), QualType()) // __context with shared vars
1192 };
1193 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1194 Params);
1195 break;
1196 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001197 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001198 case OMPD_taskyield:
1199 case OMPD_barrier:
1200 case OMPD_taskwait:
1201 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001202 llvm_unreachable("OpenMP Directive is not allowed");
1203 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001204 llvm_unreachable("Unknown OpenMP directive");
1205 }
1206}
1207
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001208StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1209 ArrayRef<OMPClause *> Clauses) {
1210 if (!S.isUsable()) {
1211 ActOnCapturedRegionError();
1212 return StmtError();
1213 }
1214 // Mark all variables in private list clauses as used in inner region. This is
1215 // required for proper codegen.
1216 for (auto *Clause : Clauses) {
1217 if (isOpenMPPrivate(Clause->getClauseKind())) {
1218 for (auto *VarRef : Clause->children()) {
1219 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001220 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001221 }
1222 }
1223 }
1224 }
1225 return ActOnCapturedRegionEnd(S.get());
1226}
1227
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001228static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1229 OpenMPDirectiveKind CurrentRegion,
1230 const DeclarationNameInfo &CurrentName,
1231 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001232 // Allowed nesting of constructs
1233 // +------------------+-----------------+------------------------------------+
1234 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1235 // +------------------+-----------------+------------------------------------+
1236 // | parallel | parallel | * |
1237 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001238 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001239 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001240 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001241 // | parallel | simd | * |
1242 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001243 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001244 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001245 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001246 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001247 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001248 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001249 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001250 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001251 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001252 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001253 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001254 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001255 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001256 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001257 // +------------------+-----------------+------------------------------------+
1258 // | for | parallel | * |
1259 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001260 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001261 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001262 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001263 // | for | simd | * |
1264 // | for | sections | + |
1265 // | for | section | + |
1266 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001267 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001268 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001269 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001270 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001271 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001272 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001273 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001274 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001275 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001276 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001277 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001278 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001279 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001280 // | master | parallel | * |
1281 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001282 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001283 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001284 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001285 // | master | simd | * |
1286 // | master | sections | + |
1287 // | master | section | + |
1288 // | master | single | + |
1289 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001290 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001291 // | master |parallel sections| * |
1292 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001293 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001294 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001295 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001296 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001297 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001298 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001299 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001300 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001301 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001302 // | critical | parallel | * |
1303 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001304 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001305 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001306 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001307 // | critical | simd | * |
1308 // | critical | sections | + |
1309 // | critical | section | + |
1310 // | critical | single | + |
1311 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001312 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001313 // | critical |parallel sections| * |
1314 // | critical | task | * |
1315 // | critical | taskyield | * |
1316 // | critical | barrier | + |
1317 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001318 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001319 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001320 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001321 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001322 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001323 // | simd | parallel | |
1324 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001325 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001326 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001327 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001328 // | simd | simd | |
1329 // | simd | sections | |
1330 // | simd | section | |
1331 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001332 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001333 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001334 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001335 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001336 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001337 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001338 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001339 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001340 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001341 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001342 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001343 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001344 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001345 // | for simd | parallel | |
1346 // | for simd | for | |
1347 // | for simd | for simd | |
1348 // | for simd | master | |
1349 // | for simd | critical | |
1350 // | for simd | simd | |
1351 // | for simd | sections | |
1352 // | for simd | section | |
1353 // | for simd | single | |
1354 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001355 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001356 // | for simd |parallel sections| |
1357 // | for simd | task | |
1358 // | for simd | taskyield | |
1359 // | for simd | barrier | |
1360 // | for simd | taskwait | |
1361 // | for simd | flush | |
1362 // | for simd | ordered | |
1363 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001364 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001365 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001366 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001367 // | parallel for simd| parallel | |
1368 // | parallel for simd| for | |
1369 // | parallel for simd| for simd | |
1370 // | parallel for simd| master | |
1371 // | parallel for simd| critical | |
1372 // | parallel for simd| simd | |
1373 // | parallel for simd| sections | |
1374 // | parallel for simd| section | |
1375 // | parallel for simd| single | |
1376 // | parallel for simd| parallel for | |
1377 // | parallel for simd|parallel for simd| |
1378 // | parallel for simd|parallel sections| |
1379 // | parallel for simd| task | |
1380 // | parallel for simd| taskyield | |
1381 // | parallel for simd| barrier | |
1382 // | parallel for simd| taskwait | |
1383 // | parallel for simd| flush | |
1384 // | parallel for simd| ordered | |
1385 // | parallel for simd| atomic | |
1386 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001387 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001388 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001389 // | sections | parallel | * |
1390 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001391 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001392 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001393 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001394 // | sections | simd | * |
1395 // | sections | sections | + |
1396 // | sections | section | * |
1397 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001398 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001399 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001400 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001401 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001402 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001403 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001404 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001405 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001406 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001407 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001408 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001409 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001410 // +------------------+-----------------+------------------------------------+
1411 // | section | parallel | * |
1412 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001413 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001414 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001415 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001416 // | section | simd | * |
1417 // | section | sections | + |
1418 // | section | section | + |
1419 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001420 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001421 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001422 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001423 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001424 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001425 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001426 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001427 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001428 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001429 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001430 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001431 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001432 // +------------------+-----------------+------------------------------------+
1433 // | single | parallel | * |
1434 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001435 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001436 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001437 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001438 // | single | simd | * |
1439 // | single | sections | + |
1440 // | single | section | + |
1441 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001442 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001443 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001444 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001445 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001446 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001447 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001448 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001449 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001450 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001451 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001452 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001453 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001454 // +------------------+-----------------+------------------------------------+
1455 // | parallel for | parallel | * |
1456 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001457 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001458 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001459 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001460 // | parallel for | simd | * |
1461 // | parallel for | sections | + |
1462 // | parallel for | section | + |
1463 // | parallel for | single | + |
1464 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001465 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001466 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001467 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001468 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001469 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001470 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001471 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001472 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001473 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001474 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001475 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001476 // +------------------+-----------------+------------------------------------+
1477 // | parallel sections| parallel | * |
1478 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001479 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001480 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001481 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001482 // | parallel sections| simd | * |
1483 // | parallel sections| sections | + |
1484 // | parallel sections| section | * |
1485 // | parallel sections| single | + |
1486 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001487 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001488 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001490 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001491 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001492 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001493 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001494 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001495 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001496 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001497 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001498 // +------------------+-----------------+------------------------------------+
1499 // | task | parallel | * |
1500 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001501 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001502 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001503 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001504 // | task | simd | * |
1505 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001506 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001507 // | task | single | + |
1508 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001509 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001510 // | task |parallel sections| * |
1511 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001512 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001513 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001514 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001515 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001516 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001517 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001518 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001519 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001520 // +------------------+-----------------+------------------------------------+
1521 // | ordered | parallel | * |
1522 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001523 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001524 // | ordered | master | * |
1525 // | ordered | critical | * |
1526 // | ordered | simd | * |
1527 // | ordered | sections | + |
1528 // | ordered | section | + |
1529 // | ordered | single | + |
1530 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001531 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001532 // | ordered |parallel sections| * |
1533 // | ordered | task | * |
1534 // | ordered | taskyield | * |
1535 // | ordered | barrier | + |
1536 // | ordered | taskwait | * |
1537 // | ordered | flush | * |
1538 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001539 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001540 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001541 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001542 // +------------------+-----------------+------------------------------------+
1543 // | atomic | parallel | |
1544 // | atomic | for | |
1545 // | atomic | for simd | |
1546 // | atomic | master | |
1547 // | atomic | critical | |
1548 // | atomic | simd | |
1549 // | atomic | sections | |
1550 // | atomic | section | |
1551 // | atomic | single | |
1552 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001553 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001554 // | atomic |parallel sections| |
1555 // | atomic | task | |
1556 // | atomic | taskyield | |
1557 // | atomic | barrier | |
1558 // | atomic | taskwait | |
1559 // | atomic | flush | |
1560 // | atomic | ordered | |
1561 // | atomic | atomic | |
1562 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001563 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001564 // +------------------+-----------------+------------------------------------+
1565 // | target | parallel | * |
1566 // | target | for | * |
1567 // | target | for simd | * |
1568 // | target | master | * |
1569 // | target | critical | * |
1570 // | target | simd | * |
1571 // | target | sections | * |
1572 // | target | section | * |
1573 // | target | single | * |
1574 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001575 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001576 // | target |parallel sections| * |
1577 // | target | task | * |
1578 // | target | taskyield | * |
1579 // | target | barrier | * |
1580 // | target | taskwait | * |
1581 // | target | flush | * |
1582 // | target | ordered | * |
1583 // | target | atomic | * |
1584 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001585 // | target | teams | * |
1586 // +------------------+-----------------+------------------------------------+
1587 // | teams | parallel | * |
1588 // | teams | for | + |
1589 // | teams | for simd | + |
1590 // | teams | master | + |
1591 // | teams | critical | + |
1592 // | teams | simd | + |
1593 // | teams | sections | + |
1594 // | teams | section | + |
1595 // | teams | single | + |
1596 // | teams | parallel for | * |
1597 // | teams |parallel for simd| * |
1598 // | teams |parallel sections| * |
1599 // | teams | task | + |
1600 // | teams | taskyield | + |
1601 // | teams | barrier | + |
1602 // | teams | taskwait | + |
1603 // | teams | flush | + |
1604 // | teams | ordered | + |
1605 // | teams | atomic | + |
1606 // | teams | target | + |
1607 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001608 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001609 if (Stack->getCurScope()) {
1610 auto ParentRegion = Stack->getParentDirective();
1611 bool NestingProhibited = false;
1612 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001613 enum {
1614 NoRecommend,
1615 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001616 ShouldBeInOrderedRegion,
1617 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001618 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001619 if (isOpenMPSimdDirective(ParentRegion)) {
1620 // OpenMP [2.16, Nesting of Regions]
1621 // OpenMP constructs may not be nested inside a simd region.
1622 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1623 return true;
1624 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001625 if (ParentRegion == OMPD_atomic) {
1626 // OpenMP [2.16, Nesting of Regions]
1627 // OpenMP constructs may not be nested inside an atomic region.
1628 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1629 return true;
1630 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001631 if (CurrentRegion == OMPD_section) {
1632 // OpenMP [2.7.2, sections Construct, Restrictions]
1633 // Orphaned section directives are prohibited. That is, the section
1634 // directives must appear within the sections construct and must not be
1635 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001636 if (ParentRegion != OMPD_sections &&
1637 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001638 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1639 << (ParentRegion != OMPD_unknown)
1640 << getOpenMPDirectiveName(ParentRegion);
1641 return true;
1642 }
1643 return false;
1644 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001645 // Allow some constructs to be orphaned (they could be used in functions,
1646 // called from OpenMP regions with the required preconditions).
1647 if (ParentRegion == OMPD_unknown)
1648 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001649 if (CurrentRegion == OMPD_master) {
1650 // OpenMP [2.16, Nesting of Regions]
1651 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001652 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001653 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1654 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001655 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1656 // OpenMP [2.16, Nesting of Regions]
1657 // A critical region may not be nested (closely or otherwise) inside a
1658 // critical region with the same name. Note that this restriction is not
1659 // sufficient to prevent deadlock.
1660 SourceLocation PreviousCriticalLoc;
1661 bool DeadLock =
1662 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1663 OpenMPDirectiveKind K,
1664 const DeclarationNameInfo &DNI,
1665 SourceLocation Loc)
1666 ->bool {
1667 if (K == OMPD_critical &&
1668 DNI.getName() == CurrentName.getName()) {
1669 PreviousCriticalLoc = Loc;
1670 return true;
1671 } else
1672 return false;
1673 },
1674 false /* skip top directive */);
1675 if (DeadLock) {
1676 SemaRef.Diag(StartLoc,
1677 diag::err_omp_prohibited_region_critical_same_name)
1678 << CurrentName.getName();
1679 if (PreviousCriticalLoc.isValid())
1680 SemaRef.Diag(PreviousCriticalLoc,
1681 diag::note_omp_previous_critical_region);
1682 return true;
1683 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001684 } else if (CurrentRegion == OMPD_barrier) {
1685 // OpenMP [2.16, Nesting of Regions]
1686 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001687 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001688 NestingProhibited =
1689 isOpenMPWorksharingDirective(ParentRegion) ||
1690 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1691 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001692 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001693 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001694 // OpenMP [2.16, Nesting of Regions]
1695 // A worksharing region may not be closely nested inside a worksharing,
1696 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001697 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001698 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001699 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1700 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1701 Recommend = ShouldBeInParallelRegion;
1702 } else if (CurrentRegion == OMPD_ordered) {
1703 // OpenMP [2.16, Nesting of Regions]
1704 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001705 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001706 // An ordered region must be closely nested inside a loop region (or
1707 // parallel loop region) with an ordered clause.
1708 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001709 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001710 !Stack->isParentOrderedRegion();
1711 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001712 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1713 // OpenMP [2.16, Nesting of Regions]
1714 // If specified, a teams construct must be contained within a target
1715 // construct.
1716 NestingProhibited = ParentRegion != OMPD_target;
1717 Recommend = ShouldBeInTargetRegion;
1718 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1719 }
1720 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1721 // OpenMP [2.16, Nesting of Regions]
1722 // distribute, parallel, parallel sections, parallel workshare, and the
1723 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1724 // constructs that can be closely nested in the teams region.
1725 // TODO: add distribute directive.
1726 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1727 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001728 }
1729 if (NestingProhibited) {
1730 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001731 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1732 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001733 return true;
1734 }
1735 }
1736 return false;
1737}
1738
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001739StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001740 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001741 ArrayRef<OMPClause *> Clauses,
1742 Stmt *AStmt,
1743 SourceLocation StartLoc,
1744 SourceLocation EndLoc) {
1745 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001746 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001747 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001748
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001749 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001750 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001751 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001752 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001753 if (AStmt) {
1754 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1755
1756 // Check default data sharing attributes for referenced variables.
1757 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1758 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1759 if (DSAChecker.isErrorFound())
1760 return StmtError();
1761 // Generate list of implicitly defined firstprivate variables.
1762 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001763
1764 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1765 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1766 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1767 SourceLocation(), SourceLocation())) {
1768 ClausesWithImplicit.push_back(Implicit);
1769 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1770 DSAChecker.getImplicitFirstprivate().size();
1771 } else
1772 ErrorFound = true;
1773 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001774 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001775
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001776 switch (Kind) {
1777 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001778 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1779 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001780 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001781 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001782 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1783 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001784 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001785 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001786 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1787 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001788 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001789 case OMPD_for_simd:
1790 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1791 EndLoc, VarsWithInheritedDSA);
1792 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001793 case OMPD_sections:
1794 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1795 EndLoc);
1796 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001797 case OMPD_section:
1798 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001799 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001800 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1801 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001802 case OMPD_single:
1803 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1804 EndLoc);
1805 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001806 case OMPD_master:
1807 assert(ClausesWithImplicit.empty() &&
1808 "No clauses are allowed for 'omp master' directive");
1809 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1810 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001811 case OMPD_critical:
1812 assert(ClausesWithImplicit.empty() &&
1813 "No clauses are allowed for 'omp critical' directive");
1814 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1815 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001816 case OMPD_parallel_for:
1817 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1818 EndLoc, VarsWithInheritedDSA);
1819 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001820 case OMPD_parallel_for_simd:
1821 Res = ActOnOpenMPParallelForSimdDirective(
1822 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1823 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001824 case OMPD_parallel_sections:
1825 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1826 StartLoc, EndLoc);
1827 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001828 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001829 Res =
1830 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1831 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001832 case OMPD_taskyield:
1833 assert(ClausesWithImplicit.empty() &&
1834 "No clauses are allowed for 'omp taskyield' directive");
1835 assert(AStmt == nullptr &&
1836 "No associated statement allowed for 'omp taskyield' directive");
1837 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1838 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001839 case OMPD_barrier:
1840 assert(ClausesWithImplicit.empty() &&
1841 "No clauses are allowed for 'omp barrier' directive");
1842 assert(AStmt == nullptr &&
1843 "No associated statement allowed for 'omp barrier' directive");
1844 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1845 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001846 case OMPD_taskwait:
1847 assert(ClausesWithImplicit.empty() &&
1848 "No clauses are allowed for 'omp taskwait' directive");
1849 assert(AStmt == nullptr &&
1850 "No associated statement allowed for 'omp taskwait' directive");
1851 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1852 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001853 case OMPD_flush:
1854 assert(AStmt == nullptr &&
1855 "No associated statement allowed for 'omp flush' directive");
1856 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1857 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001858 case OMPD_ordered:
1859 assert(ClausesWithImplicit.empty() &&
1860 "No clauses are allowed for 'omp ordered' directive");
1861 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1862 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001863 case OMPD_atomic:
1864 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1865 EndLoc);
1866 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001867 case OMPD_teams:
1868 Res =
1869 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1870 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001871 case OMPD_target:
1872 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1873 EndLoc);
1874 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001875 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001876 llvm_unreachable("OpenMP Directive is not allowed");
1877 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001878 llvm_unreachable("Unknown OpenMP directive");
1879 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001880
Alexey Bataev4acb8592014-07-07 13:01:15 +00001881 for (auto P : VarsWithInheritedDSA) {
1882 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1883 << P.first << P.second->getSourceRange();
1884 }
1885 if (!VarsWithInheritedDSA.empty())
1886 return StmtError();
1887
Alexey Bataeved09d242014-05-28 05:53:51 +00001888 if (ErrorFound)
1889 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001890 return Res;
1891}
1892
1893StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1894 Stmt *AStmt,
1895 SourceLocation StartLoc,
1896 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001897 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1898 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1899 // 1.2.2 OpenMP Language Terminology
1900 // Structured block - An executable statement with a single entry at the
1901 // top and a single exit at the bottom.
1902 // The point of exit cannot be a branch out of the structured block.
1903 // longjmp() and throw() must not violate the entry/exit criteria.
1904 CS->getCapturedDecl()->setNothrow();
1905
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001906 getCurFunction()->setHasBranchProtectedScope();
1907
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001908 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1909 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001910}
1911
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001912namespace {
1913/// \brief Helper class for checking canonical form of the OpenMP loops and
1914/// extracting iteration space of each loop in the loop nest, that will be used
1915/// for IR generation.
1916class OpenMPIterationSpaceChecker {
1917 /// \brief Reference to Sema.
1918 Sema &SemaRef;
1919 /// \brief A location for diagnostics (when there is no some better location).
1920 SourceLocation DefaultLoc;
1921 /// \brief A location for diagnostics (when increment is not compatible).
1922 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001923 /// \brief A source location for referring to loop init later.
1924 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001925 /// \brief A source location for referring to condition later.
1926 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001927 /// \brief A source location for referring to increment later.
1928 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001929 /// \brief Loop variable.
1930 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001931 /// \brief Reference to loop variable.
1932 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001933 /// \brief Lower bound (initializer for the var).
1934 Expr *LB;
1935 /// \brief Upper bound.
1936 Expr *UB;
1937 /// \brief Loop step (increment).
1938 Expr *Step;
1939 /// \brief This flag is true when condition is one of:
1940 /// Var < UB
1941 /// Var <= UB
1942 /// UB > Var
1943 /// UB >= Var
1944 bool TestIsLessOp;
1945 /// \brief This flag is true when condition is strict ( < or > ).
1946 bool TestIsStrictOp;
1947 /// \brief This flag is true when step is subtracted on each iteration.
1948 bool SubtractStep;
1949
1950public:
1951 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1952 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00001953 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1954 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001955 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1956 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001957 /// \brief Check init-expr for canonical loop form and save loop counter
1958 /// variable - #Var and its initialization value - #LB.
1959 bool CheckInit(Stmt *S);
1960 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1961 /// for less/greater and for strict/non-strict comparison.
1962 bool CheckCond(Expr *S);
1963 /// \brief Check incr-expr for canonical loop form and return true if it
1964 /// does not conform, otherwise save loop step (#Step).
1965 bool CheckInc(Expr *S);
1966 /// \brief Return the loop counter variable.
1967 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001968 /// \brief Return the reference expression to loop counter variable.
1969 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00001970 /// \brief Source range of the loop init.
1971 SourceRange GetInitSrcRange() const { return InitSrcRange; }
1972 /// \brief Source range of the loop condition.
1973 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
1974 /// \brief Source range of the loop increment.
1975 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
1976 /// \brief True if the step should be subtracted.
1977 bool ShouldSubtractStep() const { return SubtractStep; }
1978 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00001979 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001980 /// \brief Build reference expression to the counter be used for codegen.
1981 Expr *BuildCounterVar() const;
1982 /// \brief Build initization of the counter be used for codegen.
1983 Expr *BuildCounterInit() const;
1984 /// \brief Build step of the counter be used for codegen.
1985 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001986 /// \brief Return true if any expression is dependent.
1987 bool Dependent() const;
1988
1989private:
1990 /// \brief Check the right-hand side of an assignment in the increment
1991 /// expression.
1992 bool CheckIncRHS(Expr *RHS);
1993 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001994 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001995 /// \brief Helper to set upper bound.
1996 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1997 const SourceLocation &SL);
1998 /// \brief Helper to set loop increment.
1999 bool SetStep(Expr *NewStep, bool Subtract);
2000};
2001
2002bool OpenMPIterationSpaceChecker::Dependent() const {
2003 if (!Var) {
2004 assert(!LB && !UB && !Step);
2005 return false;
2006 }
2007 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2008 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2009}
2010
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002011bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2012 DeclRefExpr *NewVarRefExpr,
2013 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002014 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002015 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2016 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002017 if (!NewVar || !NewLB)
2018 return true;
2019 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002020 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002021 LB = NewLB;
2022 return false;
2023}
2024
2025bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2026 const SourceRange &SR,
2027 const SourceLocation &SL) {
2028 // State consistency checking to ensure correct usage.
2029 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2030 !TestIsLessOp && !TestIsStrictOp);
2031 if (!NewUB)
2032 return true;
2033 UB = NewUB;
2034 TestIsLessOp = LessOp;
2035 TestIsStrictOp = StrictOp;
2036 ConditionSrcRange = SR;
2037 ConditionLoc = SL;
2038 return false;
2039}
2040
2041bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2042 // State consistency checking to ensure correct usage.
2043 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2044 if (!NewStep)
2045 return true;
2046 if (!NewStep->isValueDependent()) {
2047 // Check that the step is integer expression.
2048 SourceLocation StepLoc = NewStep->getLocStart();
2049 ExprResult Val =
2050 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2051 if (Val.isInvalid())
2052 return true;
2053 NewStep = Val.get();
2054
2055 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2056 // If test-expr is of form var relational-op b and relational-op is < or
2057 // <= then incr-expr must cause var to increase on each iteration of the
2058 // loop. If test-expr is of form var relational-op b and relational-op is
2059 // > or >= then incr-expr must cause var to decrease on each iteration of
2060 // the loop.
2061 // If test-expr is of form b relational-op var and relational-op is < or
2062 // <= then incr-expr must cause var to decrease on each iteration of the
2063 // loop. If test-expr is of form b relational-op var and relational-op is
2064 // > or >= then incr-expr must cause var to increase on each iteration of
2065 // the loop.
2066 llvm::APSInt Result;
2067 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2068 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2069 bool IsConstNeg =
2070 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002071 bool IsConstPos =
2072 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002073 bool IsConstZero = IsConstant && !Result.getBoolValue();
2074 if (UB && (IsConstZero ||
2075 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002076 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002077 SemaRef.Diag(NewStep->getExprLoc(),
2078 diag::err_omp_loop_incr_not_compatible)
2079 << Var << TestIsLessOp << NewStep->getSourceRange();
2080 SemaRef.Diag(ConditionLoc,
2081 diag::note_omp_loop_cond_requres_compatible_incr)
2082 << TestIsLessOp << ConditionSrcRange;
2083 return true;
2084 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002085 if (TestIsLessOp == Subtract) {
2086 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2087 NewStep).get();
2088 Subtract = !Subtract;
2089 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002090 }
2091
2092 Step = NewStep;
2093 SubtractStep = Subtract;
2094 return false;
2095}
2096
2097bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
2098 // Check init-expr for canonical loop form and save loop counter
2099 // variable - #Var and its initialization value - #LB.
2100 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2101 // var = lb
2102 // integer-type var = lb
2103 // random-access-iterator-type var = lb
2104 // pointer-type var = lb
2105 //
2106 if (!S) {
2107 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2108 return true;
2109 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002110 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002111 if (Expr *E = dyn_cast<Expr>(S))
2112 S = E->IgnoreParens();
2113 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2114 if (BO->getOpcode() == BO_Assign)
2115 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002116 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002117 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002118 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2119 if (DS->isSingleDecl()) {
2120 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2121 if (Var->hasInit()) {
2122 // Accept non-canonical init form here but emit ext. warning.
2123 if (Var->getInitStyle() != VarDecl::CInit)
2124 SemaRef.Diag(S->getLocStart(),
2125 diag::ext_omp_loop_not_canonical_init)
2126 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002127 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002128 }
2129 }
2130 }
2131 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2132 if (CE->getOperator() == OO_Equal)
2133 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002134 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2135 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002136
2137 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2138 << S->getSourceRange();
2139 return true;
2140}
2141
Alexey Bataev23b69422014-06-18 07:08:49 +00002142/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002143/// variable (which may be the loop variable) if possible.
2144static const VarDecl *GetInitVarDecl(const Expr *E) {
2145 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002146 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002147 E = E->IgnoreParenImpCasts();
2148 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2149 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2150 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2151 CE->getArg(0) != nullptr)
2152 E = CE->getArg(0)->IgnoreParenImpCasts();
2153 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2154 if (!DRE)
2155 return nullptr;
2156 return dyn_cast<VarDecl>(DRE->getDecl());
2157}
2158
2159bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2160 // Check test-expr for canonical form, save upper-bound UB, flags for
2161 // less/greater and for strict/non-strict comparison.
2162 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2163 // var relational-op b
2164 // b relational-op var
2165 //
2166 if (!S) {
2167 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2168 return true;
2169 }
2170 S = S->IgnoreParenImpCasts();
2171 SourceLocation CondLoc = S->getLocStart();
2172 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2173 if (BO->isRelationalOp()) {
2174 if (GetInitVarDecl(BO->getLHS()) == Var)
2175 return SetUB(BO->getRHS(),
2176 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2177 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2178 BO->getSourceRange(), BO->getOperatorLoc());
2179 if (GetInitVarDecl(BO->getRHS()) == Var)
2180 return SetUB(BO->getLHS(),
2181 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2182 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2183 BO->getSourceRange(), BO->getOperatorLoc());
2184 }
2185 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2186 if (CE->getNumArgs() == 2) {
2187 auto Op = CE->getOperator();
2188 switch (Op) {
2189 case OO_Greater:
2190 case OO_GreaterEqual:
2191 case OO_Less:
2192 case OO_LessEqual:
2193 if (GetInitVarDecl(CE->getArg(0)) == Var)
2194 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2195 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2196 CE->getOperatorLoc());
2197 if (GetInitVarDecl(CE->getArg(1)) == Var)
2198 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2199 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2200 CE->getOperatorLoc());
2201 break;
2202 default:
2203 break;
2204 }
2205 }
2206 }
2207 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2208 << S->getSourceRange() << Var;
2209 return true;
2210}
2211
2212bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2213 // RHS of canonical loop form increment can be:
2214 // var + incr
2215 // incr + var
2216 // var - incr
2217 //
2218 RHS = RHS->IgnoreParenImpCasts();
2219 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2220 if (BO->isAdditiveOp()) {
2221 bool IsAdd = BO->getOpcode() == BO_Add;
2222 if (GetInitVarDecl(BO->getLHS()) == Var)
2223 return SetStep(BO->getRHS(), !IsAdd);
2224 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2225 return SetStep(BO->getLHS(), false);
2226 }
2227 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2228 bool IsAdd = CE->getOperator() == OO_Plus;
2229 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2230 if (GetInitVarDecl(CE->getArg(0)) == Var)
2231 return SetStep(CE->getArg(1), !IsAdd);
2232 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2233 return SetStep(CE->getArg(0), false);
2234 }
2235 }
2236 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2237 << RHS->getSourceRange() << Var;
2238 return true;
2239}
2240
2241bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2242 // Check incr-expr for canonical loop form and return true if it
2243 // does not conform.
2244 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2245 // ++var
2246 // var++
2247 // --var
2248 // var--
2249 // var += incr
2250 // var -= incr
2251 // var = var + incr
2252 // var = incr + var
2253 // var = var - incr
2254 //
2255 if (!S) {
2256 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2257 return true;
2258 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002259 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002260 S = S->IgnoreParens();
2261 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2262 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2263 return SetStep(
2264 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2265 (UO->isDecrementOp() ? -1 : 1)).get(),
2266 false);
2267 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2268 switch (BO->getOpcode()) {
2269 case BO_AddAssign:
2270 case BO_SubAssign:
2271 if (GetInitVarDecl(BO->getLHS()) == Var)
2272 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2273 break;
2274 case BO_Assign:
2275 if (GetInitVarDecl(BO->getLHS()) == Var)
2276 return CheckIncRHS(BO->getRHS());
2277 break;
2278 default:
2279 break;
2280 }
2281 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2282 switch (CE->getOperator()) {
2283 case OO_PlusPlus:
2284 case OO_MinusMinus:
2285 if (GetInitVarDecl(CE->getArg(0)) == Var)
2286 return SetStep(
2287 SemaRef.ActOnIntegerConstant(
2288 CE->getLocStart(),
2289 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2290 false);
2291 break;
2292 case OO_PlusEqual:
2293 case OO_MinusEqual:
2294 if (GetInitVarDecl(CE->getArg(0)) == Var)
2295 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2296 break;
2297 case OO_Equal:
2298 if (GetInitVarDecl(CE->getArg(0)) == Var)
2299 return CheckIncRHS(CE->getArg(1));
2300 break;
2301 default:
2302 break;
2303 }
2304 }
2305 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2306 << S->getSourceRange() << Var;
2307 return true;
2308}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002309
2310/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002311Expr *
2312OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2313 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002314 ExprResult Diff;
2315 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2316 SemaRef.getLangOpts().CPlusPlus) {
2317 // Upper - Lower
2318 Expr *Upper = TestIsLessOp ? UB : LB;
2319 Expr *Lower = TestIsLessOp ? LB : UB;
2320
2321 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2322
2323 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2324 // BuildBinOp already emitted error, this one is to point user to upper
2325 // and lower bound, and to tell what is passed to 'operator-'.
2326 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2327 << Upper->getSourceRange() << Lower->getSourceRange();
2328 return nullptr;
2329 }
2330 }
2331
2332 if (!Diff.isUsable())
2333 return nullptr;
2334
2335 // Upper - Lower [- 1]
2336 if (TestIsStrictOp)
2337 Diff = SemaRef.BuildBinOp(
2338 S, DefaultLoc, BO_Sub, Diff.get(),
2339 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2340 if (!Diff.isUsable())
2341 return nullptr;
2342
2343 // Upper - Lower [- 1] + Step
2344 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2345 Step->IgnoreImplicit());
2346 if (!Diff.isUsable())
2347 return nullptr;
2348
2349 // Parentheses (for dumping/debugging purposes only).
2350 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2351 if (!Diff.isUsable())
2352 return nullptr;
2353
2354 // (Upper - Lower [- 1] + Step) / Step
2355 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2356 Step->IgnoreImplicit());
2357 if (!Diff.isUsable())
2358 return nullptr;
2359
Alexander Musman174b3ca2014-10-06 11:16:29 +00002360 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2361 if (LimitedType) {
2362 auto &C = SemaRef.Context;
2363 QualType Type = Diff.get()->getType();
2364 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2365 if (NewSize != C.getTypeSize(Type)) {
2366 if (NewSize < C.getTypeSize(Type)) {
2367 assert(NewSize == 64 && "incorrect loop var size");
2368 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2369 << InitSrcRange << ConditionSrcRange;
2370 }
2371 QualType NewType = C.getIntTypeForBitwidth(
2372 NewSize, Type->hasSignedIntegerRepresentation());
2373 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2374 Sema::AA_Converting, true);
2375 if (!Diff.isUsable())
2376 return nullptr;
2377 }
2378 }
2379
Alexander Musmana5f070a2014-10-01 06:03:56 +00002380 return Diff.get();
2381}
2382
2383/// \brief Build reference expression to the counter be used for codegen.
2384Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2385 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2386 GetIncrementSrcRange().getBegin(), Var, false,
2387 DefaultLoc, Var->getType(), VK_LValue);
2388}
2389
2390/// \brief Build initization of the counter be used for codegen.
2391Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2392
2393/// \brief Build step of the counter be used for codegen.
2394Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2395
2396/// \brief Iteration space of a single for loop.
2397struct LoopIterationSpace {
2398 /// \brief This expression calculates the number of iterations in the loop.
2399 /// It is always possible to calculate it before starting the loop.
2400 Expr *NumIterations;
2401 /// \brief The loop counter variable.
2402 Expr *CounterVar;
2403 /// \brief This is initializer for the initial value of #CounterVar.
2404 Expr *CounterInit;
2405 /// \brief This is step for the #CounterVar used to generate its update:
2406 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2407 Expr *CounterStep;
2408 /// \brief Should step be subtracted?
2409 bool Subtract;
2410 /// \brief Source range of the loop init.
2411 SourceRange InitSrcRange;
2412 /// \brief Source range of the loop condition.
2413 SourceRange CondSrcRange;
2414 /// \brief Source range of the loop increment.
2415 SourceRange IncSrcRange;
2416};
2417
Alexey Bataev23b69422014-06-18 07:08:49 +00002418} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002419
2420/// \brief Called on a for stmt to check and extract its iteration space
2421/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002422static bool CheckOpenMPIterationSpace(
2423 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2424 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2425 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002426 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2427 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002428 // OpenMP [2.6, Canonical Loop Form]
2429 // for (init-expr; test-expr; incr-expr) structured-block
2430 auto For = dyn_cast_or_null<ForStmt>(S);
2431 if (!For) {
2432 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002433 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2434 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2435 << CurrentNestedLoopCount;
2436 if (NestedLoopCount > 1)
2437 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2438 diag::note_omp_collapse_expr)
2439 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002440 return true;
2441 }
2442 assert(For->getBody());
2443
2444 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2445
2446 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002447 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002448 if (ISC.CheckInit(Init)) {
2449 return true;
2450 }
2451
2452 bool HasErrors = false;
2453
2454 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002455 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002456
2457 // OpenMP [2.6, Canonical Loop Form]
2458 // Var is one of the following:
2459 // A variable of signed or unsigned integer type.
2460 // For C++, a variable of a random access iterator type.
2461 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002462 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002463 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2464 !VarType->isPointerType() &&
2465 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2466 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2467 << SemaRef.getLangOpts().CPlusPlus;
2468 HasErrors = true;
2469 }
2470
Alexey Bataev4acb8592014-07-07 13:01:15 +00002471 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2472 // Construct
2473 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2474 // parallel for construct is (are) private.
2475 // The loop iteration variable in the associated for-loop of a simd construct
2476 // with just one associated for-loop is linear with a constant-linear-step
2477 // that is the increment of the associated for-loop.
2478 // Exclude loop var from the list of variables with implicitly defined data
2479 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002480 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002481
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002482 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2483 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002484 // The loop iteration variable in the associated for-loop of a simd construct
2485 // with just one associated for-loop may be listed in a linear clause with a
2486 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002487 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2488 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002489 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002490 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2491 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2492 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002493 auto PredeterminedCKind =
2494 isOpenMPSimdDirective(DKind)
2495 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2496 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002497 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002498 DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002499 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2500 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2501 DVar.CKind != OMPC_lastprivate)) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00002502 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002503 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002504 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2505 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002506 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002507 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002508 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002509 // Make the loop iteration variable private (for worksharing constructs),
2510 // linear (for simd directives with the only one associated loop) or
2511 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002512 // FIXME: the next check and error message must be removed once the
2513 // capturing of global variables in loops is fixed.
2514 if (DVar.CKind == OMPC_unknown)
2515 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2516 /*FromParent=*/false);
2517 if (!Var->hasLocalStorage() && DVar.CKind == OMPC_unknown) {
2518 SemaRef.Diag(Init->getLocStart(), diag::err_omp_global_loop_var_dsa)
2519 << getOpenMPClauseName(PredeterminedCKind)
2520 << getOpenMPDirectiveName(DKind);
2521 HasErrors = true;
2522 } else
2523 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002524 }
2525
Alexey Bataev7ff55242014-06-19 09:13:45 +00002526 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002527
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002528 // Check test-expr.
2529 HasErrors |= ISC.CheckCond(For->getCond());
2530
2531 // Check incr-expr.
2532 HasErrors |= ISC.CheckInc(For->getInc());
2533
Alexander Musmana5f070a2014-10-01 06:03:56 +00002534 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002535 return HasErrors;
2536
Alexander Musmana5f070a2014-10-01 06:03:56 +00002537 // Build the loop's iteration space representation.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002538 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2539 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002540 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2541 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2542 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2543 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2544 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2545 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2546 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2547
2548 HasErrors |= (ResultIterSpace.NumIterations == nullptr ||
2549 ResultIterSpace.CounterVar == nullptr ||
2550 ResultIterSpace.CounterInit == nullptr ||
2551 ResultIterSpace.CounterStep == nullptr);
2552
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002553 return HasErrors;
2554}
2555
Alexander Musmana5f070a2014-10-01 06:03:56 +00002556/// \brief Build a variable declaration for OpenMP loop iteration variable.
2557static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2558 StringRef Name) {
2559 DeclContext *DC = SemaRef.CurContext;
2560 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2561 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2562 VarDecl *Decl =
2563 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2564 Decl->setImplicit();
2565 return Decl;
2566}
2567
2568/// \brief Build 'VarRef = Start + Iter * Step'.
2569static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2570 SourceLocation Loc, ExprResult VarRef,
2571 ExprResult Start, ExprResult Iter,
2572 ExprResult Step, bool Subtract) {
2573 // Add parentheses (for debugging purposes only).
2574 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2575 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2576 !Step.isUsable())
2577 return ExprError();
2578
2579 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2580 Step.get()->IgnoreImplicit());
2581 if (!Update.isUsable())
2582 return ExprError();
2583
2584 // Build 'VarRef = Start + Iter * Step'.
2585 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2586 Start.get()->IgnoreImplicit(), Update.get());
2587 if (!Update.isUsable())
2588 return ExprError();
2589
2590 Update = SemaRef.PerformImplicitConversion(
2591 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2592 if (!Update.isUsable())
2593 return ExprError();
2594
2595 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2596 return Update;
2597}
2598
2599/// \brief Convert integer expression \a E to make it have at least \a Bits
2600/// bits.
2601static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2602 Sema &SemaRef) {
2603 if (E == nullptr)
2604 return ExprError();
2605 auto &C = SemaRef.Context;
2606 QualType OldType = E->getType();
2607 unsigned HasBits = C.getTypeSize(OldType);
2608 if (HasBits >= Bits)
2609 return ExprResult(E);
2610 // OK to convert to signed, because new type has more bits than old.
2611 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2612 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2613 true);
2614}
2615
2616/// \brief Check if the given expression \a E is a constant integer that fits
2617/// into \a Bits bits.
2618static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2619 if (E == nullptr)
2620 return false;
2621 llvm::APSInt Result;
2622 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2623 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2624 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002625}
2626
2627/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002628/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2629/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002630static unsigned
2631CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2632 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002633 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002634 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002635 unsigned NestedLoopCount = 1;
2636 if (NestedLoopCountExpr) {
2637 // Found 'collapse' clause - calculate collapse number.
2638 llvm::APSInt Result;
2639 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2640 NestedLoopCount = Result.getLimitedValue();
2641 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002642 // This is helper routine for loop directives (e.g., 'for', 'simd',
2643 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002644 SmallVector<LoopIterationSpace, 4> IterSpaces;
2645 IterSpaces.resize(NestedLoopCount);
2646 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002647 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002648 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002649 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002650 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002651 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002652 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002653 // OpenMP [2.8.1, simd construct, Restrictions]
2654 // All loops associated with the construct must be perfectly nested; that
2655 // is, there must be no intervening code nor any OpenMP directive between
2656 // any two loops.
2657 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002658 }
2659
Alexander Musmana5f070a2014-10-01 06:03:56 +00002660 Built.clear(/* size */ NestedLoopCount);
2661
2662 if (SemaRef.CurContext->isDependentContext())
2663 return NestedLoopCount;
2664
2665 // An example of what is generated for the following code:
2666 //
2667 // #pragma omp simd collapse(2)
2668 // for (i = 0; i < NI; ++i)
2669 // for (j = J0; j < NJ; j+=2) {
2670 // <loop body>
2671 // }
2672 //
2673 // We generate the code below.
2674 // Note: the loop body may be outlined in CodeGen.
2675 // Note: some counters may be C++ classes, operator- is used to find number of
2676 // iterations and operator+= to calculate counter value.
2677 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2678 // or i64 is currently supported).
2679 //
2680 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2681 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2682 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2683 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2684 // // similar updates for vars in clauses (e.g. 'linear')
2685 // <loop body (using local i and j)>
2686 // }
2687 // i = NI; // assign final values of counters
2688 // j = NJ;
2689 //
2690
2691 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2692 // the iteration counts of the collapsed for loops.
2693 auto N0 = IterSpaces[0].NumIterations;
2694 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2695 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2696
2697 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2698 return NestedLoopCount;
2699
2700 auto &C = SemaRef.Context;
2701 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2702
2703 Scope *CurScope = DSA.getCurScope();
2704 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
2705 auto N = IterSpaces[Cnt].NumIterations;
2706 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2707 if (LastIteration32.isUsable())
2708 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2709 LastIteration32.get(), N);
2710 if (LastIteration64.isUsable())
2711 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2712 LastIteration64.get(), N);
2713 }
2714
2715 // Choose either the 32-bit or 64-bit version.
2716 ExprResult LastIteration = LastIteration64;
2717 if (LastIteration32.isUsable() &&
2718 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2719 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2720 FitsInto(
2721 32 /* Bits */,
2722 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2723 LastIteration64.get(), SemaRef)))
2724 LastIteration = LastIteration32;
2725
2726 if (!LastIteration.isUsable())
2727 return 0;
2728
2729 // Save the number of iterations.
2730 ExprResult NumIterations = LastIteration;
2731 {
2732 LastIteration = SemaRef.BuildBinOp(
2733 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2734 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2735 if (!LastIteration.isUsable())
2736 return 0;
2737 }
2738
2739 // Calculate the last iteration number beforehand instead of doing this on
2740 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2741 llvm::APSInt Result;
2742 bool IsConstant =
2743 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2744 ExprResult CalcLastIteration;
2745 if (!IsConstant) {
2746 SourceLocation SaveLoc;
2747 VarDecl *SaveVar =
2748 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2749 ".omp.last.iteration");
2750 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2751 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2752 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2753 SaveRef.get(), LastIteration.get());
2754 LastIteration = SaveRef;
2755
2756 // Prepare SaveRef + 1.
2757 NumIterations = SemaRef.BuildBinOp(
2758 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2759 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2760 if (!NumIterations.isUsable())
2761 return 0;
2762 }
2763
2764 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2765
2766 // Precondition tests if there is at least one iteration (LastIteration > 0).
2767 ExprResult PreCond = SemaRef.BuildBinOp(
2768 CurScope, InitLoc, BO_GT, LastIteration.get(),
2769 SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get());
2770
Alexander Musmanc6388682014-12-15 07:07:06 +00002771 QualType VType = LastIteration.get()->getType();
2772 // Build variables passed into runtime, nesessary for worksharing directives.
2773 ExprResult LB, UB, IL, ST, EUB;
2774 if (isOpenMPWorksharingDirective(DKind)) {
2775 // Lower bound variable, initialized with zero.
2776 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2777 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2778 SemaRef.AddInitializerToDecl(
2779 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2780 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2781
2782 // Upper bound variable, initialized with last iteration number.
2783 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2784 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2785 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2786 /*DirectInit*/ false,
2787 /*TypeMayContainAuto*/ false);
2788
2789 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2790 // This will be used to implement clause 'lastprivate'.
2791 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2792 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2793 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2794 SemaRef.AddInitializerToDecl(
2795 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2796 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2797
2798 // Stride variable returned by runtime (we initialize it to 1 by default).
2799 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2800 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2801 SemaRef.AddInitializerToDecl(
2802 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2803 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2804
2805 // Build expression: UB = min(UB, LastIteration)
2806 // It is nesessary for CodeGen of directives with static scheduling.
2807 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2808 UB.get(), LastIteration.get());
2809 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2810 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2811 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2812 CondOp.get());
2813 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2814 }
2815
2816 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002817 ExprResult IV;
2818 ExprResult Init;
2819 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002820 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2821 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2822 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2823 ? LB.get()
2824 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2825 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2826 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002827 }
2828
Alexander Musmanc6388682014-12-15 07:07:06 +00002829 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002830 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002831 ExprResult Cond =
2832 isOpenMPWorksharingDirective(DKind)
2833 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2834 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2835 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002836 // Loop condition with 1 iteration separated (IV < LastIteration)
2837 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2838 IV.get(), LastIteration.get());
2839
2840 // Loop increment (IV = IV + 1)
2841 SourceLocation IncLoc;
2842 ExprResult Inc =
2843 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2844 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2845 if (!Inc.isUsable())
2846 return 0;
2847 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002848 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2849 if (!Inc.isUsable())
2850 return 0;
2851
2852 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2853 // Used for directives with static scheduling.
2854 ExprResult NextLB, NextUB;
2855 if (isOpenMPWorksharingDirective(DKind)) {
2856 // LB + ST
2857 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2858 if (!NextLB.isUsable())
2859 return 0;
2860 // LB = LB + ST
2861 NextLB =
2862 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2863 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2864 if (!NextLB.isUsable())
2865 return 0;
2866 // UB + ST
2867 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2868 if (!NextUB.isUsable())
2869 return 0;
2870 // UB = UB + ST
2871 NextUB =
2872 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2873 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2874 if (!NextUB.isUsable())
2875 return 0;
2876 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002877
2878 // Build updates and final values of the loop counters.
2879 bool HasErrors = false;
2880 Built.Counters.resize(NestedLoopCount);
2881 Built.Updates.resize(NestedLoopCount);
2882 Built.Finals.resize(NestedLoopCount);
2883 {
2884 ExprResult Div;
2885 // Go from inner nested loop to outer.
2886 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2887 LoopIterationSpace &IS = IterSpaces[Cnt];
2888 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2889 // Build: Iter = (IV / Div) % IS.NumIters
2890 // where Div is product of previous iterations' IS.NumIters.
2891 ExprResult Iter;
2892 if (Div.isUsable()) {
2893 Iter =
2894 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2895 } else {
2896 Iter = IV;
2897 assert((Cnt == (int)NestedLoopCount - 1) &&
2898 "unusable div expected on first iteration only");
2899 }
2900
2901 if (Cnt != 0 && Iter.isUsable())
2902 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2903 IS.NumIterations);
2904 if (!Iter.isUsable()) {
2905 HasErrors = true;
2906 break;
2907 }
2908
2909 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2910 ExprResult Update =
2911 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2912 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2913 if (!Update.isUsable()) {
2914 HasErrors = true;
2915 break;
2916 }
2917
2918 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2919 ExprResult Final = BuildCounterUpdate(
2920 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2921 IS.NumIterations, IS.CounterStep, IS.Subtract);
2922 if (!Final.isUsable()) {
2923 HasErrors = true;
2924 break;
2925 }
2926
2927 // Build Div for the next iteration: Div <- Div * IS.NumIters
2928 if (Cnt != 0) {
2929 if (Div.isUnset())
2930 Div = IS.NumIterations;
2931 else
2932 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
2933 IS.NumIterations);
2934
2935 // Add parentheses (for debugging purposes only).
2936 if (Div.isUsable())
2937 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
2938 if (!Div.isUsable()) {
2939 HasErrors = true;
2940 break;
2941 }
2942 }
2943 if (!Update.isUsable() || !Final.isUsable()) {
2944 HasErrors = true;
2945 break;
2946 }
2947 // Save results
2948 Built.Counters[Cnt] = IS.CounterVar;
2949 Built.Updates[Cnt] = Update.get();
2950 Built.Finals[Cnt] = Final.get();
2951 }
2952 }
2953
2954 if (HasErrors)
2955 return 0;
2956
2957 // Save results
2958 Built.IterationVarRef = IV.get();
2959 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00002960 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002961 Built.CalcLastIteration = CalcLastIteration.get();
2962 Built.PreCond = PreCond.get();
2963 Built.Cond = Cond.get();
2964 Built.SeparatedCond = SeparatedCond.get();
2965 Built.Init = Init.get();
2966 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00002967 Built.LB = LB.get();
2968 Built.UB = UB.get();
2969 Built.IL = IL.get();
2970 Built.ST = ST.get();
2971 Built.EUB = EUB.get();
2972 Built.NLB = NextLB.get();
2973 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002974
Alexey Bataevabfc0692014-06-25 06:52:00 +00002975 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002976}
2977
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002978static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002979 auto CollapseFilter = [](const OMPClause *C) -> bool {
2980 return C->getClauseKind() == OMPC_collapse;
2981 };
2982 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
2983 Clauses, CollapseFilter);
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002984 if (I)
2985 return cast<OMPCollapseClause>(*I)->getNumForLoops();
2986 return nullptr;
2987}
2988
Alexey Bataev4acb8592014-07-07 13:01:15 +00002989StmtResult Sema::ActOnOpenMPSimdDirective(
2990 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2991 SourceLocation EndLoc,
2992 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002993 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002994 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002995 unsigned NestedLoopCount =
2996 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002997 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00002998 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002999 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003000
Alexander Musmana5f070a2014-10-01 06:03:56 +00003001 assert((CurContext->isDependentContext() || B.builtAll()) &&
3002 "omp simd loop exprs were not built");
3003
Alexander Musman3276a272015-03-21 10:12:56 +00003004 if (!CurContext->isDependentContext()) {
3005 // Finalize the clauses that need pre-built expressions for CodeGen.
3006 for (auto C : Clauses) {
3007 if (auto LC = dyn_cast<OMPLinearClause>(C))
3008 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3009 B.NumIterations, *this, CurScope))
3010 return StmtError();
3011 }
3012 }
3013
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003014 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003015 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3016 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003017}
3018
Alexey Bataev4acb8592014-07-07 13:01:15 +00003019StmtResult Sema::ActOnOpenMPForDirective(
3020 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3021 SourceLocation EndLoc,
3022 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003023 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003024 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003025 unsigned NestedLoopCount =
3026 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003027 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003028 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003029 return StmtError();
3030
Alexander Musmana5f070a2014-10-01 06:03:56 +00003031 assert((CurContext->isDependentContext() || B.builtAll()) &&
3032 "omp for loop exprs were not built");
3033
Alexey Bataevf29276e2014-06-18 04:14:57 +00003034 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003035 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3036 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003037}
3038
Alexander Musmanf82886e2014-09-18 05:12:34 +00003039StmtResult Sema::ActOnOpenMPForSimdDirective(
3040 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3041 SourceLocation EndLoc,
3042 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003043 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003044 // In presence of clause 'collapse', it will define the nested loops number.
3045 unsigned NestedLoopCount =
3046 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003047 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003048 if (NestedLoopCount == 0)
3049 return StmtError();
3050
Alexander Musmanc6388682014-12-15 07:07:06 +00003051 assert((CurContext->isDependentContext() || B.builtAll()) &&
3052 "omp for simd loop exprs were not built");
3053
Alexander Musmanf82886e2014-09-18 05:12:34 +00003054 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003055 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3056 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003057}
3058
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003059StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3060 Stmt *AStmt,
3061 SourceLocation StartLoc,
3062 SourceLocation EndLoc) {
3063 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3064 auto BaseStmt = AStmt;
3065 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3066 BaseStmt = CS->getCapturedStmt();
3067 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3068 auto S = C->children();
3069 if (!S)
3070 return StmtError();
3071 // All associated statements must be '#pragma omp section' except for
3072 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003073 for (++S; S; ++S) {
3074 auto SectionStmt = *S;
3075 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3076 if (SectionStmt)
3077 Diag(SectionStmt->getLocStart(),
3078 diag::err_omp_sections_substmt_not_section);
3079 return StmtError();
3080 }
3081 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003082 } else {
3083 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3084 return StmtError();
3085 }
3086
3087 getCurFunction()->setHasBranchProtectedScope();
3088
3089 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3090 AStmt);
3091}
3092
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003093StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3094 SourceLocation StartLoc,
3095 SourceLocation EndLoc) {
3096 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3097
3098 getCurFunction()->setHasBranchProtectedScope();
3099
3100 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3101}
3102
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003103StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3104 Stmt *AStmt,
3105 SourceLocation StartLoc,
3106 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003107 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3108
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003109 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003110
Alexey Bataev3255bf32015-01-19 05:20:46 +00003111 // OpenMP [2.7.3, single Construct, Restrictions]
3112 // The copyprivate clause must not be used with the nowait clause.
3113 OMPClause *Nowait = nullptr;
3114 OMPClause *Copyprivate = nullptr;
3115 for (auto *Clause : Clauses) {
3116 if (Clause->getClauseKind() == OMPC_nowait)
3117 Nowait = Clause;
3118 else if (Clause->getClauseKind() == OMPC_copyprivate)
3119 Copyprivate = Clause;
3120 if (Copyprivate && Nowait) {
3121 Diag(Copyprivate->getLocStart(),
3122 diag::err_omp_single_copyprivate_with_nowait);
3123 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3124 return StmtError();
3125 }
3126 }
3127
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003128 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3129}
3130
Alexander Musman80c22892014-07-17 08:54:58 +00003131StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3132 SourceLocation StartLoc,
3133 SourceLocation EndLoc) {
3134 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3135
3136 getCurFunction()->setHasBranchProtectedScope();
3137
3138 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3139}
3140
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003141StmtResult
3142Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3143 Stmt *AStmt, SourceLocation StartLoc,
3144 SourceLocation EndLoc) {
3145 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3146
3147 getCurFunction()->setHasBranchProtectedScope();
3148
3149 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3150 AStmt);
3151}
3152
Alexey Bataev4acb8592014-07-07 13:01:15 +00003153StmtResult Sema::ActOnOpenMPParallelForDirective(
3154 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3155 SourceLocation EndLoc,
3156 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3157 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3158 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3159 // 1.2.2 OpenMP Language Terminology
3160 // Structured block - An executable statement with a single entry at the
3161 // top and a single exit at the bottom.
3162 // The point of exit cannot be a branch out of the structured block.
3163 // longjmp() and throw() must not violate the entry/exit criteria.
3164 CS->getCapturedDecl()->setNothrow();
3165
Alexander Musmanc6388682014-12-15 07:07:06 +00003166 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003167 // In presence of clause 'collapse', it will define the nested loops number.
3168 unsigned NestedLoopCount =
3169 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003170 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003171 if (NestedLoopCount == 0)
3172 return StmtError();
3173
Alexander Musmana5f070a2014-10-01 06:03:56 +00003174 assert((CurContext->isDependentContext() || B.builtAll()) &&
3175 "omp parallel for loop exprs were not built");
3176
Alexey Bataev4acb8592014-07-07 13:01:15 +00003177 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003178 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3179 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003180}
3181
Alexander Musmane4e893b2014-09-23 09:33:00 +00003182StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3183 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3184 SourceLocation EndLoc,
3185 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3186 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3187 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3188 // 1.2.2 OpenMP Language Terminology
3189 // Structured block - An executable statement with a single entry at the
3190 // top and a single exit at the bottom.
3191 // The point of exit cannot be a branch out of the structured block.
3192 // longjmp() and throw() must not violate the entry/exit criteria.
3193 CS->getCapturedDecl()->setNothrow();
3194
Alexander Musmanc6388682014-12-15 07:07:06 +00003195 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003196 // In presence of clause 'collapse', it will define the nested loops number.
3197 unsigned NestedLoopCount =
3198 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003199 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003200 if (NestedLoopCount == 0)
3201 return StmtError();
3202
3203 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003204 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003205 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003206}
3207
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003208StmtResult
3209Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3210 Stmt *AStmt, SourceLocation StartLoc,
3211 SourceLocation EndLoc) {
3212 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3213 auto BaseStmt = AStmt;
3214 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3215 BaseStmt = CS->getCapturedStmt();
3216 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3217 auto S = C->children();
3218 if (!S)
3219 return StmtError();
3220 // All associated statements must be '#pragma omp section' except for
3221 // the first one.
3222 for (++S; S; ++S) {
3223 auto SectionStmt = *S;
3224 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3225 if (SectionStmt)
3226 Diag(SectionStmt->getLocStart(),
3227 diag::err_omp_parallel_sections_substmt_not_section);
3228 return StmtError();
3229 }
3230 }
3231 } else {
3232 Diag(AStmt->getLocStart(),
3233 diag::err_omp_parallel_sections_not_compound_stmt);
3234 return StmtError();
3235 }
3236
3237 getCurFunction()->setHasBranchProtectedScope();
3238
3239 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3240 Clauses, AStmt);
3241}
3242
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003243StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3244 Stmt *AStmt, SourceLocation StartLoc,
3245 SourceLocation EndLoc) {
3246 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3247 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3248 // 1.2.2 OpenMP Language Terminology
3249 // Structured block - An executable statement with a single entry at the
3250 // top and a single exit at the bottom.
3251 // The point of exit cannot be a branch out of the structured block.
3252 // longjmp() and throw() must not violate the entry/exit criteria.
3253 CS->getCapturedDecl()->setNothrow();
3254
3255 getCurFunction()->setHasBranchProtectedScope();
3256
3257 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3258}
3259
Alexey Bataev68446b72014-07-18 07:47:19 +00003260StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3261 SourceLocation EndLoc) {
3262 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3263}
3264
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003265StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3266 SourceLocation EndLoc) {
3267 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3268}
3269
Alexey Bataev2df347a2014-07-18 10:17:07 +00003270StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3271 SourceLocation EndLoc) {
3272 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3273}
3274
Alexey Bataev6125da92014-07-21 11:26:11 +00003275StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3276 SourceLocation StartLoc,
3277 SourceLocation EndLoc) {
3278 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3279 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3280}
3281
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003282StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3283 SourceLocation StartLoc,
3284 SourceLocation EndLoc) {
3285 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3286
3287 getCurFunction()->setHasBranchProtectedScope();
3288
3289 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3290}
3291
Alexey Bataev1d160b12015-03-13 12:27:31 +00003292namespace {
3293/// \brief Helper class for checking expression in 'omp atomic [update]'
3294/// construct.
3295class OpenMPAtomicUpdateChecker {
3296 /// \brief Error results for atomic update expressions.
3297 enum ExprAnalysisErrorCode {
3298 /// \brief A statement is not an expression statement.
3299 NotAnExpression,
3300 /// \brief Expression is not builtin binary or unary operation.
3301 NotABinaryOrUnaryExpression,
3302 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3303 NotAnUnaryIncDecExpression,
3304 /// \brief An expression is not of scalar type.
3305 NotAScalarType,
3306 /// \brief A binary operation is not an assignment operation.
3307 NotAnAssignmentOp,
3308 /// \brief RHS part of the binary operation is not a binary expression.
3309 NotABinaryExpression,
3310 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3311 /// expression.
3312 NotABinaryOperator,
3313 /// \brief RHS binary operation does not have reference to the updated LHS
3314 /// part.
3315 NotAnUpdateExpression,
3316 /// \brief No errors is found.
3317 NoError
3318 };
3319 /// \brief Reference to Sema.
3320 Sema &SemaRef;
3321 /// \brief A location for note diagnostics (when error is found).
3322 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003323 /// \brief 'x' lvalue part of the source atomic expression.
3324 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003325 /// \brief 'expr' rvalue part of the source atomic expression.
3326 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003327 /// \brief Helper expression of the form
3328 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3329 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3330 Expr *UpdateExpr;
3331 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3332 /// important for non-associative operations.
3333 bool IsXLHSInRHSPart;
3334 BinaryOperatorKind Op;
3335 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003336 /// \brief true if the source expression is a postfix unary operation, false
3337 /// if it is a prefix unary operation.
3338 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003339
3340public:
3341 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003342 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003343 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003344 /// \brief Check specified statement that it is suitable for 'atomic update'
3345 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003346 /// expression. If DiagId and NoteId == 0, then only check is performed
3347 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003348 /// \param DiagId Diagnostic which should be emitted if error is found.
3349 /// \param NoteId Diagnostic note for the main error message.
3350 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003351 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003352 /// \brief Return the 'x' lvalue part of the source atomic expression.
3353 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003354 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3355 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003356 /// \brief Return the update expression used in calculation of the updated
3357 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3358 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3359 Expr *getUpdateExpr() const { return UpdateExpr; }
3360 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3361 /// false otherwise.
3362 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3363
Alexey Bataevb78ca832015-04-01 03:33:17 +00003364 /// \brief true if the source expression is a postfix unary operation, false
3365 /// if it is a prefix unary operation.
3366 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3367
Alexey Bataev1d160b12015-03-13 12:27:31 +00003368private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003369 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3370 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003371};
3372} // namespace
3373
3374bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3375 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3376 ExprAnalysisErrorCode ErrorFound = NoError;
3377 SourceLocation ErrorLoc, NoteLoc;
3378 SourceRange ErrorRange, NoteRange;
3379 // Allowed constructs are:
3380 // x = x binop expr;
3381 // x = expr binop x;
3382 if (AtomicBinOp->getOpcode() == BO_Assign) {
3383 X = AtomicBinOp->getLHS();
3384 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3385 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3386 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3387 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3388 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003389 Op = AtomicInnerBinOp->getOpcode();
3390 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003391 auto *LHS = AtomicInnerBinOp->getLHS();
3392 auto *RHS = AtomicInnerBinOp->getRHS();
3393 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3394 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3395 /*Canonical=*/true);
3396 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3397 /*Canonical=*/true);
3398 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3399 /*Canonical=*/true);
3400 if (XId == LHSId) {
3401 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003402 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003403 } else if (XId == RHSId) {
3404 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003405 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003406 } else {
3407 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3408 ErrorRange = AtomicInnerBinOp->getSourceRange();
3409 NoteLoc = X->getExprLoc();
3410 NoteRange = X->getSourceRange();
3411 ErrorFound = NotAnUpdateExpression;
3412 }
3413 } else {
3414 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3415 ErrorRange = AtomicInnerBinOp->getSourceRange();
3416 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3417 NoteRange = SourceRange(NoteLoc, NoteLoc);
3418 ErrorFound = NotABinaryOperator;
3419 }
3420 } else {
3421 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3422 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3423 ErrorFound = NotABinaryExpression;
3424 }
3425 } else {
3426 ErrorLoc = AtomicBinOp->getExprLoc();
3427 ErrorRange = AtomicBinOp->getSourceRange();
3428 NoteLoc = AtomicBinOp->getOperatorLoc();
3429 NoteRange = SourceRange(NoteLoc, NoteLoc);
3430 ErrorFound = NotAnAssignmentOp;
3431 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003432 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003433 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3434 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3435 return true;
3436 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003437 E = X = UpdateExpr = nullptr;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003438 return false;
3439}
3440
3441bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3442 unsigned NoteId) {
3443 ExprAnalysisErrorCode ErrorFound = NoError;
3444 SourceLocation ErrorLoc, NoteLoc;
3445 SourceRange ErrorRange, NoteRange;
3446 // Allowed constructs are:
3447 // x++;
3448 // x--;
3449 // ++x;
3450 // --x;
3451 // x binop= expr;
3452 // x = x binop expr;
3453 // x = expr binop x;
3454 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3455 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3456 if (AtomicBody->getType()->isScalarType() ||
3457 AtomicBody->isInstantiationDependent()) {
3458 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3459 AtomicBody->IgnoreParenImpCasts())) {
3460 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003461 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003462 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003463 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003464 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003465 X = AtomicCompAssignOp->getLHS();
3466 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003467 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3468 AtomicBody->IgnoreParenImpCasts())) {
3469 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003470 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3471 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003472 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003473 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3474 // Check for Unary Operation
3475 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003476 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003477 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3478 OpLoc = AtomicUnaryOp->getOperatorLoc();
3479 X = AtomicUnaryOp->getSubExpr();
3480 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3481 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003482 } else {
3483 ErrorFound = NotAnUnaryIncDecExpression;
3484 ErrorLoc = AtomicUnaryOp->getExprLoc();
3485 ErrorRange = AtomicUnaryOp->getSourceRange();
3486 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3487 NoteRange = SourceRange(NoteLoc, NoteLoc);
3488 }
3489 } else {
3490 ErrorFound = NotABinaryOrUnaryExpression;
3491 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3492 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3493 }
3494 } else {
3495 ErrorFound = NotAScalarType;
3496 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3497 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3498 }
3499 } else {
3500 ErrorFound = NotAnExpression;
3501 NoteLoc = ErrorLoc = S->getLocStart();
3502 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3503 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003504 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003505 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3506 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3507 return true;
3508 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003509 E = X = UpdateExpr = nullptr;
3510 if (E && X) {
3511 // Build an update expression of form 'OpaqueValueExpr(x) binop
3512 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3513 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3514 auto *OVEX = new (SemaRef.getASTContext())
3515 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3516 auto *OVEExpr = new (SemaRef.getASTContext())
3517 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3518 auto Update =
3519 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3520 IsXLHSInRHSPart ? OVEExpr : OVEX);
3521 if (Update.isInvalid())
3522 return true;
3523 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3524 Sema::AA_Casting);
3525 if (Update.isInvalid())
3526 return true;
3527 UpdateExpr = Update.get();
3528 }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003529 return false;
3530}
3531
Alexey Bataev0162e452014-07-22 10:10:35 +00003532StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3533 Stmt *AStmt,
3534 SourceLocation StartLoc,
3535 SourceLocation EndLoc) {
3536 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003537 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003538 // 1.2.2 OpenMP Language Terminology
3539 // Structured block - An executable statement with a single entry at the
3540 // top and a single exit at the bottom.
3541 // The point of exit cannot be a branch out of the structured block.
3542 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003543 OpenMPClauseKind AtomicKind = OMPC_unknown;
3544 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003545 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003546 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003547 C->getClauseKind() == OMPC_update ||
3548 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003549 if (AtomicKind != OMPC_unknown) {
3550 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3551 << SourceRange(C->getLocStart(), C->getLocEnd());
3552 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3553 << getOpenMPClauseName(AtomicKind);
3554 } else {
3555 AtomicKind = C->getClauseKind();
3556 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003557 }
3558 }
3559 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003560
Alexey Bataev459dec02014-07-24 06:46:57 +00003561 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003562 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3563 Body = EWC->getSubExpr();
3564
Alexey Bataev62cec442014-11-18 10:14:22 +00003565 Expr *X = nullptr;
3566 Expr *V = nullptr;
3567 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003568 Expr *UE = nullptr;
3569 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003570 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003571 // OpenMP [2.12.6, atomic Construct]
3572 // In the next expressions:
3573 // * x and v (as applicable) are both l-value expressions with scalar type.
3574 // * During the execution of an atomic region, multiple syntactic
3575 // occurrences of x must designate the same storage location.
3576 // * Neither of v and expr (as applicable) may access the storage location
3577 // designated by x.
3578 // * Neither of x and expr (as applicable) may access the storage location
3579 // designated by v.
3580 // * expr is an expression with scalar type.
3581 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3582 // * binop, binop=, ++, and -- are not overloaded operators.
3583 // * The expression x binop expr must be numerically equivalent to x binop
3584 // (expr). This requirement is satisfied if the operators in expr have
3585 // precedence greater than binop, or by using parentheses around expr or
3586 // subexpressions of expr.
3587 // * The expression expr binop x must be numerically equivalent to (expr)
3588 // binop x. This requirement is satisfied if the operators in expr have
3589 // precedence equal to or greater than binop, or by using parentheses around
3590 // expr or subexpressions of expr.
3591 // * For forms that allow multiple occurrences of x, the number of times
3592 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003593 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003594 enum {
3595 NotAnExpression,
3596 NotAnAssignmentOp,
3597 NotAScalarType,
3598 NotAnLValue,
3599 NoError
3600 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003601 SourceLocation ErrorLoc, NoteLoc;
3602 SourceRange ErrorRange, NoteRange;
3603 // If clause is read:
3604 // v = x;
3605 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3606 auto AtomicBinOp =
3607 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3608 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3609 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3610 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3611 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3612 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3613 if (!X->isLValue() || !V->isLValue()) {
3614 auto NotLValueExpr = X->isLValue() ? V : X;
3615 ErrorFound = NotAnLValue;
3616 ErrorLoc = AtomicBinOp->getExprLoc();
3617 ErrorRange = AtomicBinOp->getSourceRange();
3618 NoteLoc = NotLValueExpr->getExprLoc();
3619 NoteRange = NotLValueExpr->getSourceRange();
3620 }
3621 } else if (!X->isInstantiationDependent() ||
3622 !V->isInstantiationDependent()) {
3623 auto NotScalarExpr =
3624 (X->isInstantiationDependent() || X->getType()->isScalarType())
3625 ? V
3626 : X;
3627 ErrorFound = NotAScalarType;
3628 ErrorLoc = AtomicBinOp->getExprLoc();
3629 ErrorRange = AtomicBinOp->getSourceRange();
3630 NoteLoc = NotScalarExpr->getExprLoc();
3631 NoteRange = NotScalarExpr->getSourceRange();
3632 }
3633 } else {
3634 ErrorFound = NotAnAssignmentOp;
3635 ErrorLoc = AtomicBody->getExprLoc();
3636 ErrorRange = AtomicBody->getSourceRange();
3637 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3638 : AtomicBody->getExprLoc();
3639 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3640 : AtomicBody->getSourceRange();
3641 }
3642 } else {
3643 ErrorFound = NotAnExpression;
3644 NoteLoc = ErrorLoc = Body->getLocStart();
3645 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003646 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003647 if (ErrorFound != NoError) {
3648 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3649 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003650 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3651 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003652 return StmtError();
3653 } else if (CurContext->isDependentContext())
3654 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003655 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003656 enum {
3657 NotAnExpression,
3658 NotAnAssignmentOp,
3659 NotAScalarType,
3660 NotAnLValue,
3661 NoError
3662 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003663 SourceLocation ErrorLoc, NoteLoc;
3664 SourceRange ErrorRange, NoteRange;
3665 // If clause is write:
3666 // x = expr;
3667 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3668 auto AtomicBinOp =
3669 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3670 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003671 X = AtomicBinOp->getLHS();
3672 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003673 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3674 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3675 if (!X->isLValue()) {
3676 ErrorFound = NotAnLValue;
3677 ErrorLoc = AtomicBinOp->getExprLoc();
3678 ErrorRange = AtomicBinOp->getSourceRange();
3679 NoteLoc = X->getExprLoc();
3680 NoteRange = X->getSourceRange();
3681 }
3682 } else if (!X->isInstantiationDependent() ||
3683 !E->isInstantiationDependent()) {
3684 auto NotScalarExpr =
3685 (X->isInstantiationDependent() || X->getType()->isScalarType())
3686 ? E
3687 : X;
3688 ErrorFound = NotAScalarType;
3689 ErrorLoc = AtomicBinOp->getExprLoc();
3690 ErrorRange = AtomicBinOp->getSourceRange();
3691 NoteLoc = NotScalarExpr->getExprLoc();
3692 NoteRange = NotScalarExpr->getSourceRange();
3693 }
3694 } else {
3695 ErrorFound = NotAnAssignmentOp;
3696 ErrorLoc = AtomicBody->getExprLoc();
3697 ErrorRange = AtomicBody->getSourceRange();
3698 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3699 : AtomicBody->getExprLoc();
3700 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3701 : AtomicBody->getSourceRange();
3702 }
3703 } else {
3704 ErrorFound = NotAnExpression;
3705 NoteLoc = ErrorLoc = Body->getLocStart();
3706 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003707 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003708 if (ErrorFound != NoError) {
3709 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3710 << ErrorRange;
3711 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3712 << NoteRange;
3713 return StmtError();
3714 } else if (CurContext->isDependentContext())
3715 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003716 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003717 // If clause is update:
3718 // x++;
3719 // x--;
3720 // ++x;
3721 // --x;
3722 // x binop= expr;
3723 // x = x binop expr;
3724 // x = expr binop x;
3725 OpenMPAtomicUpdateChecker Checker(*this);
3726 if (Checker.checkStatement(
3727 Body, (AtomicKind == OMPC_update)
3728 ? diag::err_omp_atomic_update_not_expression_statement
3729 : diag::err_omp_atomic_not_expression_statement,
3730 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003731 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003732 if (!CurContext->isDependentContext()) {
3733 E = Checker.getExpr();
3734 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003735 UE = Checker.getUpdateExpr();
3736 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003737 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003738 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003739 enum {
3740 NotAnAssignmentOp,
3741 NotACompoundStatement,
3742 NotTwoSubstatements,
3743 NotASpecificExpression,
3744 NoError
3745 } ErrorFound = NoError;
3746 SourceLocation ErrorLoc, NoteLoc;
3747 SourceRange ErrorRange, NoteRange;
3748 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3749 // If clause is a capture:
3750 // v = x++;
3751 // v = x--;
3752 // v = ++x;
3753 // v = --x;
3754 // v = x binop= expr;
3755 // v = x = x binop expr;
3756 // v = x = expr binop x;
3757 auto *AtomicBinOp =
3758 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3759 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3760 V = AtomicBinOp->getLHS();
3761 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3762 OpenMPAtomicUpdateChecker Checker(*this);
3763 if (Checker.checkStatement(
3764 Body, diag::err_omp_atomic_capture_not_expression_statement,
3765 diag::note_omp_atomic_update))
3766 return StmtError();
3767 E = Checker.getExpr();
3768 X = Checker.getX();
3769 UE = Checker.getUpdateExpr();
3770 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3771 IsPostfixUpdate = Checker.isPostfixUpdate();
3772 } else {
3773 ErrorLoc = AtomicBody->getExprLoc();
3774 ErrorRange = AtomicBody->getSourceRange();
3775 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3776 : AtomicBody->getExprLoc();
3777 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3778 : AtomicBody->getSourceRange();
3779 ErrorFound = NotAnAssignmentOp;
3780 }
3781 if (ErrorFound != NoError) {
3782 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3783 << ErrorRange;
3784 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3785 return StmtError();
3786 } else if (CurContext->isDependentContext()) {
3787 UE = V = E = X = nullptr;
3788 }
3789 } else {
3790 // If clause is a capture:
3791 // { v = x; x = expr; }
3792 // { v = x; x++; }
3793 // { v = x; x--; }
3794 // { v = x; ++x; }
3795 // { v = x; --x; }
3796 // { v = x; x binop= expr; }
3797 // { v = x; x = x binop expr; }
3798 // { v = x; x = expr binop x; }
3799 // { x++; v = x; }
3800 // { x--; v = x; }
3801 // { ++x; v = x; }
3802 // { --x; v = x; }
3803 // { x binop= expr; v = x; }
3804 // { x = x binop expr; v = x; }
3805 // { x = expr binop x; v = x; }
3806 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3807 // Check that this is { expr1; expr2; }
3808 if (CS->size() == 2) {
3809 auto *First = CS->body_front();
3810 auto *Second = CS->body_back();
3811 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3812 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3813 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3814 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3815 // Need to find what subexpression is 'v' and what is 'x'.
3816 OpenMPAtomicUpdateChecker Checker(*this);
3817 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3818 BinaryOperator *BinOp = nullptr;
3819 if (IsUpdateExprFound) {
3820 BinOp = dyn_cast<BinaryOperator>(First);
3821 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3822 }
3823 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3824 // { v = x; x++; }
3825 // { v = x; x--; }
3826 // { v = x; ++x; }
3827 // { v = x; --x; }
3828 // { v = x; x binop= expr; }
3829 // { v = x; x = x binop expr; }
3830 // { v = x; x = expr binop x; }
3831 // Check that the first expression has form v = x.
3832 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3833 llvm::FoldingSetNodeID XId, PossibleXId;
3834 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3835 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3836 IsUpdateExprFound = XId == PossibleXId;
3837 if (IsUpdateExprFound) {
3838 V = BinOp->getLHS();
3839 X = Checker.getX();
3840 E = Checker.getExpr();
3841 UE = Checker.getUpdateExpr();
3842 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3843 IsPostfixUpdate = Checker.isPostfixUpdate();
3844 }
3845 }
3846 if (!IsUpdateExprFound) {
3847 IsUpdateExprFound = !Checker.checkStatement(First);
3848 BinOp = nullptr;
3849 if (IsUpdateExprFound) {
3850 BinOp = dyn_cast<BinaryOperator>(Second);
3851 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3852 }
3853 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3854 // { x++; v = x; }
3855 // { x--; v = x; }
3856 // { ++x; v = x; }
3857 // { --x; v = x; }
3858 // { x binop= expr; v = x; }
3859 // { x = x binop expr; v = x; }
3860 // { x = expr binop x; v = x; }
3861 // Check that the second expression has form v = x.
3862 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3863 llvm::FoldingSetNodeID XId, PossibleXId;
3864 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3865 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3866 IsUpdateExprFound = XId == PossibleXId;
3867 if (IsUpdateExprFound) {
3868 V = BinOp->getLHS();
3869 X = Checker.getX();
3870 E = Checker.getExpr();
3871 UE = Checker.getUpdateExpr();
3872 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3873 IsPostfixUpdate = Checker.isPostfixUpdate();
3874 }
3875 }
3876 }
3877 if (!IsUpdateExprFound) {
3878 // { v = x; x = expr; }
3879 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3880 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3881 ErrorFound = NotAnAssignmentOp;
3882 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3883 : First->getLocStart();
3884 NoteRange = ErrorRange = FirstBinOp
3885 ? FirstBinOp->getSourceRange()
3886 : SourceRange(ErrorLoc, ErrorLoc);
3887 } else {
3888 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3889 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3890 ErrorFound = NotAnAssignmentOp;
3891 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3892 : Second->getLocStart();
3893 NoteRange = ErrorRange = SecondBinOp
3894 ? SecondBinOp->getSourceRange()
3895 : SourceRange(ErrorLoc, ErrorLoc);
3896 } else {
3897 auto *PossibleXRHSInFirst =
3898 FirstBinOp->getRHS()->IgnoreParenImpCasts();
3899 auto *PossibleXLHSInSecond =
3900 SecondBinOp->getLHS()->IgnoreParenImpCasts();
3901 llvm::FoldingSetNodeID X1Id, X2Id;
3902 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
3903 PossibleXLHSInSecond->Profile(X2Id, Context,
3904 /*Canonical=*/true);
3905 IsUpdateExprFound = X1Id == X2Id;
3906 if (IsUpdateExprFound) {
3907 V = FirstBinOp->getLHS();
3908 X = SecondBinOp->getLHS();
3909 E = SecondBinOp->getRHS();
3910 UE = nullptr;
3911 IsXLHSInRHSPart = false;
3912 IsPostfixUpdate = true;
3913 } else {
3914 ErrorFound = NotASpecificExpression;
3915 ErrorLoc = FirstBinOp->getExprLoc();
3916 ErrorRange = FirstBinOp->getSourceRange();
3917 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
3918 NoteRange = SecondBinOp->getRHS()->getSourceRange();
3919 }
3920 }
3921 }
3922 }
3923 } else {
3924 NoteLoc = ErrorLoc = Body->getLocStart();
3925 NoteRange = ErrorRange =
3926 SourceRange(Body->getLocStart(), Body->getLocStart());
3927 ErrorFound = NotTwoSubstatements;
3928 }
3929 } else {
3930 NoteLoc = ErrorLoc = Body->getLocStart();
3931 NoteRange = ErrorRange =
3932 SourceRange(Body->getLocStart(), Body->getLocStart());
3933 ErrorFound = NotACompoundStatement;
3934 }
3935 if (ErrorFound != NoError) {
3936 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
3937 << ErrorRange;
3938 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3939 return StmtError();
3940 } else if (CurContext->isDependentContext()) {
3941 UE = V = E = X = nullptr;
3942 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003943 }
Alexey Bataevdea47612014-07-23 07:46:59 +00003944 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003945
3946 getCurFunction()->setHasBranchProtectedScope();
3947
Alexey Bataev62cec442014-11-18 10:14:22 +00003948 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00003949 X, V, E, UE, IsXLHSInRHSPart,
3950 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00003951}
3952
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003953StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
3954 Stmt *AStmt,
3955 SourceLocation StartLoc,
3956 SourceLocation EndLoc) {
3957 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3958
Alexey Bataev13314bf2014-10-09 04:18:56 +00003959 // OpenMP [2.16, Nesting of Regions]
3960 // If specified, a teams construct must be contained within a target
3961 // construct. That target construct must contain no statements or directives
3962 // outside of the teams construct.
3963 if (DSAStack->hasInnerTeamsRegion()) {
3964 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
3965 bool OMPTeamsFound = true;
3966 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
3967 auto I = CS->body_begin();
3968 while (I != CS->body_end()) {
3969 auto OED = dyn_cast<OMPExecutableDirective>(*I);
3970 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
3971 OMPTeamsFound = false;
3972 break;
3973 }
3974 ++I;
3975 }
3976 assert(I != CS->body_end() && "Not found statement");
3977 S = *I;
3978 }
3979 if (!OMPTeamsFound) {
3980 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
3981 Diag(DSAStack->getInnerTeamsRegionLoc(),
3982 diag::note_omp_nested_teams_construct_here);
3983 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
3984 << isa<OMPExecutableDirective>(S);
3985 return StmtError();
3986 }
3987 }
3988
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003989 getCurFunction()->setHasBranchProtectedScope();
3990
3991 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3992}
3993
Alexey Bataev13314bf2014-10-09 04:18:56 +00003994StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
3995 Stmt *AStmt, SourceLocation StartLoc,
3996 SourceLocation EndLoc) {
3997 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3998 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3999 // 1.2.2 OpenMP Language Terminology
4000 // Structured block - An executable statement with a single entry at the
4001 // top and a single exit at the bottom.
4002 // The point of exit cannot be a branch out of the structured block.
4003 // longjmp() and throw() must not violate the entry/exit criteria.
4004 CS->getCapturedDecl()->setNothrow();
4005
4006 getCurFunction()->setHasBranchProtectedScope();
4007
4008 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4009}
4010
Alexey Bataeved09d242014-05-28 05:53:51 +00004011OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004012 SourceLocation StartLoc,
4013 SourceLocation LParenLoc,
4014 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004015 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004016 switch (Kind) {
4017 case OMPC_if:
4018 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4019 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004020 case OMPC_final:
4021 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4022 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004023 case OMPC_num_threads:
4024 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4025 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004026 case OMPC_safelen:
4027 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4028 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004029 case OMPC_collapse:
4030 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4031 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004032 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004033 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004034 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004035 case OMPC_private:
4036 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004037 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004038 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004039 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004040 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004041 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004042 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004043 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004044 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004045 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004046 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004047 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004048 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004049 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004050 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004051 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004052 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004053 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004054 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004055 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004056 llvm_unreachable("Clause is not allowed.");
4057 }
4058 return Res;
4059}
4060
Alexey Bataeved09d242014-05-28 05:53:51 +00004061OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004062 SourceLocation LParenLoc,
4063 SourceLocation EndLoc) {
4064 Expr *ValExpr = Condition;
4065 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4066 !Condition->isInstantiationDependent() &&
4067 !Condition->containsUnexpandedParameterPack()) {
4068 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004069 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004070 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004071 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004072
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004073 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004074 }
4075
4076 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4077}
4078
Alexey Bataev3778b602014-07-17 07:32:53 +00004079OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4080 SourceLocation StartLoc,
4081 SourceLocation LParenLoc,
4082 SourceLocation EndLoc) {
4083 Expr *ValExpr = Condition;
4084 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4085 !Condition->isInstantiationDependent() &&
4086 !Condition->containsUnexpandedParameterPack()) {
4087 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4088 Condition->getExprLoc(), Condition);
4089 if (Val.isInvalid())
4090 return nullptr;
4091
4092 ValExpr = Val.get();
4093 }
4094
4095 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4096}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004097ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4098 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004099 if (!Op)
4100 return ExprError();
4101
4102 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4103 public:
4104 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004105 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004106 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4107 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004108 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4109 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004110 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4111 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004112 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4113 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004114 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4115 QualType T,
4116 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004117 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4118 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004119 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4120 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004121 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004122 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004123 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004124 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4125 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004126 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4127 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004128 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4129 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004130 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004131 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004132 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004133 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4134 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004135 llvm_unreachable("conversion functions are permitted");
4136 }
4137 } ConvertDiagnoser;
4138 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4139}
4140
4141OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4142 SourceLocation StartLoc,
4143 SourceLocation LParenLoc,
4144 SourceLocation EndLoc) {
4145 Expr *ValExpr = NumThreads;
4146 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004147 !NumThreads->containsUnexpandedParameterPack()) {
4148 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4149 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004150 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004151 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004152 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004153
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004154 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004155
4156 // OpenMP [2.5, Restrictions]
4157 // The num_threads expression must evaluate to a positive integer value.
4158 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004159 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4160 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004161 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4162 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004163 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004164 }
4165 }
4166
Alexey Bataeved09d242014-05-28 05:53:51 +00004167 return new (Context)
4168 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004169}
4170
Alexey Bataev62c87d22014-03-21 04:51:18 +00004171ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4172 OpenMPClauseKind CKind) {
4173 if (!E)
4174 return ExprError();
4175 if (E->isValueDependent() || E->isTypeDependent() ||
4176 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004177 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004178 llvm::APSInt Result;
4179 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4180 if (ICE.isInvalid())
4181 return ExprError();
4182 if (!Result.isStrictlyPositive()) {
4183 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4184 << getOpenMPClauseName(CKind) << E->getSourceRange();
4185 return ExprError();
4186 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004187 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4188 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4189 << E->getSourceRange();
4190 return ExprError();
4191 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004192 return ICE;
4193}
4194
4195OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4196 SourceLocation LParenLoc,
4197 SourceLocation EndLoc) {
4198 // OpenMP [2.8.1, simd construct, Description]
4199 // The parameter of the safelen clause must be a constant
4200 // positive integer expression.
4201 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4202 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004203 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004204 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004205 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004206}
4207
Alexander Musman64d33f12014-06-04 07:53:32 +00004208OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4209 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004210 SourceLocation LParenLoc,
4211 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004212 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004213 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004214 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004215 // The parameter of the collapse clause must be a constant
4216 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004217 ExprResult NumForLoopsResult =
4218 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4219 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004220 return nullptr;
4221 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004222 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004223}
4224
Alexey Bataeved09d242014-05-28 05:53:51 +00004225OMPClause *Sema::ActOnOpenMPSimpleClause(
4226 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4227 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004228 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004229 switch (Kind) {
4230 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004231 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004232 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4233 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004234 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004235 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004236 Res = ActOnOpenMPProcBindClause(
4237 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4238 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004239 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004240 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004241 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004242 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004243 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004244 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004245 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004246 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004247 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004248 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004249 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004250 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004251 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004252 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004253 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004254 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004255 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004256 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004257 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004258 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004259 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004260 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004261 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004262 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004263 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004264 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004265 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004266 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004267 llvm_unreachable("Clause is not allowed.");
4268 }
4269 return Res;
4270}
4271
4272OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4273 SourceLocation KindKwLoc,
4274 SourceLocation StartLoc,
4275 SourceLocation LParenLoc,
4276 SourceLocation EndLoc) {
4277 if (Kind == OMPC_DEFAULT_unknown) {
4278 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004279 static_assert(OMPC_DEFAULT_unknown > 0,
4280 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004281 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004282 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004283 Values += "'";
4284 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4285 Values += "'";
4286 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004287 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004288 Values += " or ";
4289 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004290 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004291 break;
4292 default:
4293 Values += Sep;
4294 break;
4295 }
4296 }
4297 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004298 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004299 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004300 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004301 switch (Kind) {
4302 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004303 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004304 break;
4305 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004306 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004307 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004308 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004309 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004310 break;
4311 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004312 return new (Context)
4313 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004314}
4315
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004316OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4317 SourceLocation KindKwLoc,
4318 SourceLocation StartLoc,
4319 SourceLocation LParenLoc,
4320 SourceLocation EndLoc) {
4321 if (Kind == OMPC_PROC_BIND_unknown) {
4322 std::string Values;
4323 std::string Sep(", ");
4324 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4325 Values += "'";
4326 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4327 Values += "'";
4328 switch (i) {
4329 case OMPC_PROC_BIND_unknown - 2:
4330 Values += " or ";
4331 break;
4332 case OMPC_PROC_BIND_unknown - 1:
4333 break;
4334 default:
4335 Values += Sep;
4336 break;
4337 }
4338 }
4339 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004340 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004341 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004342 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004343 return new (Context)
4344 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004345}
4346
Alexey Bataev56dafe82014-06-20 07:16:17 +00004347OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4348 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4349 SourceLocation StartLoc, SourceLocation LParenLoc,
4350 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4351 SourceLocation EndLoc) {
4352 OMPClause *Res = nullptr;
4353 switch (Kind) {
4354 case OMPC_schedule:
4355 Res = ActOnOpenMPScheduleClause(
4356 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4357 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4358 break;
4359 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004360 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004361 case OMPC_num_threads:
4362 case OMPC_safelen:
4363 case OMPC_collapse:
4364 case OMPC_default:
4365 case OMPC_proc_bind:
4366 case OMPC_private:
4367 case OMPC_firstprivate:
4368 case OMPC_lastprivate:
4369 case OMPC_shared:
4370 case OMPC_reduction:
4371 case OMPC_linear:
4372 case OMPC_aligned:
4373 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004374 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004375 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004376 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004377 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004378 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004379 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004380 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004381 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004382 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004383 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004384 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004385 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004386 case OMPC_unknown:
4387 llvm_unreachable("Clause is not allowed.");
4388 }
4389 return Res;
4390}
4391
4392OMPClause *Sema::ActOnOpenMPScheduleClause(
4393 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4394 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4395 SourceLocation EndLoc) {
4396 if (Kind == OMPC_SCHEDULE_unknown) {
4397 std::string Values;
4398 std::string Sep(", ");
4399 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4400 Values += "'";
4401 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4402 Values += "'";
4403 switch (i) {
4404 case OMPC_SCHEDULE_unknown - 2:
4405 Values += " or ";
4406 break;
4407 case OMPC_SCHEDULE_unknown - 1:
4408 break;
4409 default:
4410 Values += Sep;
4411 break;
4412 }
4413 }
4414 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4415 << Values << getOpenMPClauseName(OMPC_schedule);
4416 return nullptr;
4417 }
4418 Expr *ValExpr = ChunkSize;
4419 if (ChunkSize) {
4420 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4421 !ChunkSize->isInstantiationDependent() &&
4422 !ChunkSize->containsUnexpandedParameterPack()) {
4423 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4424 ExprResult Val =
4425 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4426 if (Val.isInvalid())
4427 return nullptr;
4428
4429 ValExpr = Val.get();
4430
4431 // OpenMP [2.7.1, Restrictions]
4432 // chunk_size must be a loop invariant integer expression with a positive
4433 // value.
4434 llvm::APSInt Result;
4435 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
4436 Result.isSigned() && !Result.isStrictlyPositive()) {
4437 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4438 << "schedule" << ChunkSize->getSourceRange();
4439 return nullptr;
4440 }
4441 }
4442 }
4443
4444 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4445 EndLoc, Kind, ValExpr);
4446}
4447
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004448OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4449 SourceLocation StartLoc,
4450 SourceLocation EndLoc) {
4451 OMPClause *Res = nullptr;
4452 switch (Kind) {
4453 case OMPC_ordered:
4454 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4455 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004456 case OMPC_nowait:
4457 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4458 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004459 case OMPC_untied:
4460 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4461 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004462 case OMPC_mergeable:
4463 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4464 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004465 case OMPC_read:
4466 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4467 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004468 case OMPC_write:
4469 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4470 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004471 case OMPC_update:
4472 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4473 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004474 case OMPC_capture:
4475 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4476 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004477 case OMPC_seq_cst:
4478 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4479 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004480 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004481 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004482 case OMPC_num_threads:
4483 case OMPC_safelen:
4484 case OMPC_collapse:
4485 case OMPC_schedule:
4486 case OMPC_private:
4487 case OMPC_firstprivate:
4488 case OMPC_lastprivate:
4489 case OMPC_shared:
4490 case OMPC_reduction:
4491 case OMPC_linear:
4492 case OMPC_aligned:
4493 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004494 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004495 case OMPC_default:
4496 case OMPC_proc_bind:
4497 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004498 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004499 case OMPC_unknown:
4500 llvm_unreachable("Clause is not allowed.");
4501 }
4502 return Res;
4503}
4504
4505OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4506 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004507 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004508 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4509}
4510
Alexey Bataev236070f2014-06-20 11:19:47 +00004511OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4512 SourceLocation EndLoc) {
4513 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4514}
4515
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004516OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4517 SourceLocation EndLoc) {
4518 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4519}
4520
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004521OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4522 SourceLocation EndLoc) {
4523 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4524}
4525
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004526OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4527 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004528 return new (Context) OMPReadClause(StartLoc, EndLoc);
4529}
4530
Alexey Bataevdea47612014-07-23 07:46:59 +00004531OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4532 SourceLocation EndLoc) {
4533 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4534}
4535
Alexey Bataev67a4f222014-07-23 10:25:33 +00004536OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4537 SourceLocation EndLoc) {
4538 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4539}
4540
Alexey Bataev459dec02014-07-24 06:46:57 +00004541OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4542 SourceLocation EndLoc) {
4543 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4544}
4545
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004546OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4547 SourceLocation EndLoc) {
4548 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4549}
4550
Alexey Bataevc5e02582014-06-16 07:08:35 +00004551OMPClause *Sema::ActOnOpenMPVarListClause(
4552 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4553 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4554 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4555 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004556 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004557 switch (Kind) {
4558 case OMPC_private:
4559 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4560 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004561 case OMPC_firstprivate:
4562 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4563 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004564 case OMPC_lastprivate:
4565 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4566 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004567 case OMPC_shared:
4568 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4569 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004570 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004571 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4572 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004573 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004574 case OMPC_linear:
4575 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4576 ColonLoc, EndLoc);
4577 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004578 case OMPC_aligned:
4579 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4580 ColonLoc, EndLoc);
4581 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004582 case OMPC_copyin:
4583 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4584 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004585 case OMPC_copyprivate:
4586 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4587 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004588 case OMPC_flush:
4589 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4590 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004591 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004592 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004593 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004594 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004595 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004596 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004597 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004598 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004599 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004600 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004601 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004602 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004603 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004604 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004605 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004606 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004607 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004608 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004609 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004610 llvm_unreachable("Clause is not allowed.");
4611 }
4612 return Res;
4613}
4614
4615OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4616 SourceLocation StartLoc,
4617 SourceLocation LParenLoc,
4618 SourceLocation EndLoc) {
4619 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004620 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004621 for (auto &RefExpr : VarList) {
4622 assert(RefExpr && "NULL expr in OpenMP private clause.");
4623 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004624 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004625 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004626 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004627 continue;
4628 }
4629
Alexey Bataeved09d242014-05-28 05:53:51 +00004630 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004631 // OpenMP [2.1, C/C++]
4632 // A list item is a variable name.
4633 // OpenMP [2.9.3.3, Restrictions, p.1]
4634 // A variable that is part of another variable (as an array or
4635 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004636 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004637 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004638 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004639 continue;
4640 }
4641 Decl *D = DE->getDecl();
4642 VarDecl *VD = cast<VarDecl>(D);
4643
4644 QualType Type = VD->getType();
4645 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4646 // It will be analyzed later.
4647 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004648 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004649 continue;
4650 }
4651
4652 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4653 // A variable that appears in a private clause must not have an incomplete
4654 // type or a reference type.
4655 if (RequireCompleteType(ELoc, Type,
4656 diag::err_omp_private_incomplete_type)) {
4657 continue;
4658 }
4659 if (Type->isReferenceType()) {
4660 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004661 << getOpenMPClauseName(OMPC_private) << Type;
4662 bool IsDecl =
4663 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4664 Diag(VD->getLocation(),
4665 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4666 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004667 continue;
4668 }
4669
4670 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4671 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004672 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004673 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004674 while (Type->isArrayType()) {
4675 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004676 }
4677
Alexey Bataev758e55e2013-09-06 18:03:48 +00004678 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4679 // in a Construct]
4680 // Variables with the predetermined data-sharing attributes may not be
4681 // listed in data-sharing attributes clauses, except for the cases
4682 // listed below. For these exceptions only, listing a predetermined
4683 // variable in a data-sharing attribute clause is allowed and overrides
4684 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004685 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004686 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004687 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4688 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004689 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004690 continue;
4691 }
4692
Alexey Bataev03b340a2014-10-21 03:16:40 +00004693 // Generate helper private variable and initialize it with the default
4694 // value. The address of the original variable is replaced by the address of
4695 // the new private variable in CodeGen. This new variable is not added to
4696 // IdResolver, so the code in the OpenMP region uses original variable for
4697 // proper diagnostics.
4698 auto VDPrivate =
4699 VarDecl::Create(Context, CurContext, DE->getLocStart(),
4700 DE->getExprLoc(), VD->getIdentifier(), VD->getType(),
4701 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4702 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4703 if (VDPrivate->isInvalidDecl())
4704 continue;
4705 CurContext->addDecl(VDPrivate);
Alexey Bataev07649fb2014-12-16 08:01:48 +00004706 auto VDPrivateRefExpr =
4707 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4708 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004709 /*RefersToEnclosingVariableOrCapture*/ false,
Alexey Bataev07649fb2014-12-16 08:01:48 +00004710 /*NameLoc*/ SourceLocation(), DE->getType(),
4711 /*VK*/ VK_LValue);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004712
Alexey Bataev758e55e2013-09-06 18:03:48 +00004713 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004714 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004715 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004716 }
4717
Alexey Bataeved09d242014-05-28 05:53:51 +00004718 if (Vars.empty())
4719 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004720
Alexey Bataev03b340a2014-10-21 03:16:40 +00004721 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4722 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004723}
4724
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004725namespace {
4726class DiagsUninitializedSeveretyRAII {
4727private:
4728 DiagnosticsEngine &Diags;
4729 SourceLocation SavedLoc;
4730 bool IsIgnored;
4731
4732public:
4733 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4734 bool IsIgnored)
4735 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4736 if (!IsIgnored) {
4737 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4738 /*Map*/ diag::Severity::Ignored, Loc);
4739 }
4740 }
4741 ~DiagsUninitializedSeveretyRAII() {
4742 if (!IsIgnored)
4743 Diags.popMappings(SavedLoc);
4744 }
4745};
4746}
4747
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004748OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4749 SourceLocation StartLoc,
4750 SourceLocation LParenLoc,
4751 SourceLocation EndLoc) {
4752 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004753 SmallVector<Expr *, 8> PrivateCopies;
4754 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004755 bool IsImplicitClause =
4756 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4757 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4758
Alexey Bataeved09d242014-05-28 05:53:51 +00004759 for (auto &RefExpr : VarList) {
4760 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4761 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004762 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004763 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004764 PrivateCopies.push_back(nullptr);
4765 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004766 continue;
4767 }
4768
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004769 SourceLocation ELoc =
4770 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004771 // OpenMP [2.1, C/C++]
4772 // A list item is a variable name.
4773 // OpenMP [2.9.3.3, Restrictions, p.1]
4774 // A variable that is part of another variable (as an array or
4775 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004776 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004777 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004778 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004779 continue;
4780 }
4781 Decl *D = DE->getDecl();
4782 VarDecl *VD = cast<VarDecl>(D);
4783
4784 QualType Type = VD->getType();
4785 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4786 // It will be analyzed later.
4787 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004788 PrivateCopies.push_back(nullptr);
4789 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004790 continue;
4791 }
4792
4793 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4794 // A variable that appears in a private clause must not have an incomplete
4795 // type or a reference type.
4796 if (RequireCompleteType(ELoc, Type,
4797 diag::err_omp_firstprivate_incomplete_type)) {
4798 continue;
4799 }
4800 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004801 if (IsImplicitClause) {
4802 Diag(ImplicitClauseLoc,
4803 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4804 << Type;
4805 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4806 } else {
4807 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4808 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4809 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004810 bool IsDecl =
4811 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4812 Diag(VD->getLocation(),
4813 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4814 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004815 continue;
4816 }
4817
4818 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4819 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004820 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004821 // class type.
Alexey Bataev69c62a92015-04-15 04:52:20 +00004822 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004823
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004824 // If an implicit firstprivate variable found it was checked already.
4825 if (!IsImplicitClause) {
4826 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004827 Type = Type.getNonReferenceType().getCanonicalType();
4828 bool IsConstant = Type.isConstant(Context);
4829 Type = Context.getBaseElementType(Type);
4830 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4831 // A list item that specifies a given variable may not appear in more
4832 // than one clause on the same directive, except that a variable may be
4833 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004834 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004835 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004836 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004837 << getOpenMPClauseName(DVar.CKind)
4838 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004839 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004840 continue;
4841 }
4842
4843 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4844 // in a Construct]
4845 // Variables with the predetermined data-sharing attributes may not be
4846 // listed in data-sharing attributes clauses, except for the cases
4847 // listed below. For these exceptions only, listing a predetermined
4848 // variable in a data-sharing attribute clause is allowed and overrides
4849 // the variable's predetermined data-sharing attributes.
4850 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4851 // in a Construct, C/C++, p.2]
4852 // Variables with const-qualified type having no mutable member may be
4853 // listed in a firstprivate clause, even if they are static data members.
4854 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4855 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4856 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004857 << getOpenMPClauseName(DVar.CKind)
4858 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004859 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004860 continue;
4861 }
4862
Alexey Bataevf29276e2014-06-18 04:14:57 +00004863 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004864 // OpenMP [2.9.3.4, Restrictions, p.2]
4865 // A list item that is private within a parallel region must not appear
4866 // in a firstprivate clause on a worksharing construct if any of the
4867 // worksharing regions arising from the worksharing construct ever bind
4868 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004869 if (isOpenMPWorksharingDirective(CurrDir) &&
4870 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004871 DVar = DSAStack->getImplicitDSA(VD, true);
4872 if (DVar.CKind != OMPC_shared &&
4873 (isOpenMPParallelDirective(DVar.DKind) ||
4874 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004875 Diag(ELoc, diag::err_omp_required_access)
4876 << getOpenMPClauseName(OMPC_firstprivate)
4877 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004878 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004879 continue;
4880 }
4881 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004882 // OpenMP [2.9.3.4, Restrictions, p.3]
4883 // A list item that appears in a reduction clause of a parallel construct
4884 // must not appear in a firstprivate clause on a worksharing or task
4885 // construct if any of the worksharing or task regions arising from the
4886 // worksharing or task construct ever bind to any of the parallel regions
4887 // arising from the parallel construct.
4888 // OpenMP [2.9.3.4, Restrictions, p.4]
4889 // A list item that appears in a reduction clause in worksharing
4890 // construct must not appear in a firstprivate clause in a task construct
4891 // encountered during execution of any of the worksharing regions arising
4892 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004893 if (CurrDir == OMPD_task) {
4894 DVar =
4895 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4896 [](OpenMPDirectiveKind K) -> bool {
4897 return isOpenMPParallelDirective(K) ||
4898 isOpenMPWorksharingDirective(K);
4899 },
4900 false);
4901 if (DVar.CKind == OMPC_reduction &&
4902 (isOpenMPParallelDirective(DVar.DKind) ||
4903 isOpenMPWorksharingDirective(DVar.DKind))) {
4904 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4905 << getOpenMPDirectiveName(DVar.DKind);
4906 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4907 continue;
4908 }
4909 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004910 }
4911
Alexey Bataev69c62a92015-04-15 04:52:20 +00004912 auto VDPrivate =
4913 VarDecl::Create(Context, CurContext, DE->getLocStart(), ELoc,
4914 VD->getIdentifier(), VD->getType().getUnqualifiedType(),
4915 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004916 // Generate helper private variable and initialize it with the value of the
4917 // original variable. The address of the original variable is replaced by
4918 // the address of the new private variable in the CodeGen. This new variable
4919 // is not added to IdResolver, so the code in the OpenMP region uses
4920 // original variable for proper diagnostics and variable capturing.
4921 Expr *VDInitRefExpr = nullptr;
4922 // For arrays generate initializer for single element and replace it by the
4923 // original array element in CodeGen.
4924 if (DE->getType()->isArrayType()) {
4925 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4926 ELoc, VD->getIdentifier(), Type,
4927 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
4928 CurContext->addHiddenDecl(VDInit);
4929 VDInitRefExpr = DeclRefExpr::Create(
4930 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4931 /*TemplateKWLoc*/ SourceLocation(), VDInit,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004932 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004933 /*VK*/ VK_LValue);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004934 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataev69c62a92015-04-15 04:52:20 +00004935 auto *VDInitTemp =
4936 BuildVarDecl(*this, DE->getLocStart(), Type.getUnqualifiedType(),
4937 ".firstprivate.temp");
4938 InitializedEntity Entity =
4939 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004940 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
4941
4942 InitializationSequence InitSeq(*this, Entity, Kind, Init);
4943 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
4944 if (Result.isInvalid())
4945 VDPrivate->setInvalidDecl();
4946 else
4947 VDPrivate->setInit(Result.getAs<Expr>());
4948 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00004949 auto *VDInit =
4950 BuildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
4951 VDInitRefExpr =
4952 BuildDeclRefExpr(VDInit, Type, VK_LValue, DE->getExprLoc()).get();
4953 AddInitializerToDecl(VDPrivate,
4954 DefaultLvalueConversion(VDInitRefExpr).get(),
4955 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004956 }
4957 if (VDPrivate->isInvalidDecl()) {
4958 if (IsImplicitClause) {
4959 Diag(DE->getExprLoc(),
4960 diag::note_omp_task_predetermined_firstprivate_here);
4961 }
4962 continue;
4963 }
4964 CurContext->addDecl(VDPrivate);
Alexey Bataev69c62a92015-04-15 04:52:20 +00004965 auto VDPrivateRefExpr = DeclRefExpr::Create(
4966 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4967 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
4968 /*RefersToEnclosingVariableOrCapture*/ false, DE->getLocStart(),
4969 DE->getType().getUnqualifiedType(), /*VK*/ VK_LValue);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004970 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
4971 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004972 PrivateCopies.push_back(VDPrivateRefExpr);
4973 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004974 }
4975
Alexey Bataeved09d242014-05-28 05:53:51 +00004976 if (Vars.empty())
4977 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004978
4979 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004980 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004981}
4982
Alexander Musman1bb328c2014-06-04 13:06:39 +00004983OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
4984 SourceLocation StartLoc,
4985 SourceLocation LParenLoc,
4986 SourceLocation EndLoc) {
4987 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00004988 SmallVector<Expr *, 8> SrcExprs;
4989 SmallVector<Expr *, 8> DstExprs;
4990 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004991 for (auto &RefExpr : VarList) {
4992 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
4993 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
4994 // It will be analyzed later.
4995 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00004996 SrcExprs.push_back(nullptr);
4997 DstExprs.push_back(nullptr);
4998 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00004999 continue;
5000 }
5001
5002 SourceLocation ELoc = RefExpr->getExprLoc();
5003 // OpenMP [2.1, C/C++]
5004 // A list item is a variable name.
5005 // OpenMP [2.14.3.5, Restrictions, p.1]
5006 // A variable that is part of another variable (as an array or structure
5007 // element) cannot appear in a lastprivate clause.
5008 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5009 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5010 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5011 continue;
5012 }
5013 Decl *D = DE->getDecl();
5014 VarDecl *VD = cast<VarDecl>(D);
5015
5016 QualType Type = VD->getType();
5017 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5018 // It will be analyzed later.
5019 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005020 SrcExprs.push_back(nullptr);
5021 DstExprs.push_back(nullptr);
5022 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005023 continue;
5024 }
5025
5026 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5027 // A variable that appears in a lastprivate clause must not have an
5028 // incomplete type or a reference type.
5029 if (RequireCompleteType(ELoc, Type,
5030 diag::err_omp_lastprivate_incomplete_type)) {
5031 continue;
5032 }
5033 if (Type->isReferenceType()) {
5034 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5035 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5036 bool IsDecl =
5037 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5038 Diag(VD->getLocation(),
5039 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5040 << VD;
5041 continue;
5042 }
5043
5044 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5045 // in a Construct]
5046 // Variables with the predetermined data-sharing attributes may not be
5047 // listed in data-sharing attributes clauses, except for the cases
5048 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005049 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005050 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5051 DVar.CKind != OMPC_firstprivate &&
5052 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5053 Diag(ELoc, diag::err_omp_wrong_dsa)
5054 << getOpenMPClauseName(DVar.CKind)
5055 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005056 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005057 continue;
5058 }
5059
Alexey Bataevf29276e2014-06-18 04:14:57 +00005060 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5061 // OpenMP [2.14.3.5, Restrictions, p.2]
5062 // A list item that is private within a parallel region, or that appears in
5063 // the reduction clause of a parallel construct, must not appear in a
5064 // lastprivate clause on a worksharing construct if any of the corresponding
5065 // worksharing regions ever binds to any of the corresponding parallel
5066 // regions.
Alexey Bataev549210e2014-06-24 04:39:47 +00005067 if (isOpenMPWorksharingDirective(CurrDir) &&
5068 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005069 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005070 if (DVar.CKind != OMPC_shared) {
5071 Diag(ELoc, diag::err_omp_required_access)
5072 << getOpenMPClauseName(OMPC_lastprivate)
5073 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005074 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005075 continue;
5076 }
5077 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005078 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005079 // A variable of class type (or array thereof) that appears in a
5080 // lastprivate clause requires an accessible, unambiguous default
5081 // constructor for the class type, unless the list item is also specified
5082 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005083 // A variable of class type (or array thereof) that appears in a
5084 // lastprivate clause requires an accessible, unambiguous copy assignment
5085 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005086 Type = Context.getBaseElementType(Type).getNonReferenceType();
5087 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(),
5088 Type.getUnqualifiedType(), ".lastprivate.src");
5089 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, Type.getUnqualifiedType(),
5090 VK_LValue, DE->getExprLoc()).get();
5091 auto *DstVD =
5092 BuildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
5093 auto *PseudoDstExpr =
5094 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
5095 // For arrays generate assignment operation for single element and replace
5096 // it by the original array element in CodeGen.
5097 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5098 PseudoDstExpr, PseudoSrcExpr);
5099 if (AssignmentOp.isInvalid())
5100 continue;
5101 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5102 /*DiscardedValue=*/true);
5103 if (AssignmentOp.isInvalid())
5104 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005105
Alexey Bataevf29276e2014-06-18 04:14:57 +00005106 if (DVar.CKind != OMPC_firstprivate)
5107 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005108 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005109 SrcExprs.push_back(PseudoSrcExpr);
5110 DstExprs.push_back(PseudoDstExpr);
5111 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005112 }
5113
5114 if (Vars.empty())
5115 return nullptr;
5116
5117 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005118 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005119}
5120
Alexey Bataev758e55e2013-09-06 18:03:48 +00005121OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5122 SourceLocation StartLoc,
5123 SourceLocation LParenLoc,
5124 SourceLocation EndLoc) {
5125 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005126 for (auto &RefExpr : VarList) {
5127 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5128 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005129 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005130 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005131 continue;
5132 }
5133
Alexey Bataeved09d242014-05-28 05:53:51 +00005134 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005135 // OpenMP [2.1, C/C++]
5136 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005137 // OpenMP [2.14.3.2, Restrictions, p.1]
5138 // A variable that is part of another variable (as an array or structure
5139 // element) cannot appear in a shared unless it is a static data member
5140 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005141 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005142 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005143 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005144 continue;
5145 }
5146 Decl *D = DE->getDecl();
5147 VarDecl *VD = cast<VarDecl>(D);
5148
5149 QualType Type = VD->getType();
5150 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5151 // It will be analyzed later.
5152 Vars.push_back(DE);
5153 continue;
5154 }
5155
5156 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5157 // in a Construct]
5158 // Variables with the predetermined data-sharing attributes may not be
5159 // listed in data-sharing attributes clauses, except for the cases
5160 // listed below. For these exceptions only, listing a predetermined
5161 // variable in a data-sharing attribute clause is allowed and overrides
5162 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005163 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005164 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5165 DVar.RefExpr) {
5166 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5167 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005168 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005169 continue;
5170 }
5171
5172 DSAStack->addDSA(VD, DE, OMPC_shared);
5173 Vars.push_back(DE);
5174 }
5175
Alexey Bataeved09d242014-05-28 05:53:51 +00005176 if (Vars.empty())
5177 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005178
5179 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5180}
5181
Alexey Bataevc5e02582014-06-16 07:08:35 +00005182namespace {
5183class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5184 DSAStackTy *Stack;
5185
5186public:
5187 bool VisitDeclRefExpr(DeclRefExpr *E) {
5188 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005189 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005190 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5191 return false;
5192 if (DVar.CKind != OMPC_unknown)
5193 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005194 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005195 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005196 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005197 return true;
5198 return false;
5199 }
5200 return false;
5201 }
5202 bool VisitStmt(Stmt *S) {
5203 for (auto Child : S->children()) {
5204 if (Child && Visit(Child))
5205 return true;
5206 }
5207 return false;
5208 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005209 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005210};
Alexey Bataev23b69422014-06-18 07:08:49 +00005211} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005212
5213OMPClause *Sema::ActOnOpenMPReductionClause(
5214 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5215 SourceLocation ColonLoc, SourceLocation EndLoc,
5216 CXXScopeSpec &ReductionIdScopeSpec,
5217 const DeclarationNameInfo &ReductionId) {
5218 // TODO: Allow scope specification search when 'declare reduction' is
5219 // supported.
5220 assert(ReductionIdScopeSpec.isEmpty() &&
5221 "No support for scoped reduction identifiers yet.");
5222
5223 auto DN = ReductionId.getName();
5224 auto OOK = DN.getCXXOverloadedOperator();
5225 BinaryOperatorKind BOK = BO_Comma;
5226
5227 // OpenMP [2.14.3.6, reduction clause]
5228 // C
5229 // reduction-identifier is either an identifier or one of the following
5230 // operators: +, -, *, &, |, ^, && and ||
5231 // C++
5232 // reduction-identifier is either an id-expression or one of the following
5233 // operators: +, -, *, &, |, ^, && and ||
5234 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5235 switch (OOK) {
5236 case OO_Plus:
5237 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005238 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005239 break;
5240 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005241 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005242 break;
5243 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005244 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005245 break;
5246 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005247 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005248 break;
5249 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005250 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005251 break;
5252 case OO_AmpAmp:
5253 BOK = BO_LAnd;
5254 break;
5255 case OO_PipePipe:
5256 BOK = BO_LOr;
5257 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005258 case OO_New:
5259 case OO_Delete:
5260 case OO_Array_New:
5261 case OO_Array_Delete:
5262 case OO_Slash:
5263 case OO_Percent:
5264 case OO_Tilde:
5265 case OO_Exclaim:
5266 case OO_Equal:
5267 case OO_Less:
5268 case OO_Greater:
5269 case OO_LessEqual:
5270 case OO_GreaterEqual:
5271 case OO_PlusEqual:
5272 case OO_MinusEqual:
5273 case OO_StarEqual:
5274 case OO_SlashEqual:
5275 case OO_PercentEqual:
5276 case OO_CaretEqual:
5277 case OO_AmpEqual:
5278 case OO_PipeEqual:
5279 case OO_LessLess:
5280 case OO_GreaterGreater:
5281 case OO_LessLessEqual:
5282 case OO_GreaterGreaterEqual:
5283 case OO_EqualEqual:
5284 case OO_ExclaimEqual:
5285 case OO_PlusPlus:
5286 case OO_MinusMinus:
5287 case OO_Comma:
5288 case OO_ArrowStar:
5289 case OO_Arrow:
5290 case OO_Call:
5291 case OO_Subscript:
5292 case OO_Conditional:
5293 case NUM_OVERLOADED_OPERATORS:
5294 llvm_unreachable("Unexpected reduction identifier");
5295 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005296 if (auto II = DN.getAsIdentifierInfo()) {
5297 if (II->isStr("max"))
5298 BOK = BO_GT;
5299 else if (II->isStr("min"))
5300 BOK = BO_LT;
5301 }
5302 break;
5303 }
5304 SourceRange ReductionIdRange;
5305 if (ReductionIdScopeSpec.isValid()) {
5306 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5307 }
5308 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5309 if (BOK == BO_Comma) {
5310 // Not allowed reduction identifier is found.
5311 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5312 << ReductionIdRange;
5313 return nullptr;
5314 }
5315
5316 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005317 SmallVector<Expr *, 8> LHSs;
5318 SmallVector<Expr *, 8> RHSs;
5319 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005320 for (auto RefExpr : VarList) {
5321 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5322 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5323 // It will be analyzed later.
5324 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005325 LHSs.push_back(nullptr);
5326 RHSs.push_back(nullptr);
5327 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005328 continue;
5329 }
5330
5331 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5332 RefExpr->isInstantiationDependent() ||
5333 RefExpr->containsUnexpandedParameterPack()) {
5334 // It will be analyzed later.
5335 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005336 LHSs.push_back(nullptr);
5337 RHSs.push_back(nullptr);
5338 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005339 continue;
5340 }
5341
5342 auto ELoc = RefExpr->getExprLoc();
5343 auto ERange = RefExpr->getSourceRange();
5344 // OpenMP [2.1, C/C++]
5345 // A list item is a variable or array section, subject to the restrictions
5346 // specified in Section 2.4 on page 42 and in each of the sections
5347 // describing clauses and directives for which a list appears.
5348 // OpenMP [2.14.3.3, Restrictions, p.1]
5349 // A variable that is part of another variable (as an array or
5350 // structure element) cannot appear in a private clause.
5351 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5352 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5353 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5354 continue;
5355 }
5356 auto D = DE->getDecl();
5357 auto VD = cast<VarDecl>(D);
5358 auto Type = VD->getType();
5359 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5360 // A variable that appears in a private clause must not have an incomplete
5361 // type or a reference type.
5362 if (RequireCompleteType(ELoc, Type,
5363 diag::err_omp_reduction_incomplete_type))
5364 continue;
5365 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5366 // Arrays may not appear in a reduction clause.
5367 if (Type.getNonReferenceType()->isArrayType()) {
5368 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5369 bool IsDecl =
5370 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5371 Diag(VD->getLocation(),
5372 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5373 << VD;
5374 continue;
5375 }
5376 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5377 // A list item that appears in a reduction clause must not be
5378 // const-qualified.
5379 if (Type.getNonReferenceType().isConstant(Context)) {
5380 Diag(ELoc, diag::err_omp_const_variable)
5381 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5382 bool IsDecl =
5383 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5384 Diag(VD->getLocation(),
5385 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5386 << VD;
5387 continue;
5388 }
5389 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5390 // If a list-item is a reference type then it must bind to the same object
5391 // for all threads of the team.
5392 VarDecl *VDDef = VD->getDefinition();
5393 if (Type->isReferenceType() && VDDef) {
5394 DSARefChecker Check(DSAStack);
5395 if (Check.Visit(VDDef->getInit())) {
5396 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5397 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5398 continue;
5399 }
5400 }
5401 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5402 // The type of a list item that appears in a reduction clause must be valid
5403 // for the reduction-identifier. For a max or min reduction in C, the type
5404 // of the list item must be an allowed arithmetic data type: char, int,
5405 // float, double, or _Bool, possibly modified with long, short, signed, or
5406 // unsigned. For a max or min reduction in C++, the type of the list item
5407 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5408 // double, or bool, possibly modified with long, short, signed, or unsigned.
5409 if ((BOK == BO_GT || BOK == BO_LT) &&
5410 !(Type->isScalarType() ||
5411 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5412 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5413 << getLangOpts().CPlusPlus;
5414 bool IsDecl =
5415 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5416 Diag(VD->getLocation(),
5417 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5418 << VD;
5419 continue;
5420 }
5421 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5422 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5423 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5424 bool IsDecl =
5425 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5426 Diag(VD->getLocation(),
5427 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5428 << VD;
5429 continue;
5430 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005431 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5432 // in a Construct]
5433 // Variables with the predetermined data-sharing attributes may not be
5434 // listed in data-sharing attributes clauses, except for the cases
5435 // listed below. For these exceptions only, listing a predetermined
5436 // variable in a data-sharing attribute clause is allowed and overrides
5437 // the variable's predetermined data-sharing attributes.
5438 // OpenMP [2.14.3.6, Restrictions, p.3]
5439 // Any number of reduction clauses can be specified on the directive,
5440 // but a list item can appear only once in the reduction clauses for that
5441 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005442 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005443 if (DVar.CKind == OMPC_reduction) {
5444 Diag(ELoc, diag::err_omp_once_referenced)
5445 << getOpenMPClauseName(OMPC_reduction);
5446 if (DVar.RefExpr) {
5447 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5448 }
5449 } else if (DVar.CKind != OMPC_unknown) {
5450 Diag(ELoc, diag::err_omp_wrong_dsa)
5451 << getOpenMPClauseName(DVar.CKind)
5452 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005453 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005454 continue;
5455 }
5456
5457 // OpenMP [2.14.3.6, Restrictions, p.1]
5458 // A list item that appears in a reduction clause of a worksharing
5459 // construct must be shared in the parallel regions to which any of the
5460 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005461 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005462 if (isOpenMPWorksharingDirective(CurrDir) &&
5463 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005464 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005465 if (DVar.CKind != OMPC_shared) {
5466 Diag(ELoc, diag::err_omp_required_access)
5467 << getOpenMPClauseName(OMPC_reduction)
5468 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005469 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005470 continue;
5471 }
5472 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005473 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
5474 auto *LHSVD = BuildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5475 auto *RHSVD = BuildVarDecl(*this, ELoc, Type, VD->getName());
5476 // Add initializer for private variable.
5477 Expr *Init = nullptr;
5478 switch (BOK) {
5479 case BO_Add:
5480 case BO_Xor:
5481 case BO_Or:
5482 case BO_LOr:
5483 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5484 if (Type->isScalarType() || Type->isAnyComplexType()) {
5485 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005486 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005487 break;
5488 case BO_Mul:
5489 case BO_LAnd:
5490 if (Type->isScalarType() || Type->isAnyComplexType()) {
5491 // '*' and '&&' reduction ops - initializer is '1'.
5492 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5493 }
5494 break;
5495 case BO_And: {
5496 // '&' reduction op - initializer is '~0'.
5497 QualType OrigType = Type;
5498 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5499 Type = ComplexTy->getElementType();
5500 }
5501 if (Type->isRealFloatingType()) {
5502 llvm::APFloat InitValue =
5503 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5504 /*isIEEE=*/true);
5505 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5506 Type, ELoc);
5507 } else if (Type->isScalarType()) {
5508 auto Size = Context.getTypeSize(Type);
5509 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5510 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5511 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5512 }
5513 if (Init && OrigType->isAnyComplexType()) {
5514 // Init = 0xFFFF + 0xFFFFi;
5515 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5516 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5517 }
5518 Type = OrigType;
5519 break;
5520 }
5521 case BO_LT:
5522 case BO_GT: {
5523 // 'min' reduction op - initializer is 'Largest representable number in
5524 // the reduction list item type'.
5525 // 'max' reduction op - initializer is 'Least representable number in
5526 // the reduction list item type'.
5527 if (Type->isIntegerType() || Type->isPointerType()) {
5528 bool IsSigned = Type->hasSignedIntegerRepresentation();
5529 auto Size = Context.getTypeSize(Type);
5530 QualType IntTy =
5531 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5532 llvm::APInt InitValue =
5533 (BOK != BO_LT)
5534 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5535 : llvm::APInt::getMinValue(Size)
5536 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5537 : llvm::APInt::getMaxValue(Size);
5538 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5539 if (Type->isPointerType()) {
5540 // Cast to pointer type.
5541 auto CastExpr = BuildCStyleCastExpr(
5542 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5543 SourceLocation(), Init);
5544 if (CastExpr.isInvalid())
5545 continue;
5546 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005547 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005548 } else if (Type->isRealFloatingType()) {
5549 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5550 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5551 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5552 Type, ELoc);
5553 }
5554 break;
5555 }
5556 case BO_PtrMemD:
5557 case BO_PtrMemI:
5558 case BO_MulAssign:
5559 case BO_Div:
5560 case BO_Rem:
5561 case BO_Sub:
5562 case BO_Shl:
5563 case BO_Shr:
5564 case BO_LE:
5565 case BO_GE:
5566 case BO_EQ:
5567 case BO_NE:
5568 case BO_AndAssign:
5569 case BO_XorAssign:
5570 case BO_OrAssign:
5571 case BO_Assign:
5572 case BO_AddAssign:
5573 case BO_SubAssign:
5574 case BO_DivAssign:
5575 case BO_RemAssign:
5576 case BO_ShlAssign:
5577 case BO_ShrAssign:
5578 case BO_Comma:
5579 llvm_unreachable("Unexpected reduction operation");
5580 }
5581 if (Init) {
5582 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5583 /*TypeMayContainAuto=*/false);
5584 } else {
5585 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5586 }
5587 if (!RHSVD->hasInit()) {
5588 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5589 << ReductionIdRange;
5590 bool IsDecl =
5591 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5592 Diag(VD->getLocation(),
5593 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5594 << VD;
5595 continue;
5596 }
5597 auto *LHSDRE = BuildDeclRefExpr(LHSVD, Type, VK_LValue, ELoc).get();
5598 auto *RHSDRE = BuildDeclRefExpr(RHSVD, Type, VK_LValue, ELoc).get();
5599 ExprResult ReductionOp =
5600 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5601 LHSDRE, RHSDRE);
5602 if (ReductionOp.isUsable()) {
5603 if (BOK != BO_LOr && BOK != BO_LAnd) {
5604 ReductionOp =
5605 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5606 BO_Assign, LHSDRE, ReductionOp.get());
5607 } else {
5608 auto *ConditionalOp = new (Context) ConditionalOperator(
5609 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5610 RHSDRE, Type, VK_LValue, OK_Ordinary);
5611 ReductionOp =
5612 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5613 BO_Assign, LHSDRE, ConditionalOp);
5614 }
5615 if (ReductionOp.isUsable()) {
5616 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005617 }
5618 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005619 if (ReductionOp.isInvalid())
5620 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005621
5622 DSAStack->addDSA(VD, DE, OMPC_reduction);
5623 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005624 LHSs.push_back(LHSDRE);
5625 RHSs.push_back(RHSDRE);
5626 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005627 }
5628
5629 if (Vars.empty())
5630 return nullptr;
5631
5632 return OMPReductionClause::Create(
5633 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005634 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5635 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005636}
5637
Alexander Musman8dba6642014-04-22 13:09:42 +00005638OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5639 SourceLocation StartLoc,
5640 SourceLocation LParenLoc,
5641 SourceLocation ColonLoc,
5642 SourceLocation EndLoc) {
5643 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005644 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005645 for (auto &RefExpr : VarList) {
5646 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5647 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005648 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005649 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005650 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005651 continue;
5652 }
5653
5654 // OpenMP [2.14.3.7, linear clause]
5655 // A list item that appears in a linear clause is subject to the private
5656 // clause semantics described in Section 2.14.3.3 on page 159 except as
5657 // noted. In addition, the value of the new list item on each iteration
5658 // of the associated loop(s) corresponds to the value of the original
5659 // list item before entering the construct plus the logical number of
5660 // the iteration times linear-step.
5661
Alexey Bataeved09d242014-05-28 05:53:51 +00005662 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005663 // OpenMP [2.1, C/C++]
5664 // A list item is a variable name.
5665 // OpenMP [2.14.3.3, Restrictions, p.1]
5666 // A variable that is part of another variable (as an array or
5667 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005668 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005669 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005670 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005671 continue;
5672 }
5673
5674 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5675
5676 // OpenMP [2.14.3.7, linear clause]
5677 // A list-item cannot appear in more than one linear clause.
5678 // A list-item that appears in a linear clause cannot appear in any
5679 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005680 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005681 if (DVar.RefExpr) {
5682 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5683 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005684 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005685 continue;
5686 }
5687
5688 QualType QType = VD->getType();
5689 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5690 // It will be analyzed later.
5691 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005692 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005693 continue;
5694 }
5695
5696 // A variable must not have an incomplete type or a reference type.
5697 if (RequireCompleteType(ELoc, QType,
5698 diag::err_omp_linear_incomplete_type)) {
5699 continue;
5700 }
5701 if (QType->isReferenceType()) {
5702 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5703 << getOpenMPClauseName(OMPC_linear) << QType;
5704 bool IsDecl =
5705 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5706 Diag(VD->getLocation(),
5707 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5708 << VD;
5709 continue;
5710 }
5711
5712 // A list item must not be const-qualified.
5713 if (QType.isConstant(Context)) {
5714 Diag(ELoc, diag::err_omp_const_variable)
5715 << getOpenMPClauseName(OMPC_linear);
5716 bool IsDecl =
5717 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5718 Diag(VD->getLocation(),
5719 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5720 << VD;
5721 continue;
5722 }
5723
5724 // A list item must be of integral or pointer type.
5725 QType = QType.getUnqualifiedType().getCanonicalType();
5726 const Type *Ty = QType.getTypePtrOrNull();
5727 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5728 !Ty->isPointerType())) {
5729 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5730 bool IsDecl =
5731 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5732 Diag(VD->getLocation(),
5733 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5734 << VD;
5735 continue;
5736 }
5737
Alexander Musman3276a272015-03-21 10:12:56 +00005738 // Build var to save initial value.
5739 VarDecl *Init = BuildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
5740 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5741 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5742 CurContext->addDecl(Init);
5743 Init->setIsUsed();
5744 auto InitRef = DeclRefExpr::Create(
5745 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5746 /*TemplateKWLoc*/ SourceLocation(), Init,
5747 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
5748 /*VK*/ VK_LValue);
Alexander Musman8dba6642014-04-22 13:09:42 +00005749 DSAStack->addDSA(VD, DE, OMPC_linear);
5750 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005751 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005752 }
5753
5754 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005755 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005756
5757 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005758 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005759 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5760 !Step->isInstantiationDependent() &&
5761 !Step->containsUnexpandedParameterPack()) {
5762 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005763 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005764 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005765 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005766 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005767
Alexander Musman3276a272015-03-21 10:12:56 +00005768 // Build var to save the step value.
5769 VarDecl *SaveVar =
5770 BuildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5771 CurContext->addDecl(SaveVar);
5772 SaveVar->setIsUsed();
5773 ExprResult SaveRef =
5774 BuildDeclRefExpr(SaveVar, StepExpr->getType(), VK_LValue, StepLoc);
5775 ExprResult CalcStep =
5776 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5777
Alexander Musman8dba6642014-04-22 13:09:42 +00005778 // Warn about zero linear step (it would be probably better specified as
5779 // making corresponding variables 'const').
5780 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005781 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5782 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005783 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5784 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005785 if (!IsConstant && CalcStep.isUsable()) {
5786 // Calculate the step beforehand instead of doing this on each iteration.
5787 // (This is not used if the number of iterations may be kfold-ed).
5788 CalcStepExpr = CalcStep.get();
5789 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005790 }
5791
5792 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005793 Vars, Inits, StepExpr, CalcStepExpr);
5794}
5795
5796static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5797 Expr *NumIterations, Sema &SemaRef,
5798 Scope *S) {
5799 // Walk the vars and build update/final expressions for the CodeGen.
5800 SmallVector<Expr *, 8> Updates;
5801 SmallVector<Expr *, 8> Finals;
5802 Expr *Step = Clause.getStep();
5803 Expr *CalcStep = Clause.getCalcStep();
5804 // OpenMP [2.14.3.7, linear clause]
5805 // If linear-step is not specified it is assumed to be 1.
5806 if (Step == nullptr)
5807 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5808 else if (CalcStep)
5809 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5810 bool HasErrors = false;
5811 auto CurInit = Clause.inits().begin();
5812 for (auto &RefExpr : Clause.varlists()) {
5813 Expr *InitExpr = *CurInit;
5814
5815 // Build privatized reference to the current linear var.
5816 auto DE = cast<DeclRefExpr>(RefExpr);
5817 auto PrivateRef = DeclRefExpr::Create(
5818 SemaRef.Context, /*QualifierLoc*/ DE->getQualifierLoc(),
5819 /*TemplateKWLoc*/ SourceLocation(), DE->getDecl(),
5820 /* RefersToEnclosingVariableOrCapture */ true, DE->getLocStart(),
5821 DE->getType(), /*VK*/ VK_LValue);
5822
5823 // Build update: Var = InitExpr + IV * Step
5824 ExprResult Update =
5825 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5826 InitExpr, IV, Step, /* Subtract */ false);
5827 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5828
5829 // Build final: Var = InitExpr + NumIterations * Step
5830 ExprResult Final =
5831 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), RefExpr, InitExpr,
5832 NumIterations, Step, /* Subtract */ false);
5833 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5834 if (!Update.isUsable() || !Final.isUsable()) {
5835 Updates.push_back(nullptr);
5836 Finals.push_back(nullptr);
5837 HasErrors = true;
5838 } else {
5839 Updates.push_back(Update.get());
5840 Finals.push_back(Final.get());
5841 }
5842 ++CurInit;
5843 }
5844 Clause.setUpdates(Updates);
5845 Clause.setFinals(Finals);
5846 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005847}
5848
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005849OMPClause *Sema::ActOnOpenMPAlignedClause(
5850 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5851 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5852
5853 SmallVector<Expr *, 8> Vars;
5854 for (auto &RefExpr : VarList) {
5855 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5856 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5857 // It will be analyzed later.
5858 Vars.push_back(RefExpr);
5859 continue;
5860 }
5861
5862 SourceLocation ELoc = RefExpr->getExprLoc();
5863 // OpenMP [2.1, C/C++]
5864 // A list item is a variable name.
5865 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5866 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5867 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5868 continue;
5869 }
5870
5871 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5872
5873 // OpenMP [2.8.1, simd construct, Restrictions]
5874 // The type of list items appearing in the aligned clause must be
5875 // array, pointer, reference to array, or reference to pointer.
5876 QualType QType = DE->getType()
5877 .getNonReferenceType()
5878 .getUnqualifiedType()
5879 .getCanonicalType();
5880 const Type *Ty = QType.getTypePtrOrNull();
5881 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5882 !Ty->isPointerType())) {
5883 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5884 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5885 bool IsDecl =
5886 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5887 Diag(VD->getLocation(),
5888 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5889 << VD;
5890 continue;
5891 }
5892
5893 // OpenMP [2.8.1, simd construct, Restrictions]
5894 // A list-item cannot appear in more than one aligned clause.
5895 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5896 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5897 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5898 << getOpenMPClauseName(OMPC_aligned);
5899 continue;
5900 }
5901
5902 Vars.push_back(DE);
5903 }
5904
5905 // OpenMP [2.8.1, simd construct, Description]
5906 // The parameter of the aligned clause, alignment, must be a constant
5907 // positive integer expression.
5908 // If no optional parameter is specified, implementation-defined default
5909 // alignments for SIMD instructions on the target platforms are assumed.
5910 if (Alignment != nullptr) {
5911 ExprResult AlignResult =
5912 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5913 if (AlignResult.isInvalid())
5914 return nullptr;
5915 Alignment = AlignResult.get();
5916 }
5917 if (Vars.empty())
5918 return nullptr;
5919
5920 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5921 EndLoc, Vars, Alignment);
5922}
5923
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005924OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
5925 SourceLocation StartLoc,
5926 SourceLocation LParenLoc,
5927 SourceLocation EndLoc) {
5928 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00005929 SmallVector<Expr *, 8> SrcExprs;
5930 SmallVector<Expr *, 8> DstExprs;
5931 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00005932 for (auto &RefExpr : VarList) {
5933 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
5934 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005935 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005936 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00005937 SrcExprs.push_back(nullptr);
5938 DstExprs.push_back(nullptr);
5939 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005940 continue;
5941 }
5942
Alexey Bataeved09d242014-05-28 05:53:51 +00005943 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005944 // OpenMP [2.1, C/C++]
5945 // A list item is a variable name.
5946 // OpenMP [2.14.4.1, Restrictions, p.1]
5947 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00005948 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005949 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005950 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005951 continue;
5952 }
5953
5954 Decl *D = DE->getDecl();
5955 VarDecl *VD = cast<VarDecl>(D);
5956
5957 QualType Type = VD->getType();
5958 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5959 // It will be analyzed later.
5960 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00005961 SrcExprs.push_back(nullptr);
5962 DstExprs.push_back(nullptr);
5963 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005964 continue;
5965 }
5966
5967 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
5968 // A list item that appears in a copyin clause must be threadprivate.
5969 if (!DSAStack->isThreadPrivate(VD)) {
5970 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00005971 << getOpenMPClauseName(OMPC_copyin)
5972 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005973 continue;
5974 }
5975
5976 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
5977 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00005978 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005979 // operator for the class type.
Alexey Bataevf56f98c2015-04-16 05:39:01 +00005980 Type = Context.getBaseElementType(Type).getNonReferenceType();
5981 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(),
5982 Type.getUnqualifiedType(), ".copyin.src");
5983 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, Type.getUnqualifiedType(),
5984 VK_LValue, DE->getExprLoc())
5985 .get();
5986 auto *DstVD = BuildVarDecl(*this, DE->getLocStart(), Type, ".copyin.dst");
5987 auto *PseudoDstExpr =
5988 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
5989 // For arrays generate assignment operation for single element and replace
5990 // it by the original array element in CodeGen.
5991 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5992 PseudoDstExpr, PseudoSrcExpr);
5993 if (AssignmentOp.isInvalid())
5994 continue;
5995 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5996 /*DiscardedValue=*/true);
5997 if (AssignmentOp.isInvalid())
5998 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005999
6000 DSAStack->addDSA(VD, DE, OMPC_copyin);
6001 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006002 SrcExprs.push_back(PseudoSrcExpr);
6003 DstExprs.push_back(PseudoDstExpr);
6004 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006005 }
6006
Alexey Bataeved09d242014-05-28 05:53:51 +00006007 if (Vars.empty())
6008 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006009
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006010 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6011 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006012}
6013
Alexey Bataevbae9a792014-06-27 10:37:06 +00006014OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6015 SourceLocation StartLoc,
6016 SourceLocation LParenLoc,
6017 SourceLocation EndLoc) {
6018 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006019 SmallVector<Expr *, 8> SrcExprs;
6020 SmallVector<Expr *, 8> DstExprs;
6021 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006022 for (auto &RefExpr : VarList) {
6023 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6024 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6025 // It will be analyzed later.
6026 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006027 SrcExprs.push_back(nullptr);
6028 DstExprs.push_back(nullptr);
6029 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006030 continue;
6031 }
6032
6033 SourceLocation ELoc = RefExpr->getExprLoc();
6034 // OpenMP [2.1, C/C++]
6035 // A list item is a variable name.
6036 // OpenMP [2.14.4.1, Restrictions, p.1]
6037 // A list item that appears in a copyin clause must be threadprivate.
6038 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6039 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6040 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6041 continue;
6042 }
6043
6044 Decl *D = DE->getDecl();
6045 VarDecl *VD = cast<VarDecl>(D);
6046
6047 QualType Type = VD->getType();
6048 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6049 // It will be analyzed later.
6050 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006051 SrcExprs.push_back(nullptr);
6052 DstExprs.push_back(nullptr);
6053 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006054 continue;
6055 }
6056
6057 // OpenMP [2.14.4.2, Restrictions, p.2]
6058 // A list item that appears in a copyprivate clause may not appear in a
6059 // private or firstprivate clause on the single construct.
6060 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006061 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006062 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6063 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006064 Diag(ELoc, diag::err_omp_wrong_dsa)
6065 << getOpenMPClauseName(DVar.CKind)
6066 << getOpenMPClauseName(OMPC_copyprivate);
6067 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6068 continue;
6069 }
6070
6071 // OpenMP [2.11.4.2, Restrictions, p.1]
6072 // All list items that appear in a copyprivate clause must be either
6073 // threadprivate or private in the enclosing context.
6074 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006075 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006076 if (DVar.CKind == OMPC_shared) {
6077 Diag(ELoc, diag::err_omp_required_access)
6078 << getOpenMPClauseName(OMPC_copyprivate)
6079 << "threadprivate or private in the enclosing context";
6080 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6081 continue;
6082 }
6083 }
6084 }
6085
6086 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6087 // A variable of class type (or array thereof) that appears in a
6088 // copyin clause requires an accessible, unambiguous copy assignment
6089 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006090 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6091 auto *SrcVD =
6092 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6093 auto *PseudoSrcExpr =
6094 BuildDeclRefExpr(SrcVD, Type, VK_LValue, DE->getExprLoc()).get();
6095 auto *DstVD =
6096 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6097 auto *PseudoDstExpr =
6098 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
Alexey Bataeva63048e2015-03-23 06:18:07 +00006099 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6100 PseudoDstExpr, PseudoSrcExpr);
6101 if (AssignmentOp.isInvalid())
6102 continue;
6103 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6104 /*DiscardedValue=*/true);
6105 if (AssignmentOp.isInvalid())
6106 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006107
6108 // No need to mark vars as copyprivate, they are already threadprivate or
6109 // implicitly private.
6110 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006111 SrcExprs.push_back(PseudoSrcExpr);
6112 DstExprs.push_back(PseudoDstExpr);
6113 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006114 }
6115
6116 if (Vars.empty())
6117 return nullptr;
6118
Alexey Bataeva63048e2015-03-23 06:18:07 +00006119 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6120 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006121}
6122
Alexey Bataev6125da92014-07-21 11:26:11 +00006123OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6124 SourceLocation StartLoc,
6125 SourceLocation LParenLoc,
6126 SourceLocation EndLoc) {
6127 if (VarList.empty())
6128 return nullptr;
6129
6130 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6131}
Alexey Bataevdea47612014-07-23 07:46:59 +00006132