blob: c7d0c148ba0e48384df500e6d333201926bf76fa [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 Bataev9c821032015-04-30 04:23:23 +000085 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086
87 struct SharingMapTy {
88 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000089 AlignedMapTy AlignedMap;
Alexey Bataev9c821032015-04-30 04:23:23 +000090 LoopControlVariablesSetTy LCVSet;
Alexey Bataev758e55e2013-09-06 18:03:48 +000091 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000092 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +000093 OpenMPDirectiveKind Directive;
94 DeclarationNameInfo DirectiveName;
95 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +000096 SourceLocation ConstructLoc;
Alexey Bataev9fb6e642014-07-22 06:45:04 +000097 bool OrderedRegion;
Alexey Bataev9c821032015-04-30 04:23:23 +000098 unsigned CollapseNumber;
Alexey Bataev13314bf2014-10-09 04:18:56 +000099 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000100 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000101 Scope *CurScope, SourceLocation Loc)
Alexey Bataev9c821032015-04-30 04:23:23 +0000102 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000103 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev9c821032015-04-30 04:23:23 +0000104 ConstructLoc(Loc), OrderedRegion(false), CollapseNumber(1),
105 InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000106 SharingMapTy()
Alexey Bataev9c821032015-04-30 04:23:23 +0000107 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000108 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev9c821032015-04-30 04:23:23 +0000109 ConstructLoc(), OrderedRegion(false), CollapseNumber(1),
110 InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000111 };
112
113 typedef SmallVector<SharingMapTy, 64> StackTy;
114
115 /// \brief Stack of used declaration and their data-sharing attributes.
116 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000117 /// \brief true, if check for DSA must be from parent directive, false, if
118 /// from current directive.
119 bool FromParent;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000120 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000121
122 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
123
124 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000125
126 /// \brief Checks if the variable is a local for OpenMP region.
127 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000128
Alexey Bataev758e55e2013-09-06 18:03:48 +0000129public:
Alexey Bataev39f915b82015-05-08 10:41:21 +0000130 explicit DSAStackTy(Sema &S) : Stack(1), FromParent(false), SemaRef(S) {}
131
132 bool isFromParent() const { return FromParent; }
133 void setFromParent(bool Flag) { FromParent = Flag; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000134
135 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000136 Scope *CurScope, SourceLocation Loc) {
137 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
138 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000139 }
140
141 void pop() {
142 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
143 Stack.pop_back();
144 }
145
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000146 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000147 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000148 /// for diagnostics.
149 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
150
Alexey Bataev9c821032015-04-30 04:23:23 +0000151 /// \brief Register specified variable as loop control variable.
152 void addLoopControlVariable(VarDecl *D);
153 /// \brief Check if the specified variable is a loop control variable for
154 /// current region.
155 bool isLoopControlVariable(VarDecl *D);
156
Alexey Bataev758e55e2013-09-06 18:03:48 +0000157 /// \brief Adds explicit data sharing attribute to the specified declaration.
158 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
159
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 /// \brief Returns data sharing attributes from top of the stack for the
161 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000162 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000164 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000165 /// \brief Checks if the specified variables has data-sharing attributes which
166 /// match specified \a CPred predicate in any directive which matches \a DPred
167 /// predicate.
168 template <class ClausesPredicate, class DirectivesPredicate>
169 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000170 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000171 /// \brief Checks if the specified variables has data-sharing attributes which
172 /// match specified \a CPred predicate in any innermost directive which
173 /// matches \a DPred predicate.
174 template <class ClausesPredicate, class DirectivesPredicate>
175 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000176 DirectivesPredicate DPred,
177 bool FromParent);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000178 /// \brief Finds a directive which matches specified \a DPred predicate.
179 template <class NamedDirectivesPredicate>
180 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000181
Alexey Bataev758e55e2013-09-06 18:03:48 +0000182 /// \brief Returns currently analyzed directive.
183 OpenMPDirectiveKind getCurrentDirective() const {
184 return Stack.back().Directive;
185 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000186 /// \brief Returns parent directive.
187 OpenMPDirectiveKind getParentDirective() const {
188 if (Stack.size() > 2)
189 return Stack[Stack.size() - 2].Directive;
190 return OMPD_unknown;
191 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000192
193 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000194 void setDefaultDSANone(SourceLocation Loc) {
195 Stack.back().DefaultAttr = DSA_none;
196 Stack.back().DefaultAttrLoc = Loc;
197 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000199 void setDefaultDSAShared(SourceLocation Loc) {
200 Stack.back().DefaultAttr = DSA_shared;
201 Stack.back().DefaultAttrLoc = Loc;
202 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000203
204 DefaultDataSharingAttributes getDefaultDSA() const {
205 return Stack.back().DefaultAttr;
206 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000207 SourceLocation getDefaultDSALocation() const {
208 return Stack.back().DefaultAttrLoc;
209 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000210
Alexey Bataevf29276e2014-06-18 04:14:57 +0000211 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000212 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000213 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000214 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000215 }
216
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000217 /// \brief Marks current region as ordered (it has an 'ordered' clause).
218 void setOrderedRegion(bool IsOrdered = true) {
219 Stack.back().OrderedRegion = IsOrdered;
220 }
221 /// \brief Returns true, if parent region is ordered (has associated
222 /// 'ordered' clause), false - otherwise.
223 bool isParentOrderedRegion() const {
224 if (Stack.size() > 2)
225 return Stack[Stack.size() - 2].OrderedRegion;
226 return false;
227 }
228
Alexey Bataev9c821032015-04-30 04:23:23 +0000229 /// \brief Set collapse value for the region.
230 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
231 /// \brief Return collapse value for region.
232 unsigned getCollapseNumber() const {
233 return Stack.back().CollapseNumber;
234 }
235
Alexey Bataev13314bf2014-10-09 04:18:56 +0000236 /// \brief Marks current target region as one with closely nested teams
237 /// region.
238 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
239 if (Stack.size() > 2)
240 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
241 }
242 /// \brief Returns true, if current region has closely nested teams region.
243 bool hasInnerTeamsRegion() const {
244 return getInnerTeamsRegionLoc().isValid();
245 }
246 /// \brief Returns location of the nested teams region (if any).
247 SourceLocation getInnerTeamsRegionLoc() const {
248 if (Stack.size() > 1)
249 return Stack.back().InnerTeamsRegionLoc;
250 return SourceLocation();
251 }
252
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000253 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000254 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000257bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
258 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000259 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000260}
Alexey Bataeved09d242014-05-28 05:53:51 +0000261} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000262
263DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
264 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000265 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000267 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000268 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
269 // in a region but not in construct]
270 // File-scope or namespace-scope variables referenced in called routines
271 // in the region are shared unless they appear in a threadprivate
272 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000273 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000274 DVar.CKind = OMPC_shared;
275
276 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
277 // in a region but not in construct]
278 // Variables with static storage duration that are declared in called
279 // routines in the region are shared.
280 if (D->hasGlobalStorage())
281 DVar.CKind = OMPC_shared;
282
Alexey Bataev758e55e2013-09-06 18:03:48 +0000283 return DVar;
284 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000285
Alexey Bataev758e55e2013-09-06 18:03:48 +0000286 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000287 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
288 // in a Construct, C/C++, predetermined, p.1]
289 // Variables with automatic storage duration that are declared in a scope
290 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000291 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
292 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
293 DVar.CKind = OMPC_private;
294 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000295 }
296
Alexey Bataev758e55e2013-09-06 18:03:48 +0000297 // Explicitly specified attributes and local variables with predetermined
298 // attributes.
299 if (Iter->SharingMap.count(D)) {
300 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
301 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000302 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000303 return DVar;
304 }
305
306 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
307 // in a Construct, C/C++, implicitly determined, p.1]
308 // In a parallel or task construct, the data-sharing attributes of these
309 // variables are determined by the default clause, if present.
310 switch (Iter->DefaultAttr) {
311 case DSA_shared:
312 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000313 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000314 return DVar;
315 case DSA_none:
316 return DVar;
317 case DSA_unspecified:
318 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
319 // in a Construct, implicitly determined, p.2]
320 // In a parallel construct, if no default clause is present, these
321 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000322 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000323 if (isOpenMPParallelDirective(DVar.DKind) ||
324 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000325 DVar.CKind = OMPC_shared;
326 return DVar;
327 }
328
329 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
330 // in a Construct, implicitly determined, p.4]
331 // In a task construct, if no default clause is present, a variable that in
332 // the enclosing context is determined to be shared by all implicit tasks
333 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000334 if (DVar.DKind == OMPD_task) {
335 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000336 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000337 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000338 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
339 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000340 // in a Construct, implicitly determined, p.6]
341 // In a task construct, if no default clause is present, a variable
342 // whose data-sharing attribute is not determined by the rules above is
343 // firstprivate.
344 DVarTemp = getDSA(I, D);
345 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000346 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000347 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000348 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000349 return DVar;
350 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000351 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000352 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000353 }
354 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000355 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000356 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000357 return DVar;
358 }
359 }
360 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
361 // in a Construct, implicitly determined, p.3]
362 // For constructs other than task, if no default clause is present, these
363 // variables inherit their data-sharing attributes from the enclosing
364 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000365 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000366}
367
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000368DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
369 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000370 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000371 auto It = Stack.back().AlignedMap.find(D);
372 if (It == Stack.back().AlignedMap.end()) {
373 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
374 Stack.back().AlignedMap[D] = NewDE;
375 return nullptr;
376 } else {
377 assert(It->second && "Unexpected nullptr expr in the aligned map");
378 return It->second;
379 }
380 return nullptr;
381}
382
Alexey Bataev9c821032015-04-30 04:23:23 +0000383void DSAStackTy::addLoopControlVariable(VarDecl *D) {
384 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
385 D = D->getCanonicalDecl();
386 Stack.back().LCVSet.insert(D);
387}
388
389bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
390 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
391 D = D->getCanonicalDecl();
392 return Stack.back().LCVSet.count(D) > 0;
393}
394
Alexey Bataev758e55e2013-09-06 18:03:48 +0000395void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000396 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000397 if (A == OMPC_threadprivate) {
398 Stack[0].SharingMap[D].Attributes = A;
399 Stack[0].SharingMap[D].RefExpr = E;
400 } else {
401 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
402 Stack.back().SharingMap[D].Attributes = A;
403 Stack.back().SharingMap[D].RefExpr = E;
404 }
405}
406
Alexey Bataeved09d242014-05-28 05:53:51 +0000407bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000408 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000409 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000410 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000411 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000412 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000413 ++I;
414 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000415 if (I == E)
416 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000417 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000418 Scope *CurScope = getCurScope();
419 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000420 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000421 }
422 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000423 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000424 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000425}
426
Alexey Bataev39f915b82015-05-08 10:41:21 +0000427/// \brief Build a variable declaration for OpenMP loop iteration variable.
428static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
429 StringRef Name) {
430 DeclContext *DC = SemaRef.CurContext;
431 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
432 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
433 VarDecl *Decl =
434 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
435 Decl->setImplicit();
436 return Decl;
437}
438
439static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
440 SourceLocation Loc,
441 bool RefersToCapture = false) {
442 D->setReferenced();
443 D->markUsed(S.Context);
444 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
445 SourceLocation(), D, RefersToCapture, Loc, Ty,
446 VK_LValue);
447}
448
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000449DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000450 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000451 DSAVarData DVar;
452
453 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
454 // in a Construct, C/C++, predetermined, p.1]
455 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000456 if (D->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000457 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
458 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000459 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
460 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000461 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000462 }
463 if (Stack[0].SharingMap.count(D)) {
464 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
465 DVar.CKind = OMPC_threadprivate;
466 return DVar;
467 }
468
469 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
470 // in a Construct, C/C++, predetermined, p.1]
471 // Variables with automatic storage duration that are declared in a scope
472 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000473 OpenMPDirectiveKind Kind =
474 FromParent ? getParentDirective() : getCurrentDirective();
475 auto StartI = std::next(Stack.rbegin());
476 auto EndI = std::prev(Stack.rend());
477 if (FromParent && StartI != EndI) {
478 StartI = std::next(StartI);
479 }
480 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000481 if (isOpenMPLocal(D, StartI) &&
482 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
483 D->getStorageClass() == SC_None)) ||
484 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000485 DVar.CKind = OMPC_private;
486 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000487 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000488
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000489 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
490 // in a Construct, C/C++, predetermined, p.4]
491 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000492 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
493 // in a Construct, C/C++, predetermined, p.7]
494 // Variables with static storage duration that are declared in a scope
495 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000496 if (D->isStaticDataMember() || D->isStaticLocal()) {
497 DSAVarData DVarTemp =
498 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
499 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
500 return DVar;
501
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000502 DVar.CKind = OMPC_shared;
503 return DVar;
504 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000505 }
506
507 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000508 if (auto *PVD = dyn_cast<ParmVarDecl>(D)) {
509 Type = PVD->getOriginalType().getNonReferenceType().getCanonicalType();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000510 }
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000511 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
512 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000513 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
514 // in a Construct, C/C++, predetermined, p.6]
515 // Variables with const qualified type having no mutable member are
516 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000517 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000518 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000520 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000521 // Variables with const-qualified type having no mutable member may be
522 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000523 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
524 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000525 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
526 return DVar;
527
Alexey Bataev758e55e2013-09-06 18:03:48 +0000528 DVar.CKind = OMPC_shared;
529 return DVar;
530 }
531
Alexey Bataev758e55e2013-09-06 18:03:48 +0000532 // Explicitly specified attributes and local variables with predetermined
533 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000534 auto I = std::prev(StartI);
535 if (I->SharingMap.count(D)) {
536 DVar.RefExpr = I->SharingMap[D].RefExpr;
537 DVar.CKind = I->SharingMap[D].Attributes;
538 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000539 }
540
541 return DVar;
542}
543
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000544DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000545 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000546 auto StartI = Stack.rbegin();
547 auto EndI = std::prev(Stack.rend());
548 if (FromParent && StartI != EndI) {
549 StartI = std::next(StartI);
550 }
551 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000552}
553
Alexey Bataevf29276e2014-06-18 04:14:57 +0000554template <class ClausesPredicate, class DirectivesPredicate>
555DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000556 DirectivesPredicate DPred,
557 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000558 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000559 auto StartI = std::next(Stack.rbegin());
560 auto EndI = std::prev(Stack.rend());
561 if (FromParent && StartI != EndI) {
562 StartI = std::next(StartI);
563 }
564 for (auto I = StartI, EE = EndI; I != EE; ++I) {
565 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000566 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000567 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000568 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000569 return DVar;
570 }
571 return DSAVarData();
572}
573
Alexey Bataevf29276e2014-06-18 04:14:57 +0000574template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000575DSAStackTy::DSAVarData
576DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
577 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000578 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000579 auto StartI = std::next(Stack.rbegin());
580 auto EndI = std::prev(Stack.rend());
581 if (FromParent && StartI != EndI) {
582 StartI = std::next(StartI);
583 }
584 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000585 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000586 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000587 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000588 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000589 return DVar;
590 return DSAVarData();
591 }
592 return DSAVarData();
593}
594
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000595template <class NamedDirectivesPredicate>
596bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
597 auto StartI = std::next(Stack.rbegin());
598 auto EndI = std::prev(Stack.rend());
599 if (FromParent && StartI != EndI) {
600 StartI = std::next(StartI);
601 }
602 for (auto I = StartI, EE = EndI; I != EE; ++I) {
603 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
604 return true;
605 }
606 return false;
607}
608
Alexey Bataev758e55e2013-09-06 18:03:48 +0000609void Sema::InitDataSharingAttributesStack() {
610 VarDataSharingAttributesStack = new DSAStackTy(*this);
611}
612
613#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
614
Alexey Bataevf841bd92014-12-16 07:00:22 +0000615bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
616 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000617 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000618 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000619 if (DSAStack->isLoopControlVariable(VD) ||
620 (VD->hasLocalStorage() &&
621 isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
Alexey Bataev9c821032015-04-30 04:23:23 +0000622 return true;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000624 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
625 return true;
626 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000627 DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000628 return DVarPrivate.CKind != OMPC_unknown;
629 }
630 return false;
631}
632
Alexey Bataeved09d242014-05-28 05:53:51 +0000633void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000634
635void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
636 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000637 Scope *CurScope, SourceLocation Loc) {
638 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000639 PushExpressionEvaluationContext(PotentiallyEvaluated);
640}
641
Alexey Bataev39f915b82015-05-08 10:41:21 +0000642void Sema::StartOpenMPClauses() {
643 DSAStack->setFromParent(/*Flag=*/true);
644}
645
646void Sema::EndOpenMPClauses() {
647 DSAStack->setFromParent(/*Flag=*/false);
648}
649
Alexey Bataev758e55e2013-09-06 18:03:48 +0000650void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000651 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
652 // A variable of class type (or array thereof) that appears in a lastprivate
653 // clause requires an accessible, unambiguous default constructor for the
654 // class type, unless the list item is also specified in a firstprivate
655 // clause.
656 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000657 for (auto *C : D->clauses()) {
658 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
659 SmallVector<Expr *, 8> PrivateCopies;
660 for (auto *DE : Clause->varlists()) {
661 if (DE->isValueDependent() || DE->isTypeDependent()) {
662 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000663 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000664 }
665 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000666 QualType Type = VD->getType();
667 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
668 Type = PVD->getOriginalType();
669 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000670 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000671 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000672 // Generate helper private variable and initialize it with the
673 // default value. The address of the original variable is replaced
674 // by the address of the new private variable in CodeGen. This new
675 // variable is not added to IdResolver, so the code in the OpenMP
676 // region uses original variable for proper diagnostics.
Alexey Bataev39f915b82015-05-08 10:41:21 +0000677 auto *VDPrivate =
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000678 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
679 VD->getName());
Alexey Bataev38e89532015-04-16 04:54:05 +0000680 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
681 if (VDPrivate->isInvalidDecl())
682 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000683 PrivateCopies.push_back(buildDeclRefExpr(
684 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000685 } else {
686 // The variable is also a firstprivate, so initialization sequence
687 // for private copy is generated already.
688 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000689 }
690 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000691 // Set initializers to private copies if no errors were found.
692 if (PrivateCopies.size() == Clause->varlist_size()) {
693 Clause->setPrivateCopies(PrivateCopies);
694 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000695 }
696 }
697 }
698
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 DSAStack->pop();
700 DiscardCleanupsInEvaluationContext();
701 PopExpressionEvaluationContext();
702}
703
Alexander Musman3276a272015-03-21 10:12:56 +0000704static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
705 Expr *NumIterations, Sema &SemaRef,
706 Scope *S);
707
Alexey Bataeva769e072013-03-22 06:34:35 +0000708namespace {
709
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000710class VarDeclFilterCCC : public CorrectionCandidateCallback {
711private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000712 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000713
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000714public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000715 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000716 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000717 NamedDecl *ND = Candidate.getCorrectionDecl();
718 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
719 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000720 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
721 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000722 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000723 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000724 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000725};
Alexey Bataeved09d242014-05-28 05:53:51 +0000726} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000727
728ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
729 CXXScopeSpec &ScopeSpec,
730 const DeclarationNameInfo &Id) {
731 LookupResult Lookup(*this, Id, LookupOrdinaryName);
732 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
733
734 if (Lookup.isAmbiguous())
735 return ExprError();
736
737 VarDecl *VD;
738 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000739 if (TypoCorrection Corrected = CorrectTypo(
740 Id, LookupOrdinaryName, CurScope, nullptr,
741 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000742 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000743 PDiag(Lookup.empty()
744 ? diag::err_undeclared_var_use_suggest
745 : diag::err_omp_expected_var_arg_suggest)
746 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000747 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000748 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000749 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
750 : diag::err_omp_expected_var_arg)
751 << Id.getName();
752 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000753 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000754 } else {
755 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000756 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000757 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
758 return ExprError();
759 }
760 }
761 Lookup.suppressDiagnostics();
762
763 // OpenMP [2.9.2, Syntax, C/C++]
764 // Variables must be file-scope, namespace-scope, or static block-scope.
765 if (!VD->hasGlobalStorage()) {
766 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000767 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
768 bool IsDecl =
769 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000770 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000771 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
772 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000773 return ExprError();
774 }
775
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000776 VarDecl *CanonicalVD = VD->getCanonicalDecl();
777 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000778 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
779 // A threadprivate directive for file-scope variables must appear outside
780 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000781 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
782 !getCurLexicalContext()->isTranslationUnit()) {
783 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000784 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
785 bool IsDecl =
786 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
787 Diag(VD->getLocation(),
788 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
789 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000790 return ExprError();
791 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000792 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
793 // A threadprivate directive for static class member variables must appear
794 // in the class definition, in the same scope in which the member
795 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000796 if (CanonicalVD->isStaticDataMember() &&
797 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
798 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000799 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
800 bool IsDecl =
801 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
802 Diag(VD->getLocation(),
803 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
804 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000805 return ExprError();
806 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000807 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
808 // A threadprivate directive for namespace-scope variables must appear
809 // outside any definition or declaration other than the namespace
810 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000811 if (CanonicalVD->getDeclContext()->isNamespace() &&
812 (!getCurLexicalContext()->isFileContext() ||
813 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
814 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000815 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
816 bool IsDecl =
817 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
818 Diag(VD->getLocation(),
819 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
820 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000821 return ExprError();
822 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000823 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
824 // A threadprivate directive for static block-scope variables must appear
825 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000826 if (CanonicalVD->isStaticLocal() && CurScope &&
827 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000828 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000829 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
830 bool IsDecl =
831 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
832 Diag(VD->getLocation(),
833 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
834 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000835 return ExprError();
836 }
837
838 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
839 // A threadprivate directive must lexically precede all references to any
840 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000841 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000842 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000843 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000844 return ExprError();
845 }
846
847 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +0000848 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000849 return DE;
850}
851
Alexey Bataeved09d242014-05-28 05:53:51 +0000852Sema::DeclGroupPtrTy
853Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
854 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000855 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000856 CurContext->addDecl(D);
857 return DeclGroupPtrTy::make(DeclGroupRef(D));
858 }
859 return DeclGroupPtrTy();
860}
861
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000862namespace {
863class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
864 Sema &SemaRef;
865
866public:
867 bool VisitDeclRefExpr(const DeclRefExpr *E) {
868 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
869 if (VD->hasLocalStorage()) {
870 SemaRef.Diag(E->getLocStart(),
871 diag::err_omp_local_var_in_threadprivate_init)
872 << E->getSourceRange();
873 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
874 << VD << VD->getSourceRange();
875 return true;
876 }
877 }
878 return false;
879 }
880 bool VisitStmt(const Stmt *S) {
881 for (auto Child : S->children()) {
882 if (Child && Visit(Child))
883 return true;
884 }
885 return false;
886 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000887 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000888};
889} // namespace
890
Alexey Bataeved09d242014-05-28 05:53:51 +0000891OMPThreadPrivateDecl *
892Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000893 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000894 for (auto &RefExpr : VarList) {
895 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000896 VarDecl *VD = cast<VarDecl>(DE->getDecl());
897 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000898
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000899 QualType QType = VD->getType();
900 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
901 // It will be analyzed later.
902 Vars.push_back(DE);
903 continue;
904 }
905
Alexey Bataeva769e072013-03-22 06:34:35 +0000906 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
907 // A threadprivate variable must not have an incomplete type.
908 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000909 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000910 continue;
911 }
912
913 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
914 // A threadprivate variable must not have a reference type.
915 if (VD->getType()->isReferenceType()) {
916 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000917 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
918 bool IsDecl =
919 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
920 Diag(VD->getLocation(),
921 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
922 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000923 continue;
924 }
925
Richard Smithfd3834f2013-04-13 02:43:54 +0000926 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000927 if (VD->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000928 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
929 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +0000930 Diag(ILoc, diag::err_omp_var_thread_local)
931 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000932 bool IsDecl =
933 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
934 Diag(VD->getLocation(),
935 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
936 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000937 continue;
938 }
939
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000940 // Check if initial value of threadprivate variable reference variable with
941 // local storage (it is not supported by runtime).
942 if (auto Init = VD->getAnyInitializer()) {
943 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000944 if (Checker.Visit(Init))
945 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000946 }
947
Alexey Bataeved09d242014-05-28 05:53:51 +0000948 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000949 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000950 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
951 Context, SourceRange(Loc, Loc)));
952 if (auto *ML = Context.getASTMutationListener())
953 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000954 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000955 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000956 if (!Vars.empty()) {
957 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
958 Vars);
959 D->setAccess(AS_public);
960 }
961 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000962}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000963
Alexey Bataev7ff55242014-06-19 09:13:45 +0000964static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
965 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
966 bool IsLoopIterVar = false) {
967 if (DVar.RefExpr) {
968 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
969 << getOpenMPClauseName(DVar.CKind);
970 return;
971 }
972 enum {
973 PDSA_StaticMemberShared,
974 PDSA_StaticLocalVarShared,
975 PDSA_LoopIterVarPrivate,
976 PDSA_LoopIterVarLinear,
977 PDSA_LoopIterVarLastprivate,
978 PDSA_ConstVarShared,
979 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000980 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000981 PDSA_LocalVarPrivate,
982 PDSA_Implicit
983 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000984 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000985 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000986 if (IsLoopIterVar) {
987 if (DVar.CKind == OMPC_private)
988 Reason = PDSA_LoopIterVarPrivate;
989 else if (DVar.CKind == OMPC_lastprivate)
990 Reason = PDSA_LoopIterVarLastprivate;
991 else
992 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000993 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
994 Reason = PDSA_TaskVarFirstprivate;
995 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000996 } else if (VD->isStaticLocal())
997 Reason = PDSA_StaticLocalVarShared;
998 else if (VD->isStaticDataMember())
999 Reason = PDSA_StaticMemberShared;
1000 else if (VD->isFileVarDecl())
1001 Reason = PDSA_GlobalVarShared;
1002 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1003 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001004 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001005 ReportHint = true;
1006 Reason = PDSA_LocalVarPrivate;
1007 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001008 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001009 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001010 << Reason << ReportHint
1011 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1012 } else if (DVar.ImplicitDSALoc.isValid()) {
1013 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1014 << getOpenMPClauseName(DVar.CKind);
1015 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001016}
1017
Alexey Bataev758e55e2013-09-06 18:03:48 +00001018namespace {
1019class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1020 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001021 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001022 bool ErrorFound;
1023 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001024 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001025 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001026
Alexey Bataev758e55e2013-09-06 18:03:48 +00001027public:
1028 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001029 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001030 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001031 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1032 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001033
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001034 auto DVar = Stack->getTopDSA(VD, false);
1035 // Check if the variable has explicit DSA set and stop analysis if it so.
1036 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001037
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001038 auto ELoc = E->getExprLoc();
1039 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001040 // The default(none) clause requires that each variable that is referenced
1041 // in the construct, and does not have a predetermined data-sharing
1042 // attribute, must have its data-sharing attribute explicitly determined
1043 // by being listed in a data-sharing attribute clause.
1044 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001045 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001046 VarsWithInheritedDSA.count(VD) == 0) {
1047 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048 return;
1049 }
1050
1051 // OpenMP [2.9.3.6, Restrictions, p.2]
1052 // A list item that appears in a reduction clause of the innermost
1053 // enclosing worksharing or parallel construct may not be accessed in an
1054 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001055 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001056 [](OpenMPDirectiveKind K) -> bool {
1057 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001058 isOpenMPWorksharingDirective(K) ||
1059 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001060 },
1061 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001062 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1063 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001064 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1065 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001066 return;
1067 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001068
1069 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001070 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001071 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001072 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001073 }
1074 }
1075 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001076 for (auto *C : S->clauses()) {
1077 // Skip analysis of arguments of implicitly defined firstprivate clause
1078 // for task directives.
1079 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1080 for (auto *CC : C->children()) {
1081 if (CC)
1082 Visit(CC);
1083 }
1084 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001085 }
1086 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001087 for (auto *C : S->children()) {
1088 if (C && !isa<OMPExecutableDirective>(C))
1089 Visit(C);
1090 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001091 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001092
1093 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001094 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001095 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1096 return VarsWithInheritedDSA;
1097 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001098
Alexey Bataev7ff55242014-06-19 09:13:45 +00001099 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1100 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001101};
Alexey Bataeved09d242014-05-28 05:53:51 +00001102} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001103
Alexey Bataevbae9a792014-06-27 10:37:06 +00001104void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001105 switch (DKind) {
1106 case OMPD_parallel: {
1107 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1108 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001109 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001110 std::make_pair(".global_tid.", KmpInt32PtrTy),
1111 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1112 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001113 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001114 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1115 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001116 break;
1117 }
1118 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001119 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001120 std::make_pair(StringRef(), QualType()) // __context with shared vars
1121 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001122 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1123 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001124 break;
1125 }
1126 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001127 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001128 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001129 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001130 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1131 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001132 break;
1133 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001134 case OMPD_for_simd: {
1135 Sema::CapturedParamNameType Params[] = {
1136 std::make_pair(StringRef(), QualType()) // __context with shared vars
1137 };
1138 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1139 Params);
1140 break;
1141 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001142 case OMPD_sections: {
1143 Sema::CapturedParamNameType Params[] = {
1144 std::make_pair(StringRef(), QualType()) // __context with shared vars
1145 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001146 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1147 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001148 break;
1149 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001150 case OMPD_section: {
1151 Sema::CapturedParamNameType Params[] = {
1152 std::make_pair(StringRef(), QualType()) // __context with shared vars
1153 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001154 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1155 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001156 break;
1157 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001158 case OMPD_single: {
1159 Sema::CapturedParamNameType Params[] = {
1160 std::make_pair(StringRef(), QualType()) // __context with shared vars
1161 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001162 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1163 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001164 break;
1165 }
Alexander Musman80c22892014-07-17 08:54:58 +00001166 case OMPD_master: {
1167 Sema::CapturedParamNameType Params[] = {
1168 std::make_pair(StringRef(), QualType()) // __context with shared vars
1169 };
1170 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1171 Params);
1172 break;
1173 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001174 case OMPD_critical: {
1175 Sema::CapturedParamNameType Params[] = {
1176 std::make_pair(StringRef(), QualType()) // __context with shared vars
1177 };
1178 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1179 Params);
1180 break;
1181 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001182 case OMPD_parallel_for: {
1183 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1184 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1185 Sema::CapturedParamNameType Params[] = {
1186 std::make_pair(".global_tid.", KmpInt32PtrTy),
1187 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1188 std::make_pair(StringRef(), QualType()) // __context with shared vars
1189 };
1190 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1191 Params);
1192 break;
1193 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001194 case OMPD_parallel_for_simd: {
1195 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1196 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1197 Sema::CapturedParamNameType Params[] = {
1198 std::make_pair(".global_tid.", KmpInt32PtrTy),
1199 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1200 std::make_pair(StringRef(), QualType()) // __context with shared vars
1201 };
1202 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1203 Params);
1204 break;
1205 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001206 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001207 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1208 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001209 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001210 std::make_pair(".global_tid.", KmpInt32PtrTy),
1211 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001212 std::make_pair(StringRef(), QualType()) // __context with shared vars
1213 };
1214 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1215 Params);
1216 break;
1217 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001218 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001219 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001220 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001221 std::make_pair(".global_tid.", KmpInt32Ty),
1222 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001223 std::make_pair(StringRef(), QualType()) // __context with shared vars
1224 };
1225 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1226 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001227 // Mark this captured region as inlined, because we don't use outlined
1228 // function directly.
1229 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1230 AlwaysInlineAttr::CreateImplicit(
1231 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001232 break;
1233 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001234 case OMPD_ordered: {
1235 Sema::CapturedParamNameType Params[] = {
1236 std::make_pair(StringRef(), QualType()) // __context with shared vars
1237 };
1238 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1239 Params);
1240 break;
1241 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001242 case OMPD_atomic: {
1243 Sema::CapturedParamNameType Params[] = {
1244 std::make_pair(StringRef(), QualType()) // __context with shared vars
1245 };
1246 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1247 Params);
1248 break;
1249 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001250 case OMPD_target: {
1251 Sema::CapturedParamNameType Params[] = {
1252 std::make_pair(StringRef(), QualType()) // __context with shared vars
1253 };
1254 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1255 Params);
1256 break;
1257 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001258 case OMPD_teams: {
1259 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1260 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1261 Sema::CapturedParamNameType Params[] = {
1262 std::make_pair(".global_tid.", KmpInt32PtrTy),
1263 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1264 std::make_pair(StringRef(), QualType()) // __context with shared vars
1265 };
1266 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1267 Params);
1268 break;
1269 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001270 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001271 case OMPD_taskyield:
1272 case OMPD_barrier:
1273 case OMPD_taskwait:
1274 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001275 llvm_unreachable("OpenMP Directive is not allowed");
1276 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001277 llvm_unreachable("Unknown OpenMP directive");
1278 }
1279}
1280
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001281StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1282 ArrayRef<OMPClause *> Clauses) {
1283 if (!S.isUsable()) {
1284 ActOnCapturedRegionError();
1285 return StmtError();
1286 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001287 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001288 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001289 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1290 Clause->getClauseKind() == OMPC_copyprivate) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001291 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001292 for (auto *VarRef : Clause->children()) {
1293 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001294 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001295 }
1296 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001297 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1298 Clause->getClauseKind() == OMPC_schedule) {
1299 // Mark all variables in private list clauses as used in inner region.
1300 // Required for proper codegen of combined directives.
1301 // TODO: add processing for other clauses.
1302 if (auto *E = cast_or_null<Expr>(
1303 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1304 MarkDeclarationsReferencedInExpr(E);
1305 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001306 }
1307 }
1308 return ActOnCapturedRegionEnd(S.get());
1309}
1310
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001311static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1312 OpenMPDirectiveKind CurrentRegion,
1313 const DeclarationNameInfo &CurrentName,
1314 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001315 // Allowed nesting of constructs
1316 // +------------------+-----------------+------------------------------------+
1317 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1318 // +------------------+-----------------+------------------------------------+
1319 // | parallel | parallel | * |
1320 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001321 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001322 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001323 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001324 // | parallel | simd | * |
1325 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001326 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001327 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001328 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001329 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001330 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001331 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001332 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001333 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001334 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001335 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001336 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001337 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001338 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001339 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001340 // +------------------+-----------------+------------------------------------+
1341 // | for | parallel | * |
1342 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001343 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001344 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001345 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001346 // | for | simd | * |
1347 // | for | sections | + |
1348 // | for | section | + |
1349 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001350 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001351 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001352 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001353 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001354 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001355 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001356 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001357 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001358 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001359 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001360 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001361 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001362 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001363 // | master | parallel | * |
1364 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001365 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001366 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001367 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001368 // | master | simd | * |
1369 // | master | sections | + |
1370 // | master | section | + |
1371 // | master | single | + |
1372 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001373 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001374 // | master |parallel sections| * |
1375 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001376 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001377 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001378 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001379 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001380 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001381 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001382 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001383 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001384 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001385 // | critical | parallel | * |
1386 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001387 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001388 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001389 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001390 // | critical | simd | * |
1391 // | critical | sections | + |
1392 // | critical | section | + |
1393 // | critical | single | + |
1394 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001395 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001396 // | critical |parallel sections| * |
1397 // | critical | task | * |
1398 // | critical | taskyield | * |
1399 // | critical | barrier | + |
1400 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001401 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001402 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001403 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001404 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001405 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001406 // | simd | parallel | |
1407 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001408 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001409 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001410 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001411 // | simd | simd | |
1412 // | simd | sections | |
1413 // | simd | section | |
1414 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001415 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001416 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001417 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001419 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001420 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001421 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001422 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001423 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001424 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001425 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001426 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001427 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001428 // | for simd | parallel | |
1429 // | for simd | for | |
1430 // | for simd | for simd | |
1431 // | for simd | master | |
1432 // | for simd | critical | |
1433 // | for simd | simd | |
1434 // | for simd | sections | |
1435 // | for simd | section | |
1436 // | for simd | single | |
1437 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001438 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001439 // | for simd |parallel sections| |
1440 // | for simd | task | |
1441 // | for simd | taskyield | |
1442 // | for simd | barrier | |
1443 // | for simd | taskwait | |
1444 // | for simd | flush | |
1445 // | for simd | ordered | |
1446 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001447 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001448 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001449 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001450 // | parallel for simd| parallel | |
1451 // | parallel for simd| for | |
1452 // | parallel for simd| for simd | |
1453 // | parallel for simd| master | |
1454 // | parallel for simd| critical | |
1455 // | parallel for simd| simd | |
1456 // | parallel for simd| sections | |
1457 // | parallel for simd| section | |
1458 // | parallel for simd| single | |
1459 // | parallel for simd| parallel for | |
1460 // | parallel for simd|parallel for simd| |
1461 // | parallel for simd|parallel sections| |
1462 // | parallel for simd| task | |
1463 // | parallel for simd| taskyield | |
1464 // | parallel for simd| barrier | |
1465 // | parallel for simd| taskwait | |
1466 // | parallel for simd| flush | |
1467 // | parallel for simd| ordered | |
1468 // | parallel for simd| atomic | |
1469 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001470 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001471 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001472 // | sections | parallel | * |
1473 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001474 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001475 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001476 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001477 // | sections | simd | * |
1478 // | sections | sections | + |
1479 // | sections | section | * |
1480 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001481 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001482 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001483 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001484 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001485 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001486 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001487 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001488 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001489 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001490 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001491 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001492 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001493 // +------------------+-----------------+------------------------------------+
1494 // | section | parallel | * |
1495 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001496 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001497 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001498 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001499 // | section | simd | * |
1500 // | section | sections | + |
1501 // | section | section | + |
1502 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001503 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001504 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001505 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001506 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001507 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001508 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001509 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001510 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001511 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001512 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001513 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001514 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001515 // +------------------+-----------------+------------------------------------+
1516 // | single | parallel | * |
1517 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001518 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001519 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001520 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001521 // | single | simd | * |
1522 // | single | sections | + |
1523 // | single | section | + |
1524 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001525 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001526 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001527 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001528 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001529 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001530 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001531 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001532 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001533 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001534 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001535 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001536 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001537 // +------------------+-----------------+------------------------------------+
1538 // | parallel for | parallel | * |
1539 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001540 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001541 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001542 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001543 // | parallel for | simd | * |
1544 // | parallel for | sections | + |
1545 // | parallel for | section | + |
1546 // | parallel for | single | + |
1547 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001548 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001549 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001550 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001551 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001552 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001553 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001554 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001555 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001556 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001557 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001558 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001559 // +------------------+-----------------+------------------------------------+
1560 // | parallel sections| parallel | * |
1561 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001562 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001563 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001564 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001565 // | parallel sections| simd | * |
1566 // | parallel sections| sections | + |
1567 // | parallel sections| section | * |
1568 // | parallel sections| single | + |
1569 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001570 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001571 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001572 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001573 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001574 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001575 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001576 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001577 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001578 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001579 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001580 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001581 // +------------------+-----------------+------------------------------------+
1582 // | task | parallel | * |
1583 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001584 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001585 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001586 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001587 // | task | simd | * |
1588 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001589 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001590 // | task | single | + |
1591 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001592 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001593 // | task |parallel sections| * |
1594 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001595 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001596 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001597 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001598 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001599 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001600 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001601 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001602 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001603 // +------------------+-----------------+------------------------------------+
1604 // | ordered | parallel | * |
1605 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001606 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001607 // | ordered | master | * |
1608 // | ordered | critical | * |
1609 // | ordered | simd | * |
1610 // | ordered | sections | + |
1611 // | ordered | section | + |
1612 // | ordered | single | + |
1613 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001614 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001615 // | ordered |parallel sections| * |
1616 // | ordered | task | * |
1617 // | ordered | taskyield | * |
1618 // | ordered | barrier | + |
1619 // | ordered | taskwait | * |
1620 // | ordered | flush | * |
1621 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001622 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001623 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001624 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001625 // +------------------+-----------------+------------------------------------+
1626 // | atomic | parallel | |
1627 // | atomic | for | |
1628 // | atomic | for simd | |
1629 // | atomic | master | |
1630 // | atomic | critical | |
1631 // | atomic | simd | |
1632 // | atomic | sections | |
1633 // | atomic | section | |
1634 // | atomic | single | |
1635 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001636 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001637 // | atomic |parallel sections| |
1638 // | atomic | task | |
1639 // | atomic | taskyield | |
1640 // | atomic | barrier | |
1641 // | atomic | taskwait | |
1642 // | atomic | flush | |
1643 // | atomic | ordered | |
1644 // | atomic | atomic | |
1645 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001646 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001647 // +------------------+-----------------+------------------------------------+
1648 // | target | parallel | * |
1649 // | target | for | * |
1650 // | target | for simd | * |
1651 // | target | master | * |
1652 // | target | critical | * |
1653 // | target | simd | * |
1654 // | target | sections | * |
1655 // | target | section | * |
1656 // | target | single | * |
1657 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001658 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001659 // | target |parallel sections| * |
1660 // | target | task | * |
1661 // | target | taskyield | * |
1662 // | target | barrier | * |
1663 // | target | taskwait | * |
1664 // | target | flush | * |
1665 // | target | ordered | * |
1666 // | target | atomic | * |
1667 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001668 // | target | teams | * |
1669 // +------------------+-----------------+------------------------------------+
1670 // | teams | parallel | * |
1671 // | teams | for | + |
1672 // | teams | for simd | + |
1673 // | teams | master | + |
1674 // | teams | critical | + |
1675 // | teams | simd | + |
1676 // | teams | sections | + |
1677 // | teams | section | + |
1678 // | teams | single | + |
1679 // | teams | parallel for | * |
1680 // | teams |parallel for simd| * |
1681 // | teams |parallel sections| * |
1682 // | teams | task | + |
1683 // | teams | taskyield | + |
1684 // | teams | barrier | + |
1685 // | teams | taskwait | + |
1686 // | teams | flush | + |
1687 // | teams | ordered | + |
1688 // | teams | atomic | + |
1689 // | teams | target | + |
1690 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001691 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001692 if (Stack->getCurScope()) {
1693 auto ParentRegion = Stack->getParentDirective();
1694 bool NestingProhibited = false;
1695 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001696 enum {
1697 NoRecommend,
1698 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001699 ShouldBeInOrderedRegion,
1700 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001701 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001702 if (isOpenMPSimdDirective(ParentRegion)) {
1703 // OpenMP [2.16, Nesting of Regions]
1704 // OpenMP constructs may not be nested inside a simd region.
1705 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1706 return true;
1707 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001708 if (ParentRegion == OMPD_atomic) {
1709 // OpenMP [2.16, Nesting of Regions]
1710 // OpenMP constructs may not be nested inside an atomic region.
1711 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1712 return true;
1713 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001714 if (CurrentRegion == OMPD_section) {
1715 // OpenMP [2.7.2, sections Construct, Restrictions]
1716 // Orphaned section directives are prohibited. That is, the section
1717 // directives must appear within the sections construct and must not be
1718 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001719 if (ParentRegion != OMPD_sections &&
1720 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001721 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1722 << (ParentRegion != OMPD_unknown)
1723 << getOpenMPDirectiveName(ParentRegion);
1724 return true;
1725 }
1726 return false;
1727 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001728 // Allow some constructs to be orphaned (they could be used in functions,
1729 // called from OpenMP regions with the required preconditions).
1730 if (ParentRegion == OMPD_unknown)
1731 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001732 if (CurrentRegion == OMPD_master) {
1733 // OpenMP [2.16, Nesting of Regions]
1734 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001735 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001736 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1737 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001738 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1739 // OpenMP [2.16, Nesting of Regions]
1740 // A critical region may not be nested (closely or otherwise) inside a
1741 // critical region with the same name. Note that this restriction is not
1742 // sufficient to prevent deadlock.
1743 SourceLocation PreviousCriticalLoc;
1744 bool DeadLock =
1745 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1746 OpenMPDirectiveKind K,
1747 const DeclarationNameInfo &DNI,
1748 SourceLocation Loc)
1749 ->bool {
1750 if (K == OMPD_critical &&
1751 DNI.getName() == CurrentName.getName()) {
1752 PreviousCriticalLoc = Loc;
1753 return true;
1754 } else
1755 return false;
1756 },
1757 false /* skip top directive */);
1758 if (DeadLock) {
1759 SemaRef.Diag(StartLoc,
1760 diag::err_omp_prohibited_region_critical_same_name)
1761 << CurrentName.getName();
1762 if (PreviousCriticalLoc.isValid())
1763 SemaRef.Diag(PreviousCriticalLoc,
1764 diag::note_omp_previous_critical_region);
1765 return true;
1766 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001767 } else if (CurrentRegion == OMPD_barrier) {
1768 // OpenMP [2.16, Nesting of Regions]
1769 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001770 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001771 NestingProhibited =
1772 isOpenMPWorksharingDirective(ParentRegion) ||
1773 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1774 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001775 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001776 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001777 // OpenMP [2.16, Nesting of Regions]
1778 // A worksharing region may not be closely nested inside a worksharing,
1779 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001780 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001781 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001782 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1783 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1784 Recommend = ShouldBeInParallelRegion;
1785 } else if (CurrentRegion == OMPD_ordered) {
1786 // OpenMP [2.16, Nesting of Regions]
1787 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001788 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001789 // An ordered region must be closely nested inside a loop region (or
1790 // parallel loop region) with an ordered clause.
1791 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001792 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001793 !Stack->isParentOrderedRegion();
1794 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001795 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1796 // OpenMP [2.16, Nesting of Regions]
1797 // If specified, a teams construct must be contained within a target
1798 // construct.
1799 NestingProhibited = ParentRegion != OMPD_target;
1800 Recommend = ShouldBeInTargetRegion;
1801 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1802 }
1803 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1804 // OpenMP [2.16, Nesting of Regions]
1805 // distribute, parallel, parallel sections, parallel workshare, and the
1806 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1807 // constructs that can be closely nested in the teams region.
1808 // TODO: add distribute directive.
1809 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1810 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001811 }
1812 if (NestingProhibited) {
1813 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001814 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1815 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001816 return true;
1817 }
1818 }
1819 return false;
1820}
1821
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001822StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001823 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001824 ArrayRef<OMPClause *> Clauses,
1825 Stmt *AStmt,
1826 SourceLocation StartLoc,
1827 SourceLocation EndLoc) {
1828 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001829 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001830 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001831
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001832 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001833 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001834 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001835 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001836 if (AStmt) {
1837 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1838
1839 // Check default data sharing attributes for referenced variables.
1840 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1841 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1842 if (DSAChecker.isErrorFound())
1843 return StmtError();
1844 // Generate list of implicitly defined firstprivate variables.
1845 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001846
1847 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1848 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1849 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1850 SourceLocation(), SourceLocation())) {
1851 ClausesWithImplicit.push_back(Implicit);
1852 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1853 DSAChecker.getImplicitFirstprivate().size();
1854 } else
1855 ErrorFound = true;
1856 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001857 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001858
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001859 switch (Kind) {
1860 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001861 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1862 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001863 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001864 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001865 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1866 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001867 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001868 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001869 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1870 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001871 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001872 case OMPD_for_simd:
1873 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1874 EndLoc, VarsWithInheritedDSA);
1875 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001876 case OMPD_sections:
1877 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1878 EndLoc);
1879 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001880 case OMPD_section:
1881 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001882 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001883 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1884 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001885 case OMPD_single:
1886 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1887 EndLoc);
1888 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001889 case OMPD_master:
1890 assert(ClausesWithImplicit.empty() &&
1891 "No clauses are allowed for 'omp master' directive");
1892 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1893 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001894 case OMPD_critical:
1895 assert(ClausesWithImplicit.empty() &&
1896 "No clauses are allowed for 'omp critical' directive");
1897 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1898 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001899 case OMPD_parallel_for:
1900 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1901 EndLoc, VarsWithInheritedDSA);
1902 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001903 case OMPD_parallel_for_simd:
1904 Res = ActOnOpenMPParallelForSimdDirective(
1905 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1906 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001907 case OMPD_parallel_sections:
1908 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1909 StartLoc, EndLoc);
1910 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001911 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001912 Res =
1913 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1914 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001915 case OMPD_taskyield:
1916 assert(ClausesWithImplicit.empty() &&
1917 "No clauses are allowed for 'omp taskyield' directive");
1918 assert(AStmt == nullptr &&
1919 "No associated statement allowed for 'omp taskyield' directive");
1920 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1921 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001922 case OMPD_barrier:
1923 assert(ClausesWithImplicit.empty() &&
1924 "No clauses are allowed for 'omp barrier' directive");
1925 assert(AStmt == nullptr &&
1926 "No associated statement allowed for 'omp barrier' directive");
1927 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1928 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001929 case OMPD_taskwait:
1930 assert(ClausesWithImplicit.empty() &&
1931 "No clauses are allowed for 'omp taskwait' directive");
1932 assert(AStmt == nullptr &&
1933 "No associated statement allowed for 'omp taskwait' directive");
1934 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1935 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001936 case OMPD_flush:
1937 assert(AStmt == nullptr &&
1938 "No associated statement allowed for 'omp flush' directive");
1939 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1940 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001941 case OMPD_ordered:
1942 assert(ClausesWithImplicit.empty() &&
1943 "No clauses are allowed for 'omp ordered' directive");
1944 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1945 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001946 case OMPD_atomic:
1947 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1948 EndLoc);
1949 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001950 case OMPD_teams:
1951 Res =
1952 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1953 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001954 case OMPD_target:
1955 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1956 EndLoc);
1957 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001958 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001959 llvm_unreachable("OpenMP Directive is not allowed");
1960 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001961 llvm_unreachable("Unknown OpenMP directive");
1962 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001963
Alexey Bataev4acb8592014-07-07 13:01:15 +00001964 for (auto P : VarsWithInheritedDSA) {
1965 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1966 << P.first << P.second->getSourceRange();
1967 }
1968 if (!VarsWithInheritedDSA.empty())
1969 return StmtError();
1970
Alexey Bataeved09d242014-05-28 05:53:51 +00001971 if (ErrorFound)
1972 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001973 return Res;
1974}
1975
1976StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1977 Stmt *AStmt,
1978 SourceLocation StartLoc,
1979 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001980 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1981 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1982 // 1.2.2 OpenMP Language Terminology
1983 // Structured block - An executable statement with a single entry at the
1984 // top and a single exit at the bottom.
1985 // The point of exit cannot be a branch out of the structured block.
1986 // longjmp() and throw() must not violate the entry/exit criteria.
1987 CS->getCapturedDecl()->setNothrow();
1988
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001989 getCurFunction()->setHasBranchProtectedScope();
1990
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001991 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1992 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001993}
1994
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001995namespace {
1996/// \brief Helper class for checking canonical form of the OpenMP loops and
1997/// extracting iteration space of each loop in the loop nest, that will be used
1998/// for IR generation.
1999class OpenMPIterationSpaceChecker {
2000 /// \brief Reference to Sema.
2001 Sema &SemaRef;
2002 /// \brief A location for diagnostics (when there is no some better location).
2003 SourceLocation DefaultLoc;
2004 /// \brief A location for diagnostics (when increment is not compatible).
2005 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002006 /// \brief A source location for referring to loop init later.
2007 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002008 /// \brief A source location for referring to condition later.
2009 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002010 /// \brief A source location for referring to increment later.
2011 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002012 /// \brief Loop variable.
2013 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002014 /// \brief Reference to loop variable.
2015 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002016 /// \brief Lower bound (initializer for the var).
2017 Expr *LB;
2018 /// \brief Upper bound.
2019 Expr *UB;
2020 /// \brief Loop step (increment).
2021 Expr *Step;
2022 /// \brief This flag is true when condition is one of:
2023 /// Var < UB
2024 /// Var <= UB
2025 /// UB > Var
2026 /// UB >= Var
2027 bool TestIsLessOp;
2028 /// \brief This flag is true when condition is strict ( < or > ).
2029 bool TestIsStrictOp;
2030 /// \brief This flag is true when step is subtracted on each iteration.
2031 bool SubtractStep;
2032
2033public:
2034 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2035 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002036 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2037 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002038 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2039 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002040 /// \brief Check init-expr for canonical loop form and save loop counter
2041 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002042 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002043 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2044 /// for less/greater and for strict/non-strict comparison.
2045 bool CheckCond(Expr *S);
2046 /// \brief Check incr-expr for canonical loop form and return true if it
2047 /// does not conform, otherwise save loop step (#Step).
2048 bool CheckInc(Expr *S);
2049 /// \brief Return the loop counter variable.
2050 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002051 /// \brief Return the reference expression to loop counter variable.
2052 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002053 /// \brief Source range of the loop init.
2054 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2055 /// \brief Source range of the loop condition.
2056 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2057 /// \brief Source range of the loop increment.
2058 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2059 /// \brief True if the step should be subtracted.
2060 bool ShouldSubtractStep() const { return SubtractStep; }
2061 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002062 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002063 /// \brief Build the precondition expression for the loops.
2064 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002065 /// \brief Build reference expression to the counter be used for codegen.
2066 Expr *BuildCounterVar() const;
2067 /// \brief Build initization of the counter be used for codegen.
2068 Expr *BuildCounterInit() const;
2069 /// \brief Build step of the counter be used for codegen.
2070 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002071 /// \brief Return true if any expression is dependent.
2072 bool Dependent() const;
2073
2074private:
2075 /// \brief Check the right-hand side of an assignment in the increment
2076 /// expression.
2077 bool CheckIncRHS(Expr *RHS);
2078 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002079 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002080 /// \brief Helper to set upper bound.
2081 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2082 const SourceLocation &SL);
2083 /// \brief Helper to set loop increment.
2084 bool SetStep(Expr *NewStep, bool Subtract);
2085};
2086
2087bool OpenMPIterationSpaceChecker::Dependent() const {
2088 if (!Var) {
2089 assert(!LB && !UB && !Step);
2090 return false;
2091 }
2092 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2093 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2094}
2095
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002096bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2097 DeclRefExpr *NewVarRefExpr,
2098 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002099 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002100 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2101 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002102 if (!NewVar || !NewLB)
2103 return true;
2104 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002105 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002106 LB = NewLB;
2107 return false;
2108}
2109
2110bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2111 const SourceRange &SR,
2112 const SourceLocation &SL) {
2113 // State consistency checking to ensure correct usage.
2114 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2115 !TestIsLessOp && !TestIsStrictOp);
2116 if (!NewUB)
2117 return true;
2118 UB = NewUB;
2119 TestIsLessOp = LessOp;
2120 TestIsStrictOp = StrictOp;
2121 ConditionSrcRange = SR;
2122 ConditionLoc = SL;
2123 return false;
2124}
2125
2126bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2127 // State consistency checking to ensure correct usage.
2128 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2129 if (!NewStep)
2130 return true;
2131 if (!NewStep->isValueDependent()) {
2132 // Check that the step is integer expression.
2133 SourceLocation StepLoc = NewStep->getLocStart();
2134 ExprResult Val =
2135 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2136 if (Val.isInvalid())
2137 return true;
2138 NewStep = Val.get();
2139
2140 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2141 // If test-expr is of form var relational-op b and relational-op is < or
2142 // <= then incr-expr must cause var to increase on each iteration of the
2143 // loop. If test-expr is of form var relational-op b and relational-op is
2144 // > or >= then incr-expr must cause var to decrease on each iteration of
2145 // the loop.
2146 // If test-expr is of form b relational-op var and relational-op is < or
2147 // <= then incr-expr must cause var to decrease on each iteration of the
2148 // loop. If test-expr is of form b relational-op var and relational-op is
2149 // > or >= then incr-expr must cause var to increase on each iteration of
2150 // the loop.
2151 llvm::APSInt Result;
2152 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2153 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2154 bool IsConstNeg =
2155 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002156 bool IsConstPos =
2157 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002158 bool IsConstZero = IsConstant && !Result.getBoolValue();
2159 if (UB && (IsConstZero ||
2160 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002161 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002162 SemaRef.Diag(NewStep->getExprLoc(),
2163 diag::err_omp_loop_incr_not_compatible)
2164 << Var << TestIsLessOp << NewStep->getSourceRange();
2165 SemaRef.Diag(ConditionLoc,
2166 diag::note_omp_loop_cond_requres_compatible_incr)
2167 << TestIsLessOp << ConditionSrcRange;
2168 return true;
2169 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002170 if (TestIsLessOp == Subtract) {
2171 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2172 NewStep).get();
2173 Subtract = !Subtract;
2174 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002175 }
2176
2177 Step = NewStep;
2178 SubtractStep = Subtract;
2179 return false;
2180}
2181
Alexey Bataev9c821032015-04-30 04:23:23 +00002182bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002183 // Check init-expr for canonical loop form and save loop counter
2184 // variable - #Var and its initialization value - #LB.
2185 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2186 // var = lb
2187 // integer-type var = lb
2188 // random-access-iterator-type var = lb
2189 // pointer-type var = lb
2190 //
2191 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002192 if (EmitDiags) {
2193 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2194 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002195 return true;
2196 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002197 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002198 if (Expr *E = dyn_cast<Expr>(S))
2199 S = E->IgnoreParens();
2200 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2201 if (BO->getOpcode() == BO_Assign)
2202 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002203 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002204 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002205 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2206 if (DS->isSingleDecl()) {
2207 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2208 if (Var->hasInit()) {
2209 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002210 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002211 SemaRef.Diag(S->getLocStart(),
2212 diag::ext_omp_loop_not_canonical_init)
2213 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002214 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002215 }
2216 }
2217 }
2218 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2219 if (CE->getOperator() == OO_Equal)
2220 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002221 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2222 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002223
Alexey Bataev9c821032015-04-30 04:23:23 +00002224 if (EmitDiags) {
2225 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2226 << S->getSourceRange();
2227 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002228 return true;
2229}
2230
Alexey Bataev23b69422014-06-18 07:08:49 +00002231/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002232/// variable (which may be the loop variable) if possible.
2233static const VarDecl *GetInitVarDecl(const Expr *E) {
2234 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002235 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002236 E = E->IgnoreParenImpCasts();
2237 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2238 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2239 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2240 CE->getArg(0) != nullptr)
2241 E = CE->getArg(0)->IgnoreParenImpCasts();
2242 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2243 if (!DRE)
2244 return nullptr;
2245 return dyn_cast<VarDecl>(DRE->getDecl());
2246}
2247
2248bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2249 // Check test-expr for canonical form, save upper-bound UB, flags for
2250 // less/greater and for strict/non-strict comparison.
2251 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2252 // var relational-op b
2253 // b relational-op var
2254 //
2255 if (!S) {
2256 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2257 return true;
2258 }
2259 S = S->IgnoreParenImpCasts();
2260 SourceLocation CondLoc = S->getLocStart();
2261 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2262 if (BO->isRelationalOp()) {
2263 if (GetInitVarDecl(BO->getLHS()) == Var)
2264 return SetUB(BO->getRHS(),
2265 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2266 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2267 BO->getSourceRange(), BO->getOperatorLoc());
2268 if (GetInitVarDecl(BO->getRHS()) == Var)
2269 return SetUB(BO->getLHS(),
2270 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2271 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2272 BO->getSourceRange(), BO->getOperatorLoc());
2273 }
2274 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2275 if (CE->getNumArgs() == 2) {
2276 auto Op = CE->getOperator();
2277 switch (Op) {
2278 case OO_Greater:
2279 case OO_GreaterEqual:
2280 case OO_Less:
2281 case OO_LessEqual:
2282 if (GetInitVarDecl(CE->getArg(0)) == Var)
2283 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2284 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2285 CE->getOperatorLoc());
2286 if (GetInitVarDecl(CE->getArg(1)) == Var)
2287 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2288 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2289 CE->getOperatorLoc());
2290 break;
2291 default:
2292 break;
2293 }
2294 }
2295 }
2296 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2297 << S->getSourceRange() << Var;
2298 return true;
2299}
2300
2301bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2302 // RHS of canonical loop form increment can be:
2303 // var + incr
2304 // incr + var
2305 // var - incr
2306 //
2307 RHS = RHS->IgnoreParenImpCasts();
2308 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2309 if (BO->isAdditiveOp()) {
2310 bool IsAdd = BO->getOpcode() == BO_Add;
2311 if (GetInitVarDecl(BO->getLHS()) == Var)
2312 return SetStep(BO->getRHS(), !IsAdd);
2313 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2314 return SetStep(BO->getLHS(), false);
2315 }
2316 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2317 bool IsAdd = CE->getOperator() == OO_Plus;
2318 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2319 if (GetInitVarDecl(CE->getArg(0)) == Var)
2320 return SetStep(CE->getArg(1), !IsAdd);
2321 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2322 return SetStep(CE->getArg(0), false);
2323 }
2324 }
2325 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2326 << RHS->getSourceRange() << Var;
2327 return true;
2328}
2329
2330bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2331 // Check incr-expr for canonical loop form and return true if it
2332 // does not conform.
2333 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2334 // ++var
2335 // var++
2336 // --var
2337 // var--
2338 // var += incr
2339 // var -= incr
2340 // var = var + incr
2341 // var = incr + var
2342 // var = var - incr
2343 //
2344 if (!S) {
2345 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2346 return true;
2347 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002348 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002349 S = S->IgnoreParens();
2350 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2351 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2352 return SetStep(
2353 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2354 (UO->isDecrementOp() ? -1 : 1)).get(),
2355 false);
2356 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2357 switch (BO->getOpcode()) {
2358 case BO_AddAssign:
2359 case BO_SubAssign:
2360 if (GetInitVarDecl(BO->getLHS()) == Var)
2361 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2362 break;
2363 case BO_Assign:
2364 if (GetInitVarDecl(BO->getLHS()) == Var)
2365 return CheckIncRHS(BO->getRHS());
2366 break;
2367 default:
2368 break;
2369 }
2370 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2371 switch (CE->getOperator()) {
2372 case OO_PlusPlus:
2373 case OO_MinusMinus:
2374 if (GetInitVarDecl(CE->getArg(0)) == Var)
2375 return SetStep(
2376 SemaRef.ActOnIntegerConstant(
2377 CE->getLocStart(),
2378 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2379 false);
2380 break;
2381 case OO_PlusEqual:
2382 case OO_MinusEqual:
2383 if (GetInitVarDecl(CE->getArg(0)) == Var)
2384 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2385 break;
2386 case OO_Equal:
2387 if (GetInitVarDecl(CE->getArg(0)) == Var)
2388 return CheckIncRHS(CE->getArg(1));
2389 break;
2390 default:
2391 break;
2392 }
2393 }
2394 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2395 << S->getSourceRange() << Var;
2396 return true;
2397}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002398
2399/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002400Expr *
2401OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2402 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002403 ExprResult Diff;
2404 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2405 SemaRef.getLangOpts().CPlusPlus) {
2406 // Upper - Lower
2407 Expr *Upper = TestIsLessOp ? UB : LB;
2408 Expr *Lower = TestIsLessOp ? LB : UB;
2409
2410 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2411
2412 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2413 // BuildBinOp already emitted error, this one is to point user to upper
2414 // and lower bound, and to tell what is passed to 'operator-'.
2415 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2416 << Upper->getSourceRange() << Lower->getSourceRange();
2417 return nullptr;
2418 }
2419 }
2420
2421 if (!Diff.isUsable())
2422 return nullptr;
2423
2424 // Upper - Lower [- 1]
2425 if (TestIsStrictOp)
2426 Diff = SemaRef.BuildBinOp(
2427 S, DefaultLoc, BO_Sub, Diff.get(),
2428 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2429 if (!Diff.isUsable())
2430 return nullptr;
2431
2432 // Upper - Lower [- 1] + Step
2433 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2434 Step->IgnoreImplicit());
2435 if (!Diff.isUsable())
2436 return nullptr;
2437
2438 // Parentheses (for dumping/debugging purposes only).
2439 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2440 if (!Diff.isUsable())
2441 return nullptr;
2442
2443 // (Upper - Lower [- 1] + Step) / Step
2444 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2445 Step->IgnoreImplicit());
2446 if (!Diff.isUsable())
2447 return nullptr;
2448
Alexander Musman174b3ca2014-10-06 11:16:29 +00002449 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2450 if (LimitedType) {
2451 auto &C = SemaRef.Context;
2452 QualType Type = Diff.get()->getType();
2453 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2454 if (NewSize != C.getTypeSize(Type)) {
2455 if (NewSize < C.getTypeSize(Type)) {
2456 assert(NewSize == 64 && "incorrect loop var size");
2457 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2458 << InitSrcRange << ConditionSrcRange;
2459 }
2460 QualType NewType = C.getIntTypeForBitwidth(
2461 NewSize, Type->hasSignedIntegerRepresentation());
2462 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2463 Sema::AA_Converting, true);
2464 if (!Diff.isUsable())
2465 return nullptr;
2466 }
2467 }
2468
Alexander Musmana5f070a2014-10-01 06:03:56 +00002469 return Diff.get();
2470}
2471
Alexey Bataev62dbb972015-04-22 11:59:37 +00002472Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2473 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2474 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2475 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2476 auto CondExpr = SemaRef.BuildBinOp(
2477 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2478 : (TestIsStrictOp ? BO_GT : BO_GE),
2479 LB, UB);
2480 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2481 // Otherwise use original loop conditon and evaluate it in runtime.
2482 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2483}
2484
Alexander Musmana5f070a2014-10-01 06:03:56 +00002485/// \brief Build reference expression to the counter be used for codegen.
2486Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002487 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002488}
2489
2490/// \brief Build initization of the counter be used for codegen.
2491Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2492
2493/// \brief Build step of the counter be used for codegen.
2494Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2495
2496/// \brief Iteration space of a single for loop.
2497struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002498 /// \brief Condition of the loop.
2499 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002500 /// \brief This expression calculates the number of iterations in the loop.
2501 /// It is always possible to calculate it before starting the loop.
2502 Expr *NumIterations;
2503 /// \brief The loop counter variable.
2504 Expr *CounterVar;
2505 /// \brief This is initializer for the initial value of #CounterVar.
2506 Expr *CounterInit;
2507 /// \brief This is step for the #CounterVar used to generate its update:
2508 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2509 Expr *CounterStep;
2510 /// \brief Should step be subtracted?
2511 bool Subtract;
2512 /// \brief Source range of the loop init.
2513 SourceRange InitSrcRange;
2514 /// \brief Source range of the loop condition.
2515 SourceRange CondSrcRange;
2516 /// \brief Source range of the loop increment.
2517 SourceRange IncSrcRange;
2518};
2519
Alexey Bataev23b69422014-06-18 07:08:49 +00002520} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002521
Alexey Bataev9c821032015-04-30 04:23:23 +00002522void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2523 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2524 assert(Init && "Expected loop in canonical form.");
2525 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2526 if (CollapseIteration > 0 &&
2527 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2528 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2529 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2530 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2531 }
2532 DSAStack->setCollapseNumber(CollapseIteration - 1);
2533 }
2534}
2535
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002536/// \brief Called on a for stmt to check and extract its iteration space
2537/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002538static bool CheckOpenMPIterationSpace(
2539 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2540 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2541 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002542 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2543 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002544 // OpenMP [2.6, Canonical Loop Form]
2545 // for (init-expr; test-expr; incr-expr) structured-block
2546 auto For = dyn_cast_or_null<ForStmt>(S);
2547 if (!For) {
2548 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002549 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2550 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2551 << CurrentNestedLoopCount;
2552 if (NestedLoopCount > 1)
2553 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2554 diag::note_omp_collapse_expr)
2555 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002556 return true;
2557 }
2558 assert(For->getBody());
2559
2560 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2561
2562 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002563 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002564 if (ISC.CheckInit(Init)) {
2565 return true;
2566 }
2567
2568 bool HasErrors = false;
2569
2570 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002571 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002572
2573 // OpenMP [2.6, Canonical Loop Form]
2574 // Var is one of the following:
2575 // A variable of signed or unsigned integer type.
2576 // For C++, a variable of a random access iterator type.
2577 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002578 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002579 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2580 !VarType->isPointerType() &&
2581 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2582 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2583 << SemaRef.getLangOpts().CPlusPlus;
2584 HasErrors = true;
2585 }
2586
Alexey Bataev4acb8592014-07-07 13:01:15 +00002587 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2588 // Construct
2589 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2590 // parallel for construct is (are) private.
2591 // The loop iteration variable in the associated for-loop of a simd construct
2592 // with just one associated for-loop is linear with a constant-linear-step
2593 // that is the increment of the associated for-loop.
2594 // Exclude loop var from the list of variables with implicitly defined data
2595 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002596 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002597
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002598 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2599 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002600 // The loop iteration variable in the associated for-loop of a simd construct
2601 // with just one associated for-loop may be listed in a linear clause with a
2602 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002603 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2604 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002605 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002606 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2607 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2608 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002609 auto PredeterminedCKind =
2610 isOpenMPSimdDirective(DKind)
2611 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2612 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002613 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002614 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002615 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2616 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002617 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2618 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2619 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002620 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002621 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2622 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00002623 if (DVar.RefExpr == nullptr)
2624 DVar.CKind = PredeterminedCKind;
2625 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002626 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002627 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002628 // Make the loop iteration variable private (for worksharing constructs),
2629 // linear (for simd directives with the only one associated loop) or
2630 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002631 if (DVar.CKind == OMPC_unknown)
2632 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2633 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00002634 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002635 }
2636
Alexey Bataev7ff55242014-06-19 09:13:45 +00002637 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002638
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002639 // Check test-expr.
2640 HasErrors |= ISC.CheckCond(For->getCond());
2641
2642 // Check incr-expr.
2643 HasErrors |= ISC.CheckInc(For->getInc());
2644
Alexander Musmana5f070a2014-10-01 06:03:56 +00002645 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002646 return HasErrors;
2647
Alexander Musmana5f070a2014-10-01 06:03:56 +00002648 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002649 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00002650 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2651 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002652 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2653 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2654 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2655 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2656 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2657 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2658 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2659
Alexey Bataev62dbb972015-04-22 11:59:37 +00002660 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2661 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002662 ResultIterSpace.CounterVar == nullptr ||
2663 ResultIterSpace.CounterInit == nullptr ||
2664 ResultIterSpace.CounterStep == nullptr);
2665
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002666 return HasErrors;
2667}
2668
Alexander Musmana5f070a2014-10-01 06:03:56 +00002669/// \brief Build 'VarRef = Start + Iter * Step'.
2670static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2671 SourceLocation Loc, ExprResult VarRef,
2672 ExprResult Start, ExprResult Iter,
2673 ExprResult Step, bool Subtract) {
2674 // Add parentheses (for debugging purposes only).
2675 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2676 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2677 !Step.isUsable())
2678 return ExprError();
2679
2680 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2681 Step.get()->IgnoreImplicit());
2682 if (!Update.isUsable())
2683 return ExprError();
2684
2685 // Build 'VarRef = Start + Iter * Step'.
2686 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2687 Start.get()->IgnoreImplicit(), Update.get());
2688 if (!Update.isUsable())
2689 return ExprError();
2690
2691 Update = SemaRef.PerformImplicitConversion(
2692 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2693 if (!Update.isUsable())
2694 return ExprError();
2695
2696 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2697 return Update;
2698}
2699
2700/// \brief Convert integer expression \a E to make it have at least \a Bits
2701/// bits.
2702static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2703 Sema &SemaRef) {
2704 if (E == nullptr)
2705 return ExprError();
2706 auto &C = SemaRef.Context;
2707 QualType OldType = E->getType();
2708 unsigned HasBits = C.getTypeSize(OldType);
2709 if (HasBits >= Bits)
2710 return ExprResult(E);
2711 // OK to convert to signed, because new type has more bits than old.
2712 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2713 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2714 true);
2715}
2716
2717/// \brief Check if the given expression \a E is a constant integer that fits
2718/// into \a Bits bits.
2719static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2720 if (E == nullptr)
2721 return false;
2722 llvm::APSInt Result;
2723 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2724 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2725 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002726}
2727
2728/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002729/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2730/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002731static unsigned
2732CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2733 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002734 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002735 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002736 unsigned NestedLoopCount = 1;
2737 if (NestedLoopCountExpr) {
2738 // Found 'collapse' clause - calculate collapse number.
2739 llvm::APSInt Result;
2740 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2741 NestedLoopCount = Result.getLimitedValue();
2742 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002743 // This is helper routine for loop directives (e.g., 'for', 'simd',
2744 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002745 SmallVector<LoopIterationSpace, 4> IterSpaces;
2746 IterSpaces.resize(NestedLoopCount);
2747 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002748 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002749 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002750 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002751 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002752 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002753 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002754 // OpenMP [2.8.1, simd construct, Restrictions]
2755 // All loops associated with the construct must be perfectly nested; that
2756 // is, there must be no intervening code nor any OpenMP directive between
2757 // any two loops.
2758 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002759 }
2760
Alexander Musmana5f070a2014-10-01 06:03:56 +00002761 Built.clear(/* size */ NestedLoopCount);
2762
2763 if (SemaRef.CurContext->isDependentContext())
2764 return NestedLoopCount;
2765
2766 // An example of what is generated for the following code:
2767 //
2768 // #pragma omp simd collapse(2)
2769 // for (i = 0; i < NI; ++i)
2770 // for (j = J0; j < NJ; j+=2) {
2771 // <loop body>
2772 // }
2773 //
2774 // We generate the code below.
2775 // Note: the loop body may be outlined in CodeGen.
2776 // Note: some counters may be C++ classes, operator- is used to find number of
2777 // iterations and operator+= to calculate counter value.
2778 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2779 // or i64 is currently supported).
2780 //
2781 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2782 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2783 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2784 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2785 // // similar updates for vars in clauses (e.g. 'linear')
2786 // <loop body (using local i and j)>
2787 // }
2788 // i = NI; // assign final values of counters
2789 // j = NJ;
2790 //
2791
2792 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2793 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002794 // Precondition tests if there is at least one iteration (all conditions are
2795 // true).
2796 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002797 auto N0 = IterSpaces[0].NumIterations;
2798 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2799 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2800
2801 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2802 return NestedLoopCount;
2803
2804 auto &C = SemaRef.Context;
2805 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2806
2807 Scope *CurScope = DSA.getCurScope();
2808 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002809 if (PreCond.isUsable()) {
2810 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2811 PreCond.get(), IterSpaces[Cnt].PreCond);
2812 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002813 auto N = IterSpaces[Cnt].NumIterations;
2814 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2815 if (LastIteration32.isUsable())
2816 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2817 LastIteration32.get(), N);
2818 if (LastIteration64.isUsable())
2819 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2820 LastIteration64.get(), N);
2821 }
2822
2823 // Choose either the 32-bit or 64-bit version.
2824 ExprResult LastIteration = LastIteration64;
2825 if (LastIteration32.isUsable() &&
2826 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2827 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2828 FitsInto(
2829 32 /* Bits */,
2830 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2831 LastIteration64.get(), SemaRef)))
2832 LastIteration = LastIteration32;
2833
2834 if (!LastIteration.isUsable())
2835 return 0;
2836
2837 // Save the number of iterations.
2838 ExprResult NumIterations = LastIteration;
2839 {
2840 LastIteration = SemaRef.BuildBinOp(
2841 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2842 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2843 if (!LastIteration.isUsable())
2844 return 0;
2845 }
2846
2847 // Calculate the last iteration number beforehand instead of doing this on
2848 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2849 llvm::APSInt Result;
2850 bool IsConstant =
2851 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2852 ExprResult CalcLastIteration;
2853 if (!IsConstant) {
2854 SourceLocation SaveLoc;
2855 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00002856 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002857 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00002858 ExprResult SaveRef = buildDeclRefExpr(
2859 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002860 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2861 SaveRef.get(), LastIteration.get());
2862 LastIteration = SaveRef;
2863
2864 // Prepare SaveRef + 1.
2865 NumIterations = SemaRef.BuildBinOp(
2866 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2867 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2868 if (!NumIterations.isUsable())
2869 return 0;
2870 }
2871
2872 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2873
Alexander Musmanc6388682014-12-15 07:07:06 +00002874 QualType VType = LastIteration.get()->getType();
2875 // Build variables passed into runtime, nesessary for worksharing directives.
2876 ExprResult LB, UB, IL, ST, EUB;
2877 if (isOpenMPWorksharingDirective(DKind)) {
2878 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002879 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2880 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002881 SemaRef.AddInitializerToDecl(
2882 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2883 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2884
2885 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002886 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2887 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002888 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2889 /*DirectInit*/ false,
2890 /*TypeMayContainAuto*/ false);
2891
2892 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2893 // This will be used to implement clause 'lastprivate'.
2894 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002895 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2896 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002897 SemaRef.AddInitializerToDecl(
2898 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2899 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2900
2901 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00002902 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2903 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002904 SemaRef.AddInitializerToDecl(
2905 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2906 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2907
2908 // Build expression: UB = min(UB, LastIteration)
2909 // It is nesessary for CodeGen of directives with static scheduling.
2910 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2911 UB.get(), LastIteration.get());
2912 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2913 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2914 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2915 CondOp.get());
2916 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2917 }
2918
2919 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002920 ExprResult IV;
2921 ExprResult Init;
2922 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002923 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2924 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002925 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2926 ? LB.get()
2927 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2928 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2929 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002930 }
2931
Alexander Musmanc6388682014-12-15 07:07:06 +00002932 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002933 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002934 ExprResult Cond =
2935 isOpenMPWorksharingDirective(DKind)
2936 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2937 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2938 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002939 // Loop condition with 1 iteration separated (IV < LastIteration)
2940 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2941 IV.get(), LastIteration.get());
2942
2943 // Loop increment (IV = IV + 1)
2944 SourceLocation IncLoc;
2945 ExprResult Inc =
2946 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2947 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2948 if (!Inc.isUsable())
2949 return 0;
2950 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002951 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2952 if (!Inc.isUsable())
2953 return 0;
2954
2955 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2956 // Used for directives with static scheduling.
2957 ExprResult NextLB, NextUB;
2958 if (isOpenMPWorksharingDirective(DKind)) {
2959 // LB + ST
2960 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2961 if (!NextLB.isUsable())
2962 return 0;
2963 // LB = LB + ST
2964 NextLB =
2965 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2966 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2967 if (!NextLB.isUsable())
2968 return 0;
2969 // UB + ST
2970 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2971 if (!NextUB.isUsable())
2972 return 0;
2973 // UB = UB + ST
2974 NextUB =
2975 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2976 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2977 if (!NextUB.isUsable())
2978 return 0;
2979 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002980
2981 // Build updates and final values of the loop counters.
2982 bool HasErrors = false;
2983 Built.Counters.resize(NestedLoopCount);
2984 Built.Updates.resize(NestedLoopCount);
2985 Built.Finals.resize(NestedLoopCount);
2986 {
2987 ExprResult Div;
2988 // Go from inner nested loop to outer.
2989 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2990 LoopIterationSpace &IS = IterSpaces[Cnt];
2991 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2992 // Build: Iter = (IV / Div) % IS.NumIters
2993 // where Div is product of previous iterations' IS.NumIters.
2994 ExprResult Iter;
2995 if (Div.isUsable()) {
2996 Iter =
2997 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2998 } else {
2999 Iter = IV;
3000 assert((Cnt == (int)NestedLoopCount - 1) &&
3001 "unusable div expected on first iteration only");
3002 }
3003
3004 if (Cnt != 0 && Iter.isUsable())
3005 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3006 IS.NumIterations);
3007 if (!Iter.isUsable()) {
3008 HasErrors = true;
3009 break;
3010 }
3011
Alexey Bataev39f915b82015-05-08 10:41:21 +00003012 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3013 auto *CounterVar = buildDeclRefExpr(
3014 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3015 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3016 /*RefersToCapture=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003017 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003018 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003019 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3020 if (!Update.isUsable()) {
3021 HasErrors = true;
3022 break;
3023 }
3024
3025 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3026 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003027 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003028 IS.NumIterations, IS.CounterStep, IS.Subtract);
3029 if (!Final.isUsable()) {
3030 HasErrors = true;
3031 break;
3032 }
3033
3034 // Build Div for the next iteration: Div <- Div * IS.NumIters
3035 if (Cnt != 0) {
3036 if (Div.isUnset())
3037 Div = IS.NumIterations;
3038 else
3039 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3040 IS.NumIterations);
3041
3042 // Add parentheses (for debugging purposes only).
3043 if (Div.isUsable())
3044 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3045 if (!Div.isUsable()) {
3046 HasErrors = true;
3047 break;
3048 }
3049 }
3050 if (!Update.isUsable() || !Final.isUsable()) {
3051 HasErrors = true;
3052 break;
3053 }
3054 // Save results
3055 Built.Counters[Cnt] = IS.CounterVar;
3056 Built.Updates[Cnt] = Update.get();
3057 Built.Finals[Cnt] = Final.get();
3058 }
3059 }
3060
3061 if (HasErrors)
3062 return 0;
3063
3064 // Save results
3065 Built.IterationVarRef = IV.get();
3066 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003067 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003068 Built.CalcLastIteration = CalcLastIteration.get();
3069 Built.PreCond = PreCond.get();
3070 Built.Cond = Cond.get();
3071 Built.SeparatedCond = SeparatedCond.get();
3072 Built.Init = Init.get();
3073 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003074 Built.LB = LB.get();
3075 Built.UB = UB.get();
3076 Built.IL = IL.get();
3077 Built.ST = ST.get();
3078 Built.EUB = EUB.get();
3079 Built.NLB = NextLB.get();
3080 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003081
Alexey Bataevabfc0692014-06-25 06:52:00 +00003082 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003083}
3084
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003085static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevc925aa32015-04-27 08:00:32 +00003086 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003087 return C->getClauseKind() == OMPC_collapse;
3088 };
3089 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
Alexey Bataevc925aa32015-04-27 08:00:32 +00003090 Clauses, std::move(CollapseFilter));
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003091 if (I)
3092 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3093 return nullptr;
3094}
3095
Alexey Bataev4acb8592014-07-07 13:01:15 +00003096StmtResult Sema::ActOnOpenMPSimdDirective(
3097 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3098 SourceLocation EndLoc,
3099 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003100 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003101 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003102 unsigned NestedLoopCount =
3103 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003104 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003105 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003106 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003107
Alexander Musmana5f070a2014-10-01 06:03:56 +00003108 assert((CurContext->isDependentContext() || B.builtAll()) &&
3109 "omp simd loop exprs were not built");
3110
Alexander Musman3276a272015-03-21 10:12:56 +00003111 if (!CurContext->isDependentContext()) {
3112 // Finalize the clauses that need pre-built expressions for CodeGen.
3113 for (auto C : Clauses) {
3114 if (auto LC = dyn_cast<OMPLinearClause>(C))
3115 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3116 B.NumIterations, *this, CurScope))
3117 return StmtError();
3118 }
3119 }
3120
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003121 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003122 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3123 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003124}
3125
Alexey Bataev4acb8592014-07-07 13:01:15 +00003126StmtResult Sema::ActOnOpenMPForDirective(
3127 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3128 SourceLocation EndLoc,
3129 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003130 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003131 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003132 unsigned NestedLoopCount =
3133 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003134 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003135 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003136 return StmtError();
3137
Alexander Musmana5f070a2014-10-01 06:03:56 +00003138 assert((CurContext->isDependentContext() || B.builtAll()) &&
3139 "omp for loop exprs were not built");
3140
Alexey Bataevf29276e2014-06-18 04:14:57 +00003141 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003142 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3143 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003144}
3145
Alexander Musmanf82886e2014-09-18 05:12:34 +00003146StmtResult Sema::ActOnOpenMPForSimdDirective(
3147 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3148 SourceLocation EndLoc,
3149 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003150 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003151 // In presence of clause 'collapse', it will define the nested loops number.
3152 unsigned NestedLoopCount =
3153 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003154 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003155 if (NestedLoopCount == 0)
3156 return StmtError();
3157
Alexander Musmanc6388682014-12-15 07:07:06 +00003158 assert((CurContext->isDependentContext() || B.builtAll()) &&
3159 "omp for simd loop exprs were not built");
3160
Alexander Musmanf82886e2014-09-18 05:12:34 +00003161 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003162 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3163 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003164}
3165
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003166StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3167 Stmt *AStmt,
3168 SourceLocation StartLoc,
3169 SourceLocation EndLoc) {
3170 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3171 auto BaseStmt = AStmt;
3172 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3173 BaseStmt = CS->getCapturedStmt();
3174 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3175 auto S = C->children();
3176 if (!S)
3177 return StmtError();
3178 // All associated statements must be '#pragma omp section' except for
3179 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003180 for (++S; S; ++S) {
3181 auto SectionStmt = *S;
3182 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3183 if (SectionStmt)
3184 Diag(SectionStmt->getLocStart(),
3185 diag::err_omp_sections_substmt_not_section);
3186 return StmtError();
3187 }
3188 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003189 } else {
3190 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3191 return StmtError();
3192 }
3193
3194 getCurFunction()->setHasBranchProtectedScope();
3195
3196 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3197 AStmt);
3198}
3199
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003200StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3201 SourceLocation StartLoc,
3202 SourceLocation EndLoc) {
3203 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3204
3205 getCurFunction()->setHasBranchProtectedScope();
3206
3207 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3208}
3209
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003210StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3211 Stmt *AStmt,
3212 SourceLocation StartLoc,
3213 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003214 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3215
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003216 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003217
Alexey Bataev3255bf32015-01-19 05:20:46 +00003218 // OpenMP [2.7.3, single Construct, Restrictions]
3219 // The copyprivate clause must not be used with the nowait clause.
3220 OMPClause *Nowait = nullptr;
3221 OMPClause *Copyprivate = nullptr;
3222 for (auto *Clause : Clauses) {
3223 if (Clause->getClauseKind() == OMPC_nowait)
3224 Nowait = Clause;
3225 else if (Clause->getClauseKind() == OMPC_copyprivate)
3226 Copyprivate = Clause;
3227 if (Copyprivate && Nowait) {
3228 Diag(Copyprivate->getLocStart(),
3229 diag::err_omp_single_copyprivate_with_nowait);
3230 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3231 return StmtError();
3232 }
3233 }
3234
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003235 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3236}
3237
Alexander Musman80c22892014-07-17 08:54:58 +00003238StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3239 SourceLocation StartLoc,
3240 SourceLocation EndLoc) {
3241 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3242
3243 getCurFunction()->setHasBranchProtectedScope();
3244
3245 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3246}
3247
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003248StmtResult
3249Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3250 Stmt *AStmt, SourceLocation StartLoc,
3251 SourceLocation EndLoc) {
3252 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3253
3254 getCurFunction()->setHasBranchProtectedScope();
3255
3256 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3257 AStmt);
3258}
3259
Alexey Bataev4acb8592014-07-07 13:01:15 +00003260StmtResult Sema::ActOnOpenMPParallelForDirective(
3261 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3262 SourceLocation EndLoc,
3263 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3264 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3265 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3266 // 1.2.2 OpenMP Language Terminology
3267 // Structured block - An executable statement with a single entry at the
3268 // top and a single exit at the bottom.
3269 // The point of exit cannot be a branch out of the structured block.
3270 // longjmp() and throw() must not violate the entry/exit criteria.
3271 CS->getCapturedDecl()->setNothrow();
3272
Alexander Musmanc6388682014-12-15 07:07:06 +00003273 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003274 // In presence of clause 'collapse', it will define the nested loops number.
3275 unsigned NestedLoopCount =
3276 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003277 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003278 if (NestedLoopCount == 0)
3279 return StmtError();
3280
Alexander Musmana5f070a2014-10-01 06:03:56 +00003281 assert((CurContext->isDependentContext() || B.builtAll()) &&
3282 "omp parallel for loop exprs were not built");
3283
Alexey Bataev4acb8592014-07-07 13:01:15 +00003284 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003285 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3286 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003287}
3288
Alexander Musmane4e893b2014-09-23 09:33:00 +00003289StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3290 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3291 SourceLocation EndLoc,
3292 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3293 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3294 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3295 // 1.2.2 OpenMP Language Terminology
3296 // Structured block - An executable statement with a single entry at the
3297 // top and a single exit at the bottom.
3298 // The point of exit cannot be a branch out of the structured block.
3299 // longjmp() and throw() must not violate the entry/exit criteria.
3300 CS->getCapturedDecl()->setNothrow();
3301
Alexander Musmanc6388682014-12-15 07:07:06 +00003302 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003303 // In presence of clause 'collapse', it will define the nested loops number.
3304 unsigned NestedLoopCount =
3305 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003306 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003307 if (NestedLoopCount == 0)
3308 return StmtError();
3309
3310 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003311 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003312 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003313}
3314
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003315StmtResult
3316Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3317 Stmt *AStmt, SourceLocation StartLoc,
3318 SourceLocation EndLoc) {
3319 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3320 auto BaseStmt = AStmt;
3321 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3322 BaseStmt = CS->getCapturedStmt();
3323 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3324 auto S = C->children();
3325 if (!S)
3326 return StmtError();
3327 // All associated statements must be '#pragma omp section' except for
3328 // the first one.
3329 for (++S; S; ++S) {
3330 auto SectionStmt = *S;
3331 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3332 if (SectionStmt)
3333 Diag(SectionStmt->getLocStart(),
3334 diag::err_omp_parallel_sections_substmt_not_section);
3335 return StmtError();
3336 }
3337 }
3338 } else {
3339 Diag(AStmt->getLocStart(),
3340 diag::err_omp_parallel_sections_not_compound_stmt);
3341 return StmtError();
3342 }
3343
3344 getCurFunction()->setHasBranchProtectedScope();
3345
3346 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3347 Clauses, AStmt);
3348}
3349
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003350StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3351 Stmt *AStmt, SourceLocation StartLoc,
3352 SourceLocation EndLoc) {
3353 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3354 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3355 // 1.2.2 OpenMP Language Terminology
3356 // Structured block - An executable statement with a single entry at the
3357 // top and a single exit at the bottom.
3358 // The point of exit cannot be a branch out of the structured block.
3359 // longjmp() and throw() must not violate the entry/exit criteria.
3360 CS->getCapturedDecl()->setNothrow();
3361
3362 getCurFunction()->setHasBranchProtectedScope();
3363
3364 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3365}
3366
Alexey Bataev68446b72014-07-18 07:47:19 +00003367StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3368 SourceLocation EndLoc) {
3369 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3370}
3371
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003372StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3373 SourceLocation EndLoc) {
3374 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3375}
3376
Alexey Bataev2df347a2014-07-18 10:17:07 +00003377StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3378 SourceLocation EndLoc) {
3379 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3380}
3381
Alexey Bataev6125da92014-07-21 11:26:11 +00003382StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3383 SourceLocation StartLoc,
3384 SourceLocation EndLoc) {
3385 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3386 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3387}
3388
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003389StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3390 SourceLocation StartLoc,
3391 SourceLocation EndLoc) {
3392 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3393
3394 getCurFunction()->setHasBranchProtectedScope();
3395
3396 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3397}
3398
Alexey Bataev1d160b12015-03-13 12:27:31 +00003399namespace {
3400/// \brief Helper class for checking expression in 'omp atomic [update]'
3401/// construct.
3402class OpenMPAtomicUpdateChecker {
3403 /// \brief Error results for atomic update expressions.
3404 enum ExprAnalysisErrorCode {
3405 /// \brief A statement is not an expression statement.
3406 NotAnExpression,
3407 /// \brief Expression is not builtin binary or unary operation.
3408 NotABinaryOrUnaryExpression,
3409 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3410 NotAnUnaryIncDecExpression,
3411 /// \brief An expression is not of scalar type.
3412 NotAScalarType,
3413 /// \brief A binary operation is not an assignment operation.
3414 NotAnAssignmentOp,
3415 /// \brief RHS part of the binary operation is not a binary expression.
3416 NotABinaryExpression,
3417 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3418 /// expression.
3419 NotABinaryOperator,
3420 /// \brief RHS binary operation does not have reference to the updated LHS
3421 /// part.
3422 NotAnUpdateExpression,
3423 /// \brief No errors is found.
3424 NoError
3425 };
3426 /// \brief Reference to Sema.
3427 Sema &SemaRef;
3428 /// \brief A location for note diagnostics (when error is found).
3429 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003430 /// \brief 'x' lvalue part of the source atomic expression.
3431 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003432 /// \brief 'expr' rvalue part of the source atomic expression.
3433 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003434 /// \brief Helper expression of the form
3435 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3436 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3437 Expr *UpdateExpr;
3438 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3439 /// important for non-associative operations.
3440 bool IsXLHSInRHSPart;
3441 BinaryOperatorKind Op;
3442 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003443 /// \brief true if the source expression is a postfix unary operation, false
3444 /// if it is a prefix unary operation.
3445 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003446
3447public:
3448 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003449 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003450 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003451 /// \brief Check specified statement that it is suitable for 'atomic update'
3452 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003453 /// expression. If DiagId and NoteId == 0, then only check is performed
3454 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003455 /// \param DiagId Diagnostic which should be emitted if error is found.
3456 /// \param NoteId Diagnostic note for the main error message.
3457 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003458 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003459 /// \brief Return the 'x' lvalue part of the source atomic expression.
3460 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003461 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3462 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003463 /// \brief Return the update expression used in calculation of the updated
3464 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3465 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3466 Expr *getUpdateExpr() const { return UpdateExpr; }
3467 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3468 /// false otherwise.
3469 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3470
Alexey Bataevb78ca832015-04-01 03:33:17 +00003471 /// \brief true if the source expression is a postfix unary operation, false
3472 /// if it is a prefix unary operation.
3473 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3474
Alexey Bataev1d160b12015-03-13 12:27:31 +00003475private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003476 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3477 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003478};
3479} // namespace
3480
3481bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3482 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3483 ExprAnalysisErrorCode ErrorFound = NoError;
3484 SourceLocation ErrorLoc, NoteLoc;
3485 SourceRange ErrorRange, NoteRange;
3486 // Allowed constructs are:
3487 // x = x binop expr;
3488 // x = expr binop x;
3489 if (AtomicBinOp->getOpcode() == BO_Assign) {
3490 X = AtomicBinOp->getLHS();
3491 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3492 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3493 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3494 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3495 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003496 Op = AtomicInnerBinOp->getOpcode();
3497 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003498 auto *LHS = AtomicInnerBinOp->getLHS();
3499 auto *RHS = AtomicInnerBinOp->getRHS();
3500 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3501 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3502 /*Canonical=*/true);
3503 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3504 /*Canonical=*/true);
3505 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3506 /*Canonical=*/true);
3507 if (XId == LHSId) {
3508 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003509 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003510 } else if (XId == RHSId) {
3511 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003512 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003513 } else {
3514 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3515 ErrorRange = AtomicInnerBinOp->getSourceRange();
3516 NoteLoc = X->getExprLoc();
3517 NoteRange = X->getSourceRange();
3518 ErrorFound = NotAnUpdateExpression;
3519 }
3520 } else {
3521 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3522 ErrorRange = AtomicInnerBinOp->getSourceRange();
3523 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3524 NoteRange = SourceRange(NoteLoc, NoteLoc);
3525 ErrorFound = NotABinaryOperator;
3526 }
3527 } else {
3528 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3529 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3530 ErrorFound = NotABinaryExpression;
3531 }
3532 } else {
3533 ErrorLoc = AtomicBinOp->getExprLoc();
3534 ErrorRange = AtomicBinOp->getSourceRange();
3535 NoteLoc = AtomicBinOp->getOperatorLoc();
3536 NoteRange = SourceRange(NoteLoc, NoteLoc);
3537 ErrorFound = NotAnAssignmentOp;
3538 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003539 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003540 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3541 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3542 return true;
3543 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003544 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003545 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003546}
3547
3548bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3549 unsigned NoteId) {
3550 ExprAnalysisErrorCode ErrorFound = NoError;
3551 SourceLocation ErrorLoc, NoteLoc;
3552 SourceRange ErrorRange, NoteRange;
3553 // Allowed constructs are:
3554 // x++;
3555 // x--;
3556 // ++x;
3557 // --x;
3558 // x binop= expr;
3559 // x = x binop expr;
3560 // x = expr binop x;
3561 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3562 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3563 if (AtomicBody->getType()->isScalarType() ||
3564 AtomicBody->isInstantiationDependent()) {
3565 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3566 AtomicBody->IgnoreParenImpCasts())) {
3567 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003568 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003569 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003570 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003571 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003572 X = AtomicCompAssignOp->getLHS();
3573 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003574 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3575 AtomicBody->IgnoreParenImpCasts())) {
3576 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003577 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3578 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003579 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003580 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3581 // Check for Unary Operation
3582 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003583 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003584 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3585 OpLoc = AtomicUnaryOp->getOperatorLoc();
3586 X = AtomicUnaryOp->getSubExpr();
3587 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3588 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003589 } else {
3590 ErrorFound = NotAnUnaryIncDecExpression;
3591 ErrorLoc = AtomicUnaryOp->getExprLoc();
3592 ErrorRange = AtomicUnaryOp->getSourceRange();
3593 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3594 NoteRange = SourceRange(NoteLoc, NoteLoc);
3595 }
3596 } else {
3597 ErrorFound = NotABinaryOrUnaryExpression;
3598 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3599 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3600 }
3601 } else {
3602 ErrorFound = NotAScalarType;
3603 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3604 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3605 }
3606 } else {
3607 ErrorFound = NotAnExpression;
3608 NoteLoc = ErrorLoc = S->getLocStart();
3609 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3610 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003611 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003612 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3613 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3614 return true;
3615 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003616 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003617 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003618 // Build an update expression of form 'OpaqueValueExpr(x) binop
3619 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3620 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3621 auto *OVEX = new (SemaRef.getASTContext())
3622 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3623 auto *OVEExpr = new (SemaRef.getASTContext())
3624 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3625 auto Update =
3626 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3627 IsXLHSInRHSPart ? OVEExpr : OVEX);
3628 if (Update.isInvalid())
3629 return true;
3630 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3631 Sema::AA_Casting);
3632 if (Update.isInvalid())
3633 return true;
3634 UpdateExpr = Update.get();
3635 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003636 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003637}
3638
Alexey Bataev0162e452014-07-22 10:10:35 +00003639StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3640 Stmt *AStmt,
3641 SourceLocation StartLoc,
3642 SourceLocation EndLoc) {
3643 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003644 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003645 // 1.2.2 OpenMP Language Terminology
3646 // Structured block - An executable statement with a single entry at the
3647 // top and a single exit at the bottom.
3648 // The point of exit cannot be a branch out of the structured block.
3649 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003650 OpenMPClauseKind AtomicKind = OMPC_unknown;
3651 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003652 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003653 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003654 C->getClauseKind() == OMPC_update ||
3655 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003656 if (AtomicKind != OMPC_unknown) {
3657 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3658 << SourceRange(C->getLocStart(), C->getLocEnd());
3659 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3660 << getOpenMPClauseName(AtomicKind);
3661 } else {
3662 AtomicKind = C->getClauseKind();
3663 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003664 }
3665 }
3666 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003667
Alexey Bataev459dec02014-07-24 06:46:57 +00003668 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003669 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3670 Body = EWC->getSubExpr();
3671
Alexey Bataev62cec442014-11-18 10:14:22 +00003672 Expr *X = nullptr;
3673 Expr *V = nullptr;
3674 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003675 Expr *UE = nullptr;
3676 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003677 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003678 // OpenMP [2.12.6, atomic Construct]
3679 // In the next expressions:
3680 // * x and v (as applicable) are both l-value expressions with scalar type.
3681 // * During the execution of an atomic region, multiple syntactic
3682 // occurrences of x must designate the same storage location.
3683 // * Neither of v and expr (as applicable) may access the storage location
3684 // designated by x.
3685 // * Neither of x and expr (as applicable) may access the storage location
3686 // designated by v.
3687 // * expr is an expression with scalar type.
3688 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3689 // * binop, binop=, ++, and -- are not overloaded operators.
3690 // * The expression x binop expr must be numerically equivalent to x binop
3691 // (expr). This requirement is satisfied if the operators in expr have
3692 // precedence greater than binop, or by using parentheses around expr or
3693 // subexpressions of expr.
3694 // * The expression expr binop x must be numerically equivalent to (expr)
3695 // binop x. This requirement is satisfied if the operators in expr have
3696 // precedence equal to or greater than binop, or by using parentheses around
3697 // expr or subexpressions of expr.
3698 // * For forms that allow multiple occurrences of x, the number of times
3699 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003700 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003701 enum {
3702 NotAnExpression,
3703 NotAnAssignmentOp,
3704 NotAScalarType,
3705 NotAnLValue,
3706 NoError
3707 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003708 SourceLocation ErrorLoc, NoteLoc;
3709 SourceRange ErrorRange, NoteRange;
3710 // If clause is read:
3711 // v = x;
3712 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3713 auto AtomicBinOp =
3714 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3715 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3716 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3717 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3718 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3719 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3720 if (!X->isLValue() || !V->isLValue()) {
3721 auto NotLValueExpr = X->isLValue() ? V : X;
3722 ErrorFound = NotAnLValue;
3723 ErrorLoc = AtomicBinOp->getExprLoc();
3724 ErrorRange = AtomicBinOp->getSourceRange();
3725 NoteLoc = NotLValueExpr->getExprLoc();
3726 NoteRange = NotLValueExpr->getSourceRange();
3727 }
3728 } else if (!X->isInstantiationDependent() ||
3729 !V->isInstantiationDependent()) {
3730 auto NotScalarExpr =
3731 (X->isInstantiationDependent() || X->getType()->isScalarType())
3732 ? V
3733 : X;
3734 ErrorFound = NotAScalarType;
3735 ErrorLoc = AtomicBinOp->getExprLoc();
3736 ErrorRange = AtomicBinOp->getSourceRange();
3737 NoteLoc = NotScalarExpr->getExprLoc();
3738 NoteRange = NotScalarExpr->getSourceRange();
3739 }
3740 } else {
3741 ErrorFound = NotAnAssignmentOp;
3742 ErrorLoc = AtomicBody->getExprLoc();
3743 ErrorRange = AtomicBody->getSourceRange();
3744 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3745 : AtomicBody->getExprLoc();
3746 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3747 : AtomicBody->getSourceRange();
3748 }
3749 } else {
3750 ErrorFound = NotAnExpression;
3751 NoteLoc = ErrorLoc = Body->getLocStart();
3752 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003753 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003754 if (ErrorFound != NoError) {
3755 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3756 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003757 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3758 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003759 return StmtError();
3760 } else if (CurContext->isDependentContext())
3761 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003762 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003763 enum {
3764 NotAnExpression,
3765 NotAnAssignmentOp,
3766 NotAScalarType,
3767 NotAnLValue,
3768 NoError
3769 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003770 SourceLocation ErrorLoc, NoteLoc;
3771 SourceRange ErrorRange, NoteRange;
3772 // If clause is write:
3773 // x = expr;
3774 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3775 auto AtomicBinOp =
3776 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3777 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003778 X = AtomicBinOp->getLHS();
3779 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003780 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3781 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3782 if (!X->isLValue()) {
3783 ErrorFound = NotAnLValue;
3784 ErrorLoc = AtomicBinOp->getExprLoc();
3785 ErrorRange = AtomicBinOp->getSourceRange();
3786 NoteLoc = X->getExprLoc();
3787 NoteRange = X->getSourceRange();
3788 }
3789 } else if (!X->isInstantiationDependent() ||
3790 !E->isInstantiationDependent()) {
3791 auto NotScalarExpr =
3792 (X->isInstantiationDependent() || X->getType()->isScalarType())
3793 ? E
3794 : X;
3795 ErrorFound = NotAScalarType;
3796 ErrorLoc = AtomicBinOp->getExprLoc();
3797 ErrorRange = AtomicBinOp->getSourceRange();
3798 NoteLoc = NotScalarExpr->getExprLoc();
3799 NoteRange = NotScalarExpr->getSourceRange();
3800 }
3801 } else {
3802 ErrorFound = NotAnAssignmentOp;
3803 ErrorLoc = AtomicBody->getExprLoc();
3804 ErrorRange = AtomicBody->getSourceRange();
3805 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3806 : AtomicBody->getExprLoc();
3807 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3808 : AtomicBody->getSourceRange();
3809 }
3810 } else {
3811 ErrorFound = NotAnExpression;
3812 NoteLoc = ErrorLoc = Body->getLocStart();
3813 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003814 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003815 if (ErrorFound != NoError) {
3816 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3817 << ErrorRange;
3818 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3819 << NoteRange;
3820 return StmtError();
3821 } else if (CurContext->isDependentContext())
3822 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003823 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003824 // If clause is update:
3825 // x++;
3826 // x--;
3827 // ++x;
3828 // --x;
3829 // x binop= expr;
3830 // x = x binop expr;
3831 // x = expr binop x;
3832 OpenMPAtomicUpdateChecker Checker(*this);
3833 if (Checker.checkStatement(
3834 Body, (AtomicKind == OMPC_update)
3835 ? diag::err_omp_atomic_update_not_expression_statement
3836 : diag::err_omp_atomic_not_expression_statement,
3837 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003838 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003839 if (!CurContext->isDependentContext()) {
3840 E = Checker.getExpr();
3841 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003842 UE = Checker.getUpdateExpr();
3843 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003844 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003845 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003846 enum {
3847 NotAnAssignmentOp,
3848 NotACompoundStatement,
3849 NotTwoSubstatements,
3850 NotASpecificExpression,
3851 NoError
3852 } ErrorFound = NoError;
3853 SourceLocation ErrorLoc, NoteLoc;
3854 SourceRange ErrorRange, NoteRange;
3855 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3856 // If clause is a capture:
3857 // v = x++;
3858 // v = x--;
3859 // v = ++x;
3860 // v = --x;
3861 // v = x binop= expr;
3862 // v = x = x binop expr;
3863 // v = x = expr binop x;
3864 auto *AtomicBinOp =
3865 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3866 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3867 V = AtomicBinOp->getLHS();
3868 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3869 OpenMPAtomicUpdateChecker Checker(*this);
3870 if (Checker.checkStatement(
3871 Body, diag::err_omp_atomic_capture_not_expression_statement,
3872 diag::note_omp_atomic_update))
3873 return StmtError();
3874 E = Checker.getExpr();
3875 X = Checker.getX();
3876 UE = Checker.getUpdateExpr();
3877 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3878 IsPostfixUpdate = Checker.isPostfixUpdate();
3879 } else {
3880 ErrorLoc = AtomicBody->getExprLoc();
3881 ErrorRange = AtomicBody->getSourceRange();
3882 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3883 : AtomicBody->getExprLoc();
3884 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3885 : AtomicBody->getSourceRange();
3886 ErrorFound = NotAnAssignmentOp;
3887 }
3888 if (ErrorFound != NoError) {
3889 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3890 << ErrorRange;
3891 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3892 return StmtError();
3893 } else if (CurContext->isDependentContext()) {
3894 UE = V = E = X = nullptr;
3895 }
3896 } else {
3897 // If clause is a capture:
3898 // { v = x; x = expr; }
3899 // { v = x; x++; }
3900 // { v = x; x--; }
3901 // { v = x; ++x; }
3902 // { v = x; --x; }
3903 // { v = x; x binop= expr; }
3904 // { v = x; x = x binop expr; }
3905 // { v = x; x = expr binop x; }
3906 // { x++; v = x; }
3907 // { x--; v = x; }
3908 // { ++x; v = x; }
3909 // { --x; v = x; }
3910 // { x binop= expr; v = x; }
3911 // { x = x binop expr; v = x; }
3912 // { x = expr binop x; v = x; }
3913 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3914 // Check that this is { expr1; expr2; }
3915 if (CS->size() == 2) {
3916 auto *First = CS->body_front();
3917 auto *Second = CS->body_back();
3918 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3919 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3920 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3921 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3922 // Need to find what subexpression is 'v' and what is 'x'.
3923 OpenMPAtomicUpdateChecker Checker(*this);
3924 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3925 BinaryOperator *BinOp = nullptr;
3926 if (IsUpdateExprFound) {
3927 BinOp = dyn_cast<BinaryOperator>(First);
3928 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3929 }
3930 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3931 // { v = x; x++; }
3932 // { v = x; x--; }
3933 // { v = x; ++x; }
3934 // { v = x; --x; }
3935 // { v = x; x binop= expr; }
3936 // { v = x; x = x binop expr; }
3937 // { v = x; x = expr binop x; }
3938 // Check that the first expression has form v = x.
3939 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3940 llvm::FoldingSetNodeID XId, PossibleXId;
3941 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3942 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3943 IsUpdateExprFound = XId == PossibleXId;
3944 if (IsUpdateExprFound) {
3945 V = BinOp->getLHS();
3946 X = Checker.getX();
3947 E = Checker.getExpr();
3948 UE = Checker.getUpdateExpr();
3949 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003950 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003951 }
3952 }
3953 if (!IsUpdateExprFound) {
3954 IsUpdateExprFound = !Checker.checkStatement(First);
3955 BinOp = nullptr;
3956 if (IsUpdateExprFound) {
3957 BinOp = dyn_cast<BinaryOperator>(Second);
3958 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3959 }
3960 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3961 // { x++; v = x; }
3962 // { x--; v = x; }
3963 // { ++x; v = x; }
3964 // { --x; v = x; }
3965 // { x binop= expr; v = x; }
3966 // { x = x binop expr; v = x; }
3967 // { x = expr binop x; v = x; }
3968 // Check that the second expression has form v = x.
3969 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3970 llvm::FoldingSetNodeID XId, PossibleXId;
3971 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3972 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3973 IsUpdateExprFound = XId == PossibleXId;
3974 if (IsUpdateExprFound) {
3975 V = BinOp->getLHS();
3976 X = Checker.getX();
3977 E = Checker.getExpr();
3978 UE = Checker.getUpdateExpr();
3979 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003980 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003981 }
3982 }
3983 }
3984 if (!IsUpdateExprFound) {
3985 // { v = x; x = expr; }
3986 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3987 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3988 ErrorFound = NotAnAssignmentOp;
3989 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3990 : First->getLocStart();
3991 NoteRange = ErrorRange = FirstBinOp
3992 ? FirstBinOp->getSourceRange()
3993 : SourceRange(ErrorLoc, ErrorLoc);
3994 } else {
3995 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3996 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3997 ErrorFound = NotAnAssignmentOp;
3998 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3999 : Second->getLocStart();
4000 NoteRange = ErrorRange = SecondBinOp
4001 ? SecondBinOp->getSourceRange()
4002 : SourceRange(ErrorLoc, ErrorLoc);
4003 } else {
4004 auto *PossibleXRHSInFirst =
4005 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4006 auto *PossibleXLHSInSecond =
4007 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4008 llvm::FoldingSetNodeID X1Id, X2Id;
4009 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4010 PossibleXLHSInSecond->Profile(X2Id, Context,
4011 /*Canonical=*/true);
4012 IsUpdateExprFound = X1Id == X2Id;
4013 if (IsUpdateExprFound) {
4014 V = FirstBinOp->getLHS();
4015 X = SecondBinOp->getLHS();
4016 E = SecondBinOp->getRHS();
4017 UE = nullptr;
4018 IsXLHSInRHSPart = false;
4019 IsPostfixUpdate = true;
4020 } else {
4021 ErrorFound = NotASpecificExpression;
4022 ErrorLoc = FirstBinOp->getExprLoc();
4023 ErrorRange = FirstBinOp->getSourceRange();
4024 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4025 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4026 }
4027 }
4028 }
4029 }
4030 } else {
4031 NoteLoc = ErrorLoc = Body->getLocStart();
4032 NoteRange = ErrorRange =
4033 SourceRange(Body->getLocStart(), Body->getLocStart());
4034 ErrorFound = NotTwoSubstatements;
4035 }
4036 } else {
4037 NoteLoc = ErrorLoc = Body->getLocStart();
4038 NoteRange = ErrorRange =
4039 SourceRange(Body->getLocStart(), Body->getLocStart());
4040 ErrorFound = NotACompoundStatement;
4041 }
4042 if (ErrorFound != NoError) {
4043 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4044 << ErrorRange;
4045 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4046 return StmtError();
4047 } else if (CurContext->isDependentContext()) {
4048 UE = V = E = X = nullptr;
4049 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004050 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004051 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004052
4053 getCurFunction()->setHasBranchProtectedScope();
4054
Alexey Bataev62cec442014-11-18 10:14:22 +00004055 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004056 X, V, E, UE, IsXLHSInRHSPart,
4057 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004058}
4059
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004060StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4061 Stmt *AStmt,
4062 SourceLocation StartLoc,
4063 SourceLocation EndLoc) {
4064 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4065
Alexey Bataev13314bf2014-10-09 04:18:56 +00004066 // OpenMP [2.16, Nesting of Regions]
4067 // If specified, a teams construct must be contained within a target
4068 // construct. That target construct must contain no statements or directives
4069 // outside of the teams construct.
4070 if (DSAStack->hasInnerTeamsRegion()) {
4071 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4072 bool OMPTeamsFound = true;
4073 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4074 auto I = CS->body_begin();
4075 while (I != CS->body_end()) {
4076 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4077 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4078 OMPTeamsFound = false;
4079 break;
4080 }
4081 ++I;
4082 }
4083 assert(I != CS->body_end() && "Not found statement");
4084 S = *I;
4085 }
4086 if (!OMPTeamsFound) {
4087 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4088 Diag(DSAStack->getInnerTeamsRegionLoc(),
4089 diag::note_omp_nested_teams_construct_here);
4090 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4091 << isa<OMPExecutableDirective>(S);
4092 return StmtError();
4093 }
4094 }
4095
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004096 getCurFunction()->setHasBranchProtectedScope();
4097
4098 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4099}
4100
Alexey Bataev13314bf2014-10-09 04:18:56 +00004101StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4102 Stmt *AStmt, SourceLocation StartLoc,
4103 SourceLocation EndLoc) {
4104 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4105 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4106 // 1.2.2 OpenMP Language Terminology
4107 // Structured block - An executable statement with a single entry at the
4108 // top and a single exit at the bottom.
4109 // The point of exit cannot be a branch out of the structured block.
4110 // longjmp() and throw() must not violate the entry/exit criteria.
4111 CS->getCapturedDecl()->setNothrow();
4112
4113 getCurFunction()->setHasBranchProtectedScope();
4114
4115 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4116}
4117
Alexey Bataeved09d242014-05-28 05:53:51 +00004118OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004119 SourceLocation StartLoc,
4120 SourceLocation LParenLoc,
4121 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004122 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004123 switch (Kind) {
4124 case OMPC_if:
4125 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4126 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004127 case OMPC_final:
4128 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4129 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004130 case OMPC_num_threads:
4131 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4132 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004133 case OMPC_safelen:
4134 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4135 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004136 case OMPC_collapse:
4137 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4138 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004139 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004140 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004141 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004142 case OMPC_private:
4143 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004144 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004145 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004146 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004147 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004148 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004149 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004150 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004151 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004152 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004153 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004154 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004155 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004156 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004157 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004158 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004159 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004160 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004161 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004162 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004163 llvm_unreachable("Clause is not allowed.");
4164 }
4165 return Res;
4166}
4167
Alexey Bataeved09d242014-05-28 05:53:51 +00004168OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004169 SourceLocation LParenLoc,
4170 SourceLocation EndLoc) {
4171 Expr *ValExpr = Condition;
4172 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4173 !Condition->isInstantiationDependent() &&
4174 !Condition->containsUnexpandedParameterPack()) {
4175 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004176 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004177 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004178 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004179
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004180 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004181 }
4182
4183 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4184}
4185
Alexey Bataev3778b602014-07-17 07:32:53 +00004186OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4187 SourceLocation StartLoc,
4188 SourceLocation LParenLoc,
4189 SourceLocation EndLoc) {
4190 Expr *ValExpr = Condition;
4191 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4192 !Condition->isInstantiationDependent() &&
4193 !Condition->containsUnexpandedParameterPack()) {
4194 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4195 Condition->getExprLoc(), Condition);
4196 if (Val.isInvalid())
4197 return nullptr;
4198
4199 ValExpr = Val.get();
4200 }
4201
4202 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4203}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004204ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4205 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004206 if (!Op)
4207 return ExprError();
4208
4209 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4210 public:
4211 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004212 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004213 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4214 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004215 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4216 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004217 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4218 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004219 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4220 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004221 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4222 QualType T,
4223 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004224 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4225 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004226 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4227 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004228 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004229 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004230 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004231 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4232 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004233 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4234 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004235 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4236 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004237 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004238 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004239 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004240 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4241 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004242 llvm_unreachable("conversion functions are permitted");
4243 }
4244 } ConvertDiagnoser;
4245 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4246}
4247
4248OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4249 SourceLocation StartLoc,
4250 SourceLocation LParenLoc,
4251 SourceLocation EndLoc) {
4252 Expr *ValExpr = NumThreads;
4253 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004254 !NumThreads->containsUnexpandedParameterPack()) {
4255 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4256 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004257 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004258 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004259 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004260
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004261 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004262
4263 // OpenMP [2.5, Restrictions]
4264 // The num_threads expression must evaluate to a positive integer value.
4265 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004266 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4267 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004268 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4269 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004270 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004271 }
4272 }
4273
Alexey Bataeved09d242014-05-28 05:53:51 +00004274 return new (Context)
4275 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004276}
4277
Alexey Bataev62c87d22014-03-21 04:51:18 +00004278ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4279 OpenMPClauseKind CKind) {
4280 if (!E)
4281 return ExprError();
4282 if (E->isValueDependent() || E->isTypeDependent() ||
4283 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004284 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004285 llvm::APSInt Result;
4286 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4287 if (ICE.isInvalid())
4288 return ExprError();
4289 if (!Result.isStrictlyPositive()) {
4290 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4291 << getOpenMPClauseName(CKind) << E->getSourceRange();
4292 return ExprError();
4293 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004294 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4295 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4296 << E->getSourceRange();
4297 return ExprError();
4298 }
Alexey Bataev9c821032015-04-30 04:23:23 +00004299 if (CKind == OMPC_collapse) {
4300 DSAStack->setCollapseNumber(Result.getExtValue());
4301 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004302 return ICE;
4303}
4304
4305OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4306 SourceLocation LParenLoc,
4307 SourceLocation EndLoc) {
4308 // OpenMP [2.8.1, simd construct, Description]
4309 // The parameter of the safelen clause must be a constant
4310 // positive integer expression.
4311 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4312 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004313 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004314 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004315 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004316}
4317
Alexander Musman64d33f12014-06-04 07:53:32 +00004318OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4319 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004320 SourceLocation LParenLoc,
4321 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004322 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004323 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004324 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004325 // The parameter of the collapse clause must be a constant
4326 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004327 ExprResult NumForLoopsResult =
4328 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4329 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004330 return nullptr;
4331 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004332 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004333}
4334
Alexey Bataeved09d242014-05-28 05:53:51 +00004335OMPClause *Sema::ActOnOpenMPSimpleClause(
4336 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4337 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004338 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004339 switch (Kind) {
4340 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004341 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004342 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4343 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004344 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004345 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004346 Res = ActOnOpenMPProcBindClause(
4347 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4348 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004349 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004350 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004351 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004352 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004353 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004354 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004355 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004356 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004357 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004358 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004359 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004360 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004361 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004362 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004363 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004364 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004365 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004366 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004367 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004368 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004369 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004370 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004371 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004372 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004373 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004374 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004375 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004376 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004377 llvm_unreachable("Clause is not allowed.");
4378 }
4379 return Res;
4380}
4381
4382OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4383 SourceLocation KindKwLoc,
4384 SourceLocation StartLoc,
4385 SourceLocation LParenLoc,
4386 SourceLocation EndLoc) {
4387 if (Kind == OMPC_DEFAULT_unknown) {
4388 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004389 static_assert(OMPC_DEFAULT_unknown > 0,
4390 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004391 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004392 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004393 Values += "'";
4394 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4395 Values += "'";
4396 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004397 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004398 Values += " or ";
4399 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004400 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004401 break;
4402 default:
4403 Values += Sep;
4404 break;
4405 }
4406 }
4407 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004408 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004409 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004410 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004411 switch (Kind) {
4412 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004413 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004414 break;
4415 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004416 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004417 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004418 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004419 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004420 break;
4421 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004422 return new (Context)
4423 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004424}
4425
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004426OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4427 SourceLocation KindKwLoc,
4428 SourceLocation StartLoc,
4429 SourceLocation LParenLoc,
4430 SourceLocation EndLoc) {
4431 if (Kind == OMPC_PROC_BIND_unknown) {
4432 std::string Values;
4433 std::string Sep(", ");
4434 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4435 Values += "'";
4436 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4437 Values += "'";
4438 switch (i) {
4439 case OMPC_PROC_BIND_unknown - 2:
4440 Values += " or ";
4441 break;
4442 case OMPC_PROC_BIND_unknown - 1:
4443 break;
4444 default:
4445 Values += Sep;
4446 break;
4447 }
4448 }
4449 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004450 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004451 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004452 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004453 return new (Context)
4454 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004455}
4456
Alexey Bataev56dafe82014-06-20 07:16:17 +00004457OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4458 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4459 SourceLocation StartLoc, SourceLocation LParenLoc,
4460 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4461 SourceLocation EndLoc) {
4462 OMPClause *Res = nullptr;
4463 switch (Kind) {
4464 case OMPC_schedule:
4465 Res = ActOnOpenMPScheduleClause(
4466 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4467 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4468 break;
4469 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004470 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004471 case OMPC_num_threads:
4472 case OMPC_safelen:
4473 case OMPC_collapse:
4474 case OMPC_default:
4475 case OMPC_proc_bind:
4476 case OMPC_private:
4477 case OMPC_firstprivate:
4478 case OMPC_lastprivate:
4479 case OMPC_shared:
4480 case OMPC_reduction:
4481 case OMPC_linear:
4482 case OMPC_aligned:
4483 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004484 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004485 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004486 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004487 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004488 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004489 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004490 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004491 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004492 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004493 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004494 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004495 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004496 case OMPC_unknown:
4497 llvm_unreachable("Clause is not allowed.");
4498 }
4499 return Res;
4500}
4501
4502OMPClause *Sema::ActOnOpenMPScheduleClause(
4503 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4504 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4505 SourceLocation EndLoc) {
4506 if (Kind == OMPC_SCHEDULE_unknown) {
4507 std::string Values;
4508 std::string Sep(", ");
4509 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4510 Values += "'";
4511 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4512 Values += "'";
4513 switch (i) {
4514 case OMPC_SCHEDULE_unknown - 2:
4515 Values += " or ";
4516 break;
4517 case OMPC_SCHEDULE_unknown - 1:
4518 break;
4519 default:
4520 Values += Sep;
4521 break;
4522 }
4523 }
4524 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4525 << Values << getOpenMPClauseName(OMPC_schedule);
4526 return nullptr;
4527 }
4528 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00004529 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004530 if (ChunkSize) {
4531 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4532 !ChunkSize->isInstantiationDependent() &&
4533 !ChunkSize->containsUnexpandedParameterPack()) {
4534 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4535 ExprResult Val =
4536 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4537 if (Val.isInvalid())
4538 return nullptr;
4539
4540 ValExpr = Val.get();
4541
4542 // OpenMP [2.7.1, Restrictions]
4543 // chunk_size must be a loop invariant integer expression with a positive
4544 // value.
4545 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00004546 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4547 if (Result.isSigned() && !Result.isStrictlyPositive()) {
4548 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4549 << "schedule" << ChunkSize->getSourceRange();
4550 return nullptr;
4551 }
4552 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4553 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4554 ChunkSize->getType(), ".chunk.");
4555 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4556 ChunkSize->getExprLoc(),
4557 /*RefersToCapture=*/true);
4558 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004559 }
4560 }
4561 }
4562
4563 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00004564 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00004565}
4566
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004567OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4568 SourceLocation StartLoc,
4569 SourceLocation EndLoc) {
4570 OMPClause *Res = nullptr;
4571 switch (Kind) {
4572 case OMPC_ordered:
4573 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4574 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004575 case OMPC_nowait:
4576 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4577 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004578 case OMPC_untied:
4579 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4580 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004581 case OMPC_mergeable:
4582 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4583 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004584 case OMPC_read:
4585 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4586 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004587 case OMPC_write:
4588 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4589 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004590 case OMPC_update:
4591 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4592 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004593 case OMPC_capture:
4594 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4595 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004596 case OMPC_seq_cst:
4597 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4598 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004599 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004600 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004601 case OMPC_num_threads:
4602 case OMPC_safelen:
4603 case OMPC_collapse:
4604 case OMPC_schedule:
4605 case OMPC_private:
4606 case OMPC_firstprivate:
4607 case OMPC_lastprivate:
4608 case OMPC_shared:
4609 case OMPC_reduction:
4610 case OMPC_linear:
4611 case OMPC_aligned:
4612 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004613 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004614 case OMPC_default:
4615 case OMPC_proc_bind:
4616 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004617 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004618 case OMPC_unknown:
4619 llvm_unreachable("Clause is not allowed.");
4620 }
4621 return Res;
4622}
4623
4624OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4625 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004626 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004627 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4628}
4629
Alexey Bataev236070f2014-06-20 11:19:47 +00004630OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4631 SourceLocation EndLoc) {
4632 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4633}
4634
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004635OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4636 SourceLocation EndLoc) {
4637 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4638}
4639
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004640OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4641 SourceLocation EndLoc) {
4642 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4643}
4644
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004645OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4646 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004647 return new (Context) OMPReadClause(StartLoc, EndLoc);
4648}
4649
Alexey Bataevdea47612014-07-23 07:46:59 +00004650OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4651 SourceLocation EndLoc) {
4652 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4653}
4654
Alexey Bataev67a4f222014-07-23 10:25:33 +00004655OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4656 SourceLocation EndLoc) {
4657 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4658}
4659
Alexey Bataev459dec02014-07-24 06:46:57 +00004660OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4661 SourceLocation EndLoc) {
4662 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4663}
4664
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004665OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4666 SourceLocation EndLoc) {
4667 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4668}
4669
Alexey Bataevc5e02582014-06-16 07:08:35 +00004670OMPClause *Sema::ActOnOpenMPVarListClause(
4671 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4672 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4673 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4674 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004675 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004676 switch (Kind) {
4677 case OMPC_private:
4678 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4679 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004680 case OMPC_firstprivate:
4681 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4682 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004683 case OMPC_lastprivate:
4684 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4685 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004686 case OMPC_shared:
4687 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4688 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004689 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004690 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4691 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004692 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004693 case OMPC_linear:
4694 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4695 ColonLoc, EndLoc);
4696 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004697 case OMPC_aligned:
4698 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4699 ColonLoc, EndLoc);
4700 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004701 case OMPC_copyin:
4702 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4703 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004704 case OMPC_copyprivate:
4705 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4706 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004707 case OMPC_flush:
4708 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4709 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004710 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004711 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004712 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004713 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004714 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004715 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004716 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004717 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004718 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004719 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004720 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004721 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004722 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004723 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004724 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004725 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004726 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004727 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004728 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004729 llvm_unreachable("Clause is not allowed.");
4730 }
4731 return Res;
4732}
4733
4734OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4735 SourceLocation StartLoc,
4736 SourceLocation LParenLoc,
4737 SourceLocation EndLoc) {
4738 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004739 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004740 for (auto &RefExpr : VarList) {
4741 assert(RefExpr && "NULL expr in OpenMP private clause.");
4742 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004743 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004744 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004745 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004746 continue;
4747 }
4748
Alexey Bataeved09d242014-05-28 05:53:51 +00004749 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004750 // OpenMP [2.1, C/C++]
4751 // A list item is a variable name.
4752 // OpenMP [2.9.3.3, Restrictions, p.1]
4753 // A variable that is part of another variable (as an array or
4754 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004755 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004756 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004757 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004758 continue;
4759 }
4760 Decl *D = DE->getDecl();
4761 VarDecl *VD = cast<VarDecl>(D);
4762
4763 QualType Type = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004764 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
4765 Type = PVD->getOriginalType();
4766 }
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004767 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4768 // It will be analyzed later.
4769 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004770 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004771 continue;
4772 }
4773
4774 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4775 // A variable that appears in a private clause must not have an incomplete
4776 // type or a reference type.
4777 if (RequireCompleteType(ELoc, Type,
4778 diag::err_omp_private_incomplete_type)) {
4779 continue;
4780 }
4781 if (Type->isReferenceType()) {
4782 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004783 << getOpenMPClauseName(OMPC_private) << Type;
4784 bool IsDecl =
4785 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4786 Diag(VD->getLocation(),
4787 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4788 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004789 continue;
4790 }
4791
Alexey Bataev758e55e2013-09-06 18:03:48 +00004792 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4793 // in a Construct]
4794 // Variables with the predetermined data-sharing attributes may not be
4795 // listed in data-sharing attributes clauses, except for the cases
4796 // listed below. For these exceptions only, listing a predetermined
4797 // variable in a data-sharing attribute clause is allowed and overrides
4798 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004799 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004800 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004801 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4802 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004803 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004804 continue;
4805 }
4806
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004807 // Variably modified types are not supported for tasks.
4808 if (Type->isVariablyModifiedType() &&
4809 DSAStack->getCurrentDirective() == OMPD_task) {
4810 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
4811 << getOpenMPClauseName(OMPC_private) << Type
4812 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4813 bool IsDecl =
4814 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4815 Diag(VD->getLocation(),
4816 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4817 << VD;
4818 continue;
4819 }
4820
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004821 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4822 // A variable of class type (or array thereof) that appears in a private
4823 // clause requires an accessible, unambiguous default constructor for the
4824 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004825 // Generate helper private variable and initialize it with the default
4826 // value. The address of the original variable is replaced by the address of
4827 // the new private variable in CodeGen. This new variable is not added to
4828 // IdResolver, so the code in the OpenMP region uses original variable for
4829 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004830 Type = Type.getUnqualifiedType();
4831 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
Alexey Bataev39f915b82015-05-08 10:41:21 +00004832 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004833 if (VDPrivate->isInvalidDecl())
4834 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004835 auto VDPrivateRefExpr = buildDeclRefExpr(
4836 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00004837
Alexey Bataev758e55e2013-09-06 18:03:48 +00004838 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004839 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004840 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004841 }
4842
Alexey Bataeved09d242014-05-28 05:53:51 +00004843 if (Vars.empty())
4844 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004845
Alexey Bataev03b340a2014-10-21 03:16:40 +00004846 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4847 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004848}
4849
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004850namespace {
4851class DiagsUninitializedSeveretyRAII {
4852private:
4853 DiagnosticsEngine &Diags;
4854 SourceLocation SavedLoc;
4855 bool IsIgnored;
4856
4857public:
4858 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4859 bool IsIgnored)
4860 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4861 if (!IsIgnored) {
4862 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4863 /*Map*/ diag::Severity::Ignored, Loc);
4864 }
4865 }
4866 ~DiagsUninitializedSeveretyRAII() {
4867 if (!IsIgnored)
4868 Diags.popMappings(SavedLoc);
4869 }
4870};
4871}
4872
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004873OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4874 SourceLocation StartLoc,
4875 SourceLocation LParenLoc,
4876 SourceLocation EndLoc) {
4877 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004878 SmallVector<Expr *, 8> PrivateCopies;
4879 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004880 bool IsImplicitClause =
4881 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4882 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4883
Alexey Bataeved09d242014-05-28 05:53:51 +00004884 for (auto &RefExpr : VarList) {
4885 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4886 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004887 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004888 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004889 PrivateCopies.push_back(nullptr);
4890 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004891 continue;
4892 }
4893
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004894 SourceLocation ELoc =
4895 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004896 // OpenMP [2.1, C/C++]
4897 // A list item is a variable name.
4898 // OpenMP [2.9.3.3, Restrictions, p.1]
4899 // A variable that is part of another variable (as an array or
4900 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004901 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004902 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004903 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004904 continue;
4905 }
4906 Decl *D = DE->getDecl();
4907 VarDecl *VD = cast<VarDecl>(D);
4908
4909 QualType Type = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004910 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
4911 Type = PVD->getOriginalType();
4912 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004913 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4914 // It will be analyzed later.
4915 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004916 PrivateCopies.push_back(nullptr);
4917 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004918 continue;
4919 }
4920
4921 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4922 // A variable that appears in a private clause must not have an incomplete
4923 // type or a reference type.
4924 if (RequireCompleteType(ELoc, Type,
4925 diag::err_omp_firstprivate_incomplete_type)) {
4926 continue;
4927 }
4928 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004929 if (IsImplicitClause) {
4930 Diag(ImplicitClauseLoc,
4931 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4932 << Type;
4933 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4934 } else {
4935 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4936 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4937 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004938 bool IsDecl =
4939 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4940 Diag(VD->getLocation(),
4941 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4942 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004943 continue;
4944 }
4945
4946 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4947 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004948 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004949 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004950 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004951
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004952 // If an implicit firstprivate variable found it was checked already.
4953 if (!IsImplicitClause) {
4954 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004955 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004956 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4957 // A list item that specifies a given variable may not appear in more
4958 // than one clause on the same directive, except that a variable may be
4959 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004960 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004961 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004962 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004963 << getOpenMPClauseName(DVar.CKind)
4964 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004965 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004966 continue;
4967 }
4968
4969 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4970 // in a Construct]
4971 // Variables with the predetermined data-sharing attributes may not be
4972 // listed in data-sharing attributes clauses, except for the cases
4973 // listed below. For these exceptions only, listing a predetermined
4974 // variable in a data-sharing attribute clause is allowed and overrides
4975 // the variable's predetermined data-sharing attributes.
4976 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4977 // in a Construct, C/C++, p.2]
4978 // Variables with const-qualified type having no mutable member may be
4979 // listed in a firstprivate clause, even if they are static data members.
4980 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4981 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4982 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004983 << getOpenMPClauseName(DVar.CKind)
4984 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004985 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004986 continue;
4987 }
4988
Alexey Bataevf29276e2014-06-18 04:14:57 +00004989 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004990 // OpenMP [2.9.3.4, Restrictions, p.2]
4991 // A list item that is private within a parallel region must not appear
4992 // in a firstprivate clause on a worksharing construct if any of the
4993 // worksharing regions arising from the worksharing construct ever bind
4994 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004995 if (isOpenMPWorksharingDirective(CurrDir) &&
4996 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004997 DVar = DSAStack->getImplicitDSA(VD, true);
4998 if (DVar.CKind != OMPC_shared &&
4999 (isOpenMPParallelDirective(DVar.DKind) ||
5000 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005001 Diag(ELoc, diag::err_omp_required_access)
5002 << getOpenMPClauseName(OMPC_firstprivate)
5003 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005004 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005005 continue;
5006 }
5007 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005008 // OpenMP [2.9.3.4, Restrictions, p.3]
5009 // A list item that appears in a reduction clause of a parallel construct
5010 // must not appear in a firstprivate clause on a worksharing or task
5011 // construct if any of the worksharing or task regions arising from the
5012 // worksharing or task construct ever bind to any of the parallel regions
5013 // arising from the parallel construct.
5014 // OpenMP [2.9.3.4, Restrictions, p.4]
5015 // A list item that appears in a reduction clause in worksharing
5016 // construct must not appear in a firstprivate clause in a task construct
5017 // encountered during execution of any of the worksharing regions arising
5018 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005019 if (CurrDir == OMPD_task) {
5020 DVar =
5021 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5022 [](OpenMPDirectiveKind K) -> bool {
5023 return isOpenMPParallelDirective(K) ||
5024 isOpenMPWorksharingDirective(K);
5025 },
5026 false);
5027 if (DVar.CKind == OMPC_reduction &&
5028 (isOpenMPParallelDirective(DVar.DKind) ||
5029 isOpenMPWorksharingDirective(DVar.DKind))) {
5030 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5031 << getOpenMPDirectiveName(DVar.DKind);
5032 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5033 continue;
5034 }
5035 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005036 }
5037
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005038 // Variably modified types are not supported for tasks.
5039 if (Type->isVariablyModifiedType() &&
5040 DSAStack->getCurrentDirective() == OMPD_task) {
5041 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5042 << getOpenMPClauseName(OMPC_firstprivate) << Type
5043 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5044 bool IsDecl =
5045 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5046 Diag(VD->getLocation(),
5047 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5048 << VD;
5049 continue;
5050 }
5051
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005052 Type = Type.getUnqualifiedType();
5053 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005054 // Generate helper private variable and initialize it with the value of the
5055 // original variable. The address of the original variable is replaced by
5056 // the address of the new private variable in the CodeGen. This new variable
5057 // is not added to IdResolver, so the code in the OpenMP region uses
5058 // original variable for proper diagnostics and variable capturing.
5059 Expr *VDInitRefExpr = nullptr;
5060 // For arrays generate initializer for single element and replace it by the
5061 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005062 if (Type->isArrayType()) {
5063 auto VDInit =
5064 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5065 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005066 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005067 ElemType = ElemType.getUnqualifiedType();
5068 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5069 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00005070 InitializedEntity Entity =
5071 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005072 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5073
5074 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5075 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5076 if (Result.isInvalid())
5077 VDPrivate->setInvalidDecl();
5078 else
5079 VDPrivate->setInit(Result.getAs<Expr>());
5080 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00005081 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005082 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005083 VDInitRefExpr =
5084 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00005085 AddInitializerToDecl(VDPrivate,
5086 DefaultLvalueConversion(VDInitRefExpr).get(),
5087 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005088 }
5089 if (VDPrivate->isInvalidDecl()) {
5090 if (IsImplicitClause) {
5091 Diag(DE->getExprLoc(),
5092 diag::note_omp_task_predetermined_firstprivate_here);
5093 }
5094 continue;
5095 }
5096 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005097 auto VDPrivateRefExpr = buildDeclRefExpr(
5098 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005099 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5100 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005101 PrivateCopies.push_back(VDPrivateRefExpr);
5102 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005103 }
5104
Alexey Bataeved09d242014-05-28 05:53:51 +00005105 if (Vars.empty())
5106 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005107
5108 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005109 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005110}
5111
Alexander Musman1bb328c2014-06-04 13:06:39 +00005112OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5113 SourceLocation StartLoc,
5114 SourceLocation LParenLoc,
5115 SourceLocation EndLoc) {
5116 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00005117 SmallVector<Expr *, 8> SrcExprs;
5118 SmallVector<Expr *, 8> DstExprs;
5119 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005120 for (auto &RefExpr : VarList) {
5121 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5122 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5123 // It will be analyzed later.
5124 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00005125 SrcExprs.push_back(nullptr);
5126 DstExprs.push_back(nullptr);
5127 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005128 continue;
5129 }
5130
5131 SourceLocation ELoc = RefExpr->getExprLoc();
5132 // OpenMP [2.1, C/C++]
5133 // A list item is a variable name.
5134 // OpenMP [2.14.3.5, Restrictions, p.1]
5135 // A variable that is part of another variable (as an array or structure
5136 // element) cannot appear in a lastprivate clause.
5137 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5138 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5139 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5140 continue;
5141 }
5142 Decl *D = DE->getDecl();
5143 VarDecl *VD = cast<VarDecl>(D);
5144
5145 QualType Type = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005146 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
5147 Type = PVD->getOriginalType();
5148 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005149 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5150 // It will be analyzed later.
5151 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005152 SrcExprs.push_back(nullptr);
5153 DstExprs.push_back(nullptr);
5154 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005155 continue;
5156 }
5157
5158 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5159 // A variable that appears in a lastprivate clause must not have an
5160 // incomplete type or a reference type.
5161 if (RequireCompleteType(ELoc, Type,
5162 diag::err_omp_lastprivate_incomplete_type)) {
5163 continue;
5164 }
5165 if (Type->isReferenceType()) {
5166 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5167 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5168 bool IsDecl =
5169 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5170 Diag(VD->getLocation(),
5171 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5172 << VD;
5173 continue;
5174 }
5175
5176 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5177 // in a Construct]
5178 // Variables with the predetermined data-sharing attributes may not be
5179 // listed in data-sharing attributes clauses, except for the cases
5180 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005181 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005182 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5183 DVar.CKind != OMPC_firstprivate &&
5184 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5185 Diag(ELoc, diag::err_omp_wrong_dsa)
5186 << getOpenMPClauseName(DVar.CKind)
5187 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005188 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005189 continue;
5190 }
5191
Alexey Bataevf29276e2014-06-18 04:14:57 +00005192 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5193 // OpenMP [2.14.3.5, Restrictions, p.2]
5194 // A list item that is private within a parallel region, or that appears in
5195 // the reduction clause of a parallel construct, must not appear in a
5196 // lastprivate clause on a worksharing construct if any of the corresponding
5197 // worksharing regions ever binds to any of the corresponding parallel
5198 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005199 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00005200 if (isOpenMPWorksharingDirective(CurrDir) &&
5201 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005202 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005203 if (DVar.CKind != OMPC_shared) {
5204 Diag(ELoc, diag::err_omp_required_access)
5205 << getOpenMPClauseName(OMPC_lastprivate)
5206 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005207 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005208 continue;
5209 }
5210 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005211 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005212 // A variable of class type (or array thereof) that appears in a
5213 // lastprivate clause requires an accessible, unambiguous default
5214 // constructor for the class type, unless the list item is also specified
5215 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005216 // A variable of class type (or array thereof) that appears in a
5217 // lastprivate clause requires an accessible, unambiguous copy assignment
5218 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005219 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005220 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev38e89532015-04-16 04:54:05 +00005221 Type.getUnqualifiedType(), ".lastprivate.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00005222 auto *PseudoSrcExpr = buildDeclRefExpr(
5223 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005224 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005225 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
Alexey Bataev38e89532015-04-16 04:54:05 +00005226 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005227 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005228 // For arrays generate assignment operation for single element and replace
5229 // it by the original array element in CodeGen.
5230 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5231 PseudoDstExpr, PseudoSrcExpr);
5232 if (AssignmentOp.isInvalid())
5233 continue;
5234 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5235 /*DiscardedValue=*/true);
5236 if (AssignmentOp.isInvalid())
5237 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005238
Alexey Bataev39f915b82015-05-08 10:41:21 +00005239 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005240 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005241 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005242 SrcExprs.push_back(PseudoSrcExpr);
5243 DstExprs.push_back(PseudoDstExpr);
5244 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005245 }
5246
5247 if (Vars.empty())
5248 return nullptr;
5249
5250 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005251 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005252}
5253
Alexey Bataev758e55e2013-09-06 18:03:48 +00005254OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5255 SourceLocation StartLoc,
5256 SourceLocation LParenLoc,
5257 SourceLocation EndLoc) {
5258 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005259 for (auto &RefExpr : VarList) {
5260 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5261 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005262 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005263 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005264 continue;
5265 }
5266
Alexey Bataeved09d242014-05-28 05:53:51 +00005267 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005268 // OpenMP [2.1, C/C++]
5269 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005270 // OpenMP [2.14.3.2, Restrictions, p.1]
5271 // A variable that is part of another variable (as an array or structure
5272 // element) cannot appear in a shared unless it is a static data member
5273 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005274 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005275 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005276 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005277 continue;
5278 }
5279 Decl *D = DE->getDecl();
5280 VarDecl *VD = cast<VarDecl>(D);
5281
5282 QualType Type = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005283 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
5284 Type = PVD->getOriginalType();
5285 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00005286 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5287 // It will be analyzed later.
5288 Vars.push_back(DE);
5289 continue;
5290 }
5291
5292 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5293 // in a Construct]
5294 // Variables with the predetermined data-sharing attributes may not be
5295 // listed in data-sharing attributes clauses, except for the cases
5296 // listed below. For these exceptions only, listing a predetermined
5297 // variable in a data-sharing attribute clause is allowed and overrides
5298 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005299 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005300 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5301 DVar.RefExpr) {
5302 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5303 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005304 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005305 continue;
5306 }
5307
5308 DSAStack->addDSA(VD, DE, OMPC_shared);
5309 Vars.push_back(DE);
5310 }
5311
Alexey Bataeved09d242014-05-28 05:53:51 +00005312 if (Vars.empty())
5313 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005314
5315 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5316}
5317
Alexey Bataevc5e02582014-06-16 07:08:35 +00005318namespace {
5319class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5320 DSAStackTy *Stack;
5321
5322public:
5323 bool VisitDeclRefExpr(DeclRefExpr *E) {
5324 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005325 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005326 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5327 return false;
5328 if (DVar.CKind != OMPC_unknown)
5329 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005330 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005331 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005332 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005333 return true;
5334 return false;
5335 }
5336 return false;
5337 }
5338 bool VisitStmt(Stmt *S) {
5339 for (auto Child : S->children()) {
5340 if (Child && Visit(Child))
5341 return true;
5342 }
5343 return false;
5344 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005345 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005346};
Alexey Bataev23b69422014-06-18 07:08:49 +00005347} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005348
5349OMPClause *Sema::ActOnOpenMPReductionClause(
5350 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5351 SourceLocation ColonLoc, SourceLocation EndLoc,
5352 CXXScopeSpec &ReductionIdScopeSpec,
5353 const DeclarationNameInfo &ReductionId) {
5354 // TODO: Allow scope specification search when 'declare reduction' is
5355 // supported.
5356 assert(ReductionIdScopeSpec.isEmpty() &&
5357 "No support for scoped reduction identifiers yet.");
5358
5359 auto DN = ReductionId.getName();
5360 auto OOK = DN.getCXXOverloadedOperator();
5361 BinaryOperatorKind BOK = BO_Comma;
5362
5363 // OpenMP [2.14.3.6, reduction clause]
5364 // C
5365 // reduction-identifier is either an identifier or one of the following
5366 // operators: +, -, *, &, |, ^, && and ||
5367 // C++
5368 // reduction-identifier is either an id-expression or one of the following
5369 // operators: +, -, *, &, |, ^, && and ||
5370 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5371 switch (OOK) {
5372 case OO_Plus:
5373 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005374 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005375 break;
5376 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005377 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005378 break;
5379 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005380 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005381 break;
5382 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005383 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005384 break;
5385 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005386 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005387 break;
5388 case OO_AmpAmp:
5389 BOK = BO_LAnd;
5390 break;
5391 case OO_PipePipe:
5392 BOK = BO_LOr;
5393 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005394 case OO_New:
5395 case OO_Delete:
5396 case OO_Array_New:
5397 case OO_Array_Delete:
5398 case OO_Slash:
5399 case OO_Percent:
5400 case OO_Tilde:
5401 case OO_Exclaim:
5402 case OO_Equal:
5403 case OO_Less:
5404 case OO_Greater:
5405 case OO_LessEqual:
5406 case OO_GreaterEqual:
5407 case OO_PlusEqual:
5408 case OO_MinusEqual:
5409 case OO_StarEqual:
5410 case OO_SlashEqual:
5411 case OO_PercentEqual:
5412 case OO_CaretEqual:
5413 case OO_AmpEqual:
5414 case OO_PipeEqual:
5415 case OO_LessLess:
5416 case OO_GreaterGreater:
5417 case OO_LessLessEqual:
5418 case OO_GreaterGreaterEqual:
5419 case OO_EqualEqual:
5420 case OO_ExclaimEqual:
5421 case OO_PlusPlus:
5422 case OO_MinusMinus:
5423 case OO_Comma:
5424 case OO_ArrowStar:
5425 case OO_Arrow:
5426 case OO_Call:
5427 case OO_Subscript:
5428 case OO_Conditional:
5429 case NUM_OVERLOADED_OPERATORS:
5430 llvm_unreachable("Unexpected reduction identifier");
5431 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005432 if (auto II = DN.getAsIdentifierInfo()) {
5433 if (II->isStr("max"))
5434 BOK = BO_GT;
5435 else if (II->isStr("min"))
5436 BOK = BO_LT;
5437 }
5438 break;
5439 }
5440 SourceRange ReductionIdRange;
5441 if (ReductionIdScopeSpec.isValid()) {
5442 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5443 }
5444 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5445 if (BOK == BO_Comma) {
5446 // Not allowed reduction identifier is found.
5447 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5448 << ReductionIdRange;
5449 return nullptr;
5450 }
5451
5452 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005453 SmallVector<Expr *, 8> LHSs;
5454 SmallVector<Expr *, 8> RHSs;
5455 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005456 for (auto RefExpr : VarList) {
5457 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5458 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5459 // It will be analyzed later.
5460 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005461 LHSs.push_back(nullptr);
5462 RHSs.push_back(nullptr);
5463 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005464 continue;
5465 }
5466
5467 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5468 RefExpr->isInstantiationDependent() ||
5469 RefExpr->containsUnexpandedParameterPack()) {
5470 // It will be analyzed later.
5471 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005472 LHSs.push_back(nullptr);
5473 RHSs.push_back(nullptr);
5474 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005475 continue;
5476 }
5477
5478 auto ELoc = RefExpr->getExprLoc();
5479 auto ERange = RefExpr->getSourceRange();
5480 // OpenMP [2.1, C/C++]
5481 // A list item is a variable or array section, subject to the restrictions
5482 // specified in Section 2.4 on page 42 and in each of the sections
5483 // describing clauses and directives for which a list appears.
5484 // OpenMP [2.14.3.3, Restrictions, p.1]
5485 // A variable that is part of another variable (as an array or
5486 // structure element) cannot appear in a private clause.
5487 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5488 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5489 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5490 continue;
5491 }
5492 auto D = DE->getDecl();
5493 auto VD = cast<VarDecl>(D);
5494 auto Type = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005495 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
5496 Type = PVD->getOriginalType();
5497 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005498 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5499 // A variable that appears in a private clause must not have an incomplete
5500 // type or a reference type.
5501 if (RequireCompleteType(ELoc, Type,
5502 diag::err_omp_reduction_incomplete_type))
5503 continue;
5504 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5505 // Arrays may not appear in a reduction clause.
5506 if (Type.getNonReferenceType()->isArrayType()) {
5507 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5508 bool IsDecl =
5509 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5510 Diag(VD->getLocation(),
5511 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5512 << VD;
5513 continue;
5514 }
5515 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5516 // A list item that appears in a reduction clause must not be
5517 // const-qualified.
5518 if (Type.getNonReferenceType().isConstant(Context)) {
5519 Diag(ELoc, diag::err_omp_const_variable)
5520 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5521 bool IsDecl =
5522 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5523 Diag(VD->getLocation(),
5524 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5525 << VD;
5526 continue;
5527 }
5528 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5529 // If a list-item is a reference type then it must bind to the same object
5530 // for all threads of the team.
5531 VarDecl *VDDef = VD->getDefinition();
5532 if (Type->isReferenceType() && VDDef) {
5533 DSARefChecker Check(DSAStack);
5534 if (Check.Visit(VDDef->getInit())) {
5535 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5536 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5537 continue;
5538 }
5539 }
5540 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5541 // The type of a list item that appears in a reduction clause must be valid
5542 // for the reduction-identifier. For a max or min reduction in C, the type
5543 // of the list item must be an allowed arithmetic data type: char, int,
5544 // float, double, or _Bool, possibly modified with long, short, signed, or
5545 // unsigned. For a max or min reduction in C++, the type of the list item
5546 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5547 // double, or bool, possibly modified with long, short, signed, or unsigned.
5548 if ((BOK == BO_GT || BOK == BO_LT) &&
5549 !(Type->isScalarType() ||
5550 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5551 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5552 << getLangOpts().CPlusPlus;
5553 bool IsDecl =
5554 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5555 Diag(VD->getLocation(),
5556 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5557 << VD;
5558 continue;
5559 }
5560 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5561 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5562 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5563 bool IsDecl =
5564 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5565 Diag(VD->getLocation(),
5566 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5567 << VD;
5568 continue;
5569 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005570 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5571 // in a Construct]
5572 // Variables with the predetermined data-sharing attributes may not be
5573 // listed in data-sharing attributes clauses, except for the cases
5574 // listed below. For these exceptions only, listing a predetermined
5575 // variable in a data-sharing attribute clause is allowed and overrides
5576 // the variable's predetermined data-sharing attributes.
5577 // OpenMP [2.14.3.6, Restrictions, p.3]
5578 // Any number of reduction clauses can be specified on the directive,
5579 // but a list item can appear only once in the reduction clauses for that
5580 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005581 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005582 if (DVar.CKind == OMPC_reduction) {
5583 Diag(ELoc, diag::err_omp_once_referenced)
5584 << getOpenMPClauseName(OMPC_reduction);
5585 if (DVar.RefExpr) {
5586 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5587 }
5588 } else if (DVar.CKind != OMPC_unknown) {
5589 Diag(ELoc, diag::err_omp_wrong_dsa)
5590 << getOpenMPClauseName(DVar.CKind)
5591 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005592 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005593 continue;
5594 }
5595
5596 // OpenMP [2.14.3.6, Restrictions, p.1]
5597 // A list item that appears in a reduction clause of a worksharing
5598 // construct must be shared in the parallel regions to which any of the
5599 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005600 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005601 if (isOpenMPWorksharingDirective(CurrDir) &&
5602 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005603 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005604 if (DVar.CKind != OMPC_shared) {
5605 Diag(ELoc, diag::err_omp_required_access)
5606 << getOpenMPClauseName(OMPC_reduction)
5607 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005608 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005609 continue;
5610 }
5611 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005612 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005613 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5614 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005615 // Add initializer for private variable.
5616 Expr *Init = nullptr;
5617 switch (BOK) {
5618 case BO_Add:
5619 case BO_Xor:
5620 case BO_Or:
5621 case BO_LOr:
5622 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5623 if (Type->isScalarType() || Type->isAnyComplexType()) {
5624 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005625 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005626 break;
5627 case BO_Mul:
5628 case BO_LAnd:
5629 if (Type->isScalarType() || Type->isAnyComplexType()) {
5630 // '*' and '&&' reduction ops - initializer is '1'.
5631 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5632 }
5633 break;
5634 case BO_And: {
5635 // '&' reduction op - initializer is '~0'.
5636 QualType OrigType = Type;
5637 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5638 Type = ComplexTy->getElementType();
5639 }
5640 if (Type->isRealFloatingType()) {
5641 llvm::APFloat InitValue =
5642 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5643 /*isIEEE=*/true);
5644 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5645 Type, ELoc);
5646 } else if (Type->isScalarType()) {
5647 auto Size = Context.getTypeSize(Type);
5648 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5649 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5650 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5651 }
5652 if (Init && OrigType->isAnyComplexType()) {
5653 // Init = 0xFFFF + 0xFFFFi;
5654 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5655 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5656 }
5657 Type = OrigType;
5658 break;
5659 }
5660 case BO_LT:
5661 case BO_GT: {
5662 // 'min' reduction op - initializer is 'Largest representable number in
5663 // the reduction list item type'.
5664 // 'max' reduction op - initializer is 'Least representable number in
5665 // the reduction list item type'.
5666 if (Type->isIntegerType() || Type->isPointerType()) {
5667 bool IsSigned = Type->hasSignedIntegerRepresentation();
5668 auto Size = Context.getTypeSize(Type);
5669 QualType IntTy =
5670 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5671 llvm::APInt InitValue =
5672 (BOK != BO_LT)
5673 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5674 : llvm::APInt::getMinValue(Size)
5675 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5676 : llvm::APInt::getMaxValue(Size);
5677 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5678 if (Type->isPointerType()) {
5679 // Cast to pointer type.
5680 auto CastExpr = BuildCStyleCastExpr(
5681 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5682 SourceLocation(), Init);
5683 if (CastExpr.isInvalid())
5684 continue;
5685 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005686 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005687 } else if (Type->isRealFloatingType()) {
5688 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5689 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5690 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5691 Type, ELoc);
5692 }
5693 break;
5694 }
5695 case BO_PtrMemD:
5696 case BO_PtrMemI:
5697 case BO_MulAssign:
5698 case BO_Div:
5699 case BO_Rem:
5700 case BO_Sub:
5701 case BO_Shl:
5702 case BO_Shr:
5703 case BO_LE:
5704 case BO_GE:
5705 case BO_EQ:
5706 case BO_NE:
5707 case BO_AndAssign:
5708 case BO_XorAssign:
5709 case BO_OrAssign:
5710 case BO_Assign:
5711 case BO_AddAssign:
5712 case BO_SubAssign:
5713 case BO_DivAssign:
5714 case BO_RemAssign:
5715 case BO_ShlAssign:
5716 case BO_ShrAssign:
5717 case BO_Comma:
5718 llvm_unreachable("Unexpected reduction operation");
5719 }
5720 if (Init) {
5721 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5722 /*TypeMayContainAuto=*/false);
5723 } else {
5724 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5725 }
5726 if (!RHSVD->hasInit()) {
5727 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5728 << ReductionIdRange;
5729 bool IsDecl =
5730 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5731 Diag(VD->getLocation(),
5732 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5733 << VD;
5734 continue;
5735 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00005736 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5737 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005738 ExprResult ReductionOp =
5739 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5740 LHSDRE, RHSDRE);
5741 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00005742 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005743 ReductionOp =
5744 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5745 BO_Assign, LHSDRE, ReductionOp.get());
5746 } else {
5747 auto *ConditionalOp = new (Context) ConditionalOperator(
5748 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5749 RHSDRE, Type, VK_LValue, OK_Ordinary);
5750 ReductionOp =
5751 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5752 BO_Assign, LHSDRE, ConditionalOp);
5753 }
5754 if (ReductionOp.isUsable()) {
5755 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005756 }
5757 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005758 if (ReductionOp.isInvalid())
5759 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005760
5761 DSAStack->addDSA(VD, DE, OMPC_reduction);
5762 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005763 LHSs.push_back(LHSDRE);
5764 RHSs.push_back(RHSDRE);
5765 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005766 }
5767
5768 if (Vars.empty())
5769 return nullptr;
5770
5771 return OMPReductionClause::Create(
5772 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005773 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5774 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005775}
5776
Alexander Musman8dba6642014-04-22 13:09:42 +00005777OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5778 SourceLocation StartLoc,
5779 SourceLocation LParenLoc,
5780 SourceLocation ColonLoc,
5781 SourceLocation EndLoc) {
5782 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005783 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005784 for (auto &RefExpr : VarList) {
5785 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5786 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005787 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005788 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005789 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005790 continue;
5791 }
5792
5793 // OpenMP [2.14.3.7, linear clause]
5794 // A list item that appears in a linear clause is subject to the private
5795 // clause semantics described in Section 2.14.3.3 on page 159 except as
5796 // noted. In addition, the value of the new list item on each iteration
5797 // of the associated loop(s) corresponds to the value of the original
5798 // list item before entering the construct plus the logical number of
5799 // the iteration times linear-step.
5800
Alexey Bataeved09d242014-05-28 05:53:51 +00005801 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005802 // OpenMP [2.1, C/C++]
5803 // A list item is a variable name.
5804 // OpenMP [2.14.3.3, Restrictions, p.1]
5805 // A variable that is part of another variable (as an array or
5806 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005807 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005808 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005809 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005810 continue;
5811 }
5812
5813 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5814
5815 // OpenMP [2.14.3.7, linear clause]
5816 // A list-item cannot appear in more than one linear clause.
5817 // A list-item that appears in a linear clause cannot appear in any
5818 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005819 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005820 if (DVar.RefExpr) {
5821 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5822 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005823 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005824 continue;
5825 }
5826
5827 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005828 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
5829 QType = PVD->getOriginalType();
5830 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005831 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5832 // It will be analyzed later.
5833 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005834 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005835 continue;
5836 }
5837
5838 // A variable must not have an incomplete type or a reference type.
5839 if (RequireCompleteType(ELoc, QType,
5840 diag::err_omp_linear_incomplete_type)) {
5841 continue;
5842 }
5843 if (QType->isReferenceType()) {
5844 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5845 << getOpenMPClauseName(OMPC_linear) << QType;
5846 bool IsDecl =
5847 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5848 Diag(VD->getLocation(),
5849 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5850 << VD;
5851 continue;
5852 }
5853
5854 // A list item must not be const-qualified.
5855 if (QType.isConstant(Context)) {
5856 Diag(ELoc, diag::err_omp_const_variable)
5857 << getOpenMPClauseName(OMPC_linear);
5858 bool IsDecl =
5859 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5860 Diag(VD->getLocation(),
5861 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5862 << VD;
5863 continue;
5864 }
5865
5866 // A list item must be of integral or pointer type.
5867 QType = QType.getUnqualifiedType().getCanonicalType();
5868 const Type *Ty = QType.getTypePtrOrNull();
5869 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5870 !Ty->isPointerType())) {
5871 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5872 bool IsDecl =
5873 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5874 Diag(VD->getLocation(),
5875 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5876 << VD;
5877 continue;
5878 }
5879
Alexander Musman3276a272015-03-21 10:12:56 +00005880 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005881 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexander Musman3276a272015-03-21 10:12:56 +00005882 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5883 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005884 auto InitRef = buildDeclRefExpr(
5885 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00005886 DSAStack->addDSA(VD, DE, OMPC_linear);
5887 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005888 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005889 }
5890
5891 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005892 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005893
5894 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005895 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005896 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5897 !Step->isInstantiationDependent() &&
5898 !Step->containsUnexpandedParameterPack()) {
5899 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005900 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005901 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005902 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005903 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005904
Alexander Musman3276a272015-03-21 10:12:56 +00005905 // Build var to save the step value.
5906 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005907 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00005908 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005909 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00005910 ExprResult CalcStep =
5911 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5912
Alexander Musman8dba6642014-04-22 13:09:42 +00005913 // Warn about zero linear step (it would be probably better specified as
5914 // making corresponding variables 'const').
5915 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005916 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5917 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005918 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5919 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005920 if (!IsConstant && CalcStep.isUsable()) {
5921 // Calculate the step beforehand instead of doing this on each iteration.
5922 // (This is not used if the number of iterations may be kfold-ed).
5923 CalcStepExpr = CalcStep.get();
5924 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005925 }
5926
5927 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005928 Vars, Inits, StepExpr, CalcStepExpr);
5929}
5930
5931static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5932 Expr *NumIterations, Sema &SemaRef,
5933 Scope *S) {
5934 // Walk the vars and build update/final expressions for the CodeGen.
5935 SmallVector<Expr *, 8> Updates;
5936 SmallVector<Expr *, 8> Finals;
5937 Expr *Step = Clause.getStep();
5938 Expr *CalcStep = Clause.getCalcStep();
5939 // OpenMP [2.14.3.7, linear clause]
5940 // If linear-step is not specified it is assumed to be 1.
5941 if (Step == nullptr)
5942 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5943 else if (CalcStep)
5944 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5945 bool HasErrors = false;
5946 auto CurInit = Clause.inits().begin();
5947 for (auto &RefExpr : Clause.varlists()) {
5948 Expr *InitExpr = *CurInit;
5949
5950 // Build privatized reference to the current linear var.
5951 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005952 auto PrivateRef =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005953 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
5954 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
5955 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00005956
5957 // Build update: Var = InitExpr + IV * Step
5958 ExprResult Update =
5959 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5960 InitExpr, IV, Step, /* Subtract */ false);
5961 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5962
5963 // Build final: Var = InitExpr + NumIterations * Step
5964 ExprResult Final =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005965 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5966 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexander Musman3276a272015-03-21 10:12:56 +00005967 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5968 if (!Update.isUsable() || !Final.isUsable()) {
5969 Updates.push_back(nullptr);
5970 Finals.push_back(nullptr);
5971 HasErrors = true;
5972 } else {
5973 Updates.push_back(Update.get());
5974 Finals.push_back(Final.get());
5975 }
5976 ++CurInit;
5977 }
5978 Clause.setUpdates(Updates);
5979 Clause.setFinals(Finals);
5980 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005981}
5982
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005983OMPClause *Sema::ActOnOpenMPAlignedClause(
5984 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5985 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5986
5987 SmallVector<Expr *, 8> Vars;
5988 for (auto &RefExpr : VarList) {
5989 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5990 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5991 // It will be analyzed later.
5992 Vars.push_back(RefExpr);
5993 continue;
5994 }
5995
5996 SourceLocation ELoc = RefExpr->getExprLoc();
5997 // OpenMP [2.1, C/C++]
5998 // A list item is a variable name.
5999 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6000 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6001 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6002 continue;
6003 }
6004
6005 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6006
6007 // OpenMP [2.8.1, simd construct, Restrictions]
6008 // The type of list items appearing in the aligned clause must be
6009 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006010 QualType QType = VD->getType();
6011 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
6012 QType = PVD->getOriginalType();
6013 }
6014 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006015 const Type *Ty = QType.getTypePtrOrNull();
6016 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6017 !Ty->isPointerType())) {
6018 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6019 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6020 bool IsDecl =
6021 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6022 Diag(VD->getLocation(),
6023 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6024 << VD;
6025 continue;
6026 }
6027
6028 // OpenMP [2.8.1, simd construct, Restrictions]
6029 // A list-item cannot appear in more than one aligned clause.
6030 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6031 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6032 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6033 << getOpenMPClauseName(OMPC_aligned);
6034 continue;
6035 }
6036
6037 Vars.push_back(DE);
6038 }
6039
6040 // OpenMP [2.8.1, simd construct, Description]
6041 // The parameter of the aligned clause, alignment, must be a constant
6042 // positive integer expression.
6043 // If no optional parameter is specified, implementation-defined default
6044 // alignments for SIMD instructions on the target platforms are assumed.
6045 if (Alignment != nullptr) {
6046 ExprResult AlignResult =
6047 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6048 if (AlignResult.isInvalid())
6049 return nullptr;
6050 Alignment = AlignResult.get();
6051 }
6052 if (Vars.empty())
6053 return nullptr;
6054
6055 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6056 EndLoc, Vars, Alignment);
6057}
6058
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006059OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6060 SourceLocation StartLoc,
6061 SourceLocation LParenLoc,
6062 SourceLocation EndLoc) {
6063 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006064 SmallVector<Expr *, 8> SrcExprs;
6065 SmallVector<Expr *, 8> DstExprs;
6066 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00006067 for (auto &RefExpr : VarList) {
6068 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6069 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006070 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006071 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006072 SrcExprs.push_back(nullptr);
6073 DstExprs.push_back(nullptr);
6074 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006075 continue;
6076 }
6077
Alexey Bataeved09d242014-05-28 05:53:51 +00006078 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006079 // OpenMP [2.1, C/C++]
6080 // A list item is a variable name.
6081 // OpenMP [2.14.4.1, Restrictions, p.1]
6082 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00006083 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006084 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006085 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006086 continue;
6087 }
6088
6089 Decl *D = DE->getDecl();
6090 VarDecl *VD = cast<VarDecl>(D);
6091
6092 QualType Type = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006093 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
6094 Type = PVD->getOriginalType();
6095 }
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006096 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6097 // It will be analyzed later.
6098 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006099 SrcExprs.push_back(nullptr);
6100 DstExprs.push_back(nullptr);
6101 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006102 continue;
6103 }
6104
6105 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6106 // A list item that appears in a copyin clause must be threadprivate.
6107 if (!DSAStack->isThreadPrivate(VD)) {
6108 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00006109 << getOpenMPClauseName(OMPC_copyin)
6110 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006111 continue;
6112 }
6113
6114 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6115 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00006116 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006117 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006118 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006119 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006120 ElemType.getUnqualifiedType(), ".copyin.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00006121 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006122 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6123 auto *DstVD =
6124 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006125 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006126 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006127 // For arrays generate assignment operation for single element and replace
6128 // it by the original array element in CodeGen.
6129 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6130 PseudoDstExpr, PseudoSrcExpr);
6131 if (AssignmentOp.isInvalid())
6132 continue;
6133 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6134 /*DiscardedValue=*/true);
6135 if (AssignmentOp.isInvalid())
6136 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006137
6138 DSAStack->addDSA(VD, DE, OMPC_copyin);
6139 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006140 SrcExprs.push_back(PseudoSrcExpr);
6141 DstExprs.push_back(PseudoDstExpr);
6142 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006143 }
6144
Alexey Bataeved09d242014-05-28 05:53:51 +00006145 if (Vars.empty())
6146 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006147
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006148 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6149 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006150}
6151
Alexey Bataevbae9a792014-06-27 10:37:06 +00006152OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6153 SourceLocation StartLoc,
6154 SourceLocation LParenLoc,
6155 SourceLocation EndLoc) {
6156 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006157 SmallVector<Expr *, 8> SrcExprs;
6158 SmallVector<Expr *, 8> DstExprs;
6159 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006160 for (auto &RefExpr : VarList) {
6161 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6162 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6163 // It will be analyzed later.
6164 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006165 SrcExprs.push_back(nullptr);
6166 DstExprs.push_back(nullptr);
6167 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006168 continue;
6169 }
6170
6171 SourceLocation ELoc = RefExpr->getExprLoc();
6172 // OpenMP [2.1, C/C++]
6173 // A list item is a variable name.
6174 // OpenMP [2.14.4.1, Restrictions, p.1]
6175 // A list item that appears in a copyin clause must be threadprivate.
6176 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6177 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6178 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6179 continue;
6180 }
6181
6182 Decl *D = DE->getDecl();
6183 VarDecl *VD = cast<VarDecl>(D);
6184
6185 QualType Type = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006186 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
6187 Type = PVD->getOriginalType();
6188 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00006189 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6190 // It will be analyzed later.
6191 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006192 SrcExprs.push_back(nullptr);
6193 DstExprs.push_back(nullptr);
6194 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006195 continue;
6196 }
6197
6198 // OpenMP [2.14.4.2, Restrictions, p.2]
6199 // A list item that appears in a copyprivate clause may not appear in a
6200 // private or firstprivate clause on the single construct.
6201 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006202 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006203 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6204 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006205 Diag(ELoc, diag::err_omp_wrong_dsa)
6206 << getOpenMPClauseName(DVar.CKind)
6207 << getOpenMPClauseName(OMPC_copyprivate);
6208 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6209 continue;
6210 }
6211
6212 // OpenMP [2.11.4.2, Restrictions, p.1]
6213 // All list items that appear in a copyprivate clause must be either
6214 // threadprivate or private in the enclosing context.
6215 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006216 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006217 if (DVar.CKind == OMPC_shared) {
6218 Diag(ELoc, diag::err_omp_required_access)
6219 << getOpenMPClauseName(OMPC_copyprivate)
6220 << "threadprivate or private in the enclosing context";
6221 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6222 continue;
6223 }
6224 }
6225 }
6226
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006227 // Variably modified types are not supported.
6228 if (Type->isVariablyModifiedType()) {
6229 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006230 << getOpenMPClauseName(OMPC_copyprivate) << Type
6231 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006232 bool IsDecl =
6233 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6234 Diag(VD->getLocation(),
6235 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6236 << VD;
6237 continue;
6238 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006239
Alexey Bataevbae9a792014-06-27 10:37:06 +00006240 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6241 // A variable of class type (or array thereof) that appears in a
6242 // copyin clause requires an accessible, unambiguous copy assignment
6243 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006244 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6245 auto *SrcVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006246 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006247 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006248 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00006249 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006250 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006251 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006252 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00006253 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6254 PseudoDstExpr, PseudoSrcExpr);
6255 if (AssignmentOp.isInvalid())
6256 continue;
6257 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6258 /*DiscardedValue=*/true);
6259 if (AssignmentOp.isInvalid())
6260 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006261
6262 // No need to mark vars as copyprivate, they are already threadprivate or
6263 // implicitly private.
6264 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006265 SrcExprs.push_back(PseudoSrcExpr);
6266 DstExprs.push_back(PseudoDstExpr);
6267 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006268 }
6269
6270 if (Vars.empty())
6271 return nullptr;
6272
Alexey Bataeva63048e2015-03-23 06:18:07 +00006273 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6274 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006275}
6276
Alexey Bataev6125da92014-07-21 11:26:11 +00006277OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6278 SourceLocation StartLoc,
6279 SourceLocation LParenLoc,
6280 SourceLocation EndLoc) {
6281 if (VarList.empty())
6282 return nullptr;
6283
6284 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6285}
Alexey Bataevdea47612014-07-23 07:46:59 +00006286