blob: e609fcf1d9bec1b51b34ceb04cb17aff36590d55 [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 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
509 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000510 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
511 // in a Construct, C/C++, predetermined, p.6]
512 // Variables with const qualified type having no mutable member are
513 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000514 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000515 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000516 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000517 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000518 // Variables with const-qualified type having no mutable member may be
519 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000520 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
521 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000522 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
523 return DVar;
524
Alexey Bataev758e55e2013-09-06 18:03:48 +0000525 DVar.CKind = OMPC_shared;
526 return DVar;
527 }
528
Alexey Bataev758e55e2013-09-06 18:03:48 +0000529 // Explicitly specified attributes and local variables with predetermined
530 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000531 auto I = std::prev(StartI);
532 if (I->SharingMap.count(D)) {
533 DVar.RefExpr = I->SharingMap[D].RefExpr;
534 DVar.CKind = I->SharingMap[D].Attributes;
535 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000536 }
537
538 return DVar;
539}
540
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000541DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000542 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000543 auto StartI = Stack.rbegin();
544 auto EndI = std::prev(Stack.rend());
545 if (FromParent && StartI != EndI) {
546 StartI = std::next(StartI);
547 }
548 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000549}
550
Alexey Bataevf29276e2014-06-18 04:14:57 +0000551template <class ClausesPredicate, class DirectivesPredicate>
552DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000553 DirectivesPredicate DPred,
554 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000555 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000556 auto StartI = std::next(Stack.rbegin());
557 auto EndI = std::prev(Stack.rend());
558 if (FromParent && StartI != EndI) {
559 StartI = std::next(StartI);
560 }
561 for (auto I = StartI, EE = EndI; I != EE; ++I) {
562 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000563 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000564 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000565 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000566 return DVar;
567 }
568 return DSAVarData();
569}
570
Alexey Bataevf29276e2014-06-18 04:14:57 +0000571template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000572DSAStackTy::DSAVarData
573DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
574 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000575 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000576 auto StartI = std::next(Stack.rbegin());
577 auto EndI = std::prev(Stack.rend());
578 if (FromParent && StartI != EndI) {
579 StartI = std::next(StartI);
580 }
581 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000582 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000583 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000584 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000585 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000586 return DVar;
587 return DSAVarData();
588 }
589 return DSAVarData();
590}
591
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000592template <class NamedDirectivesPredicate>
593bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
594 auto StartI = std::next(Stack.rbegin());
595 auto EndI = std::prev(Stack.rend());
596 if (FromParent && StartI != EndI) {
597 StartI = std::next(StartI);
598 }
599 for (auto I = StartI, EE = EndI; I != EE; ++I) {
600 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
601 return true;
602 }
603 return false;
604}
605
Alexey Bataev758e55e2013-09-06 18:03:48 +0000606void Sema::InitDataSharingAttributesStack() {
607 VarDataSharingAttributesStack = new DSAStackTy(*this);
608}
609
610#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
611
Alexey Bataevf841bd92014-12-16 07:00:22 +0000612bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
613 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000614 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000615 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000616 if (DSAStack->isLoopControlVariable(VD) ||
617 (VD->hasLocalStorage() &&
618 isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
Alexey Bataev9c821032015-04-30 04:23:23 +0000619 return true;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000620 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000621 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
622 return true;
623 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000624 DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000625 return DVarPrivate.CKind != OMPC_unknown;
626 }
627 return false;
628}
629
Alexey Bataeved09d242014-05-28 05:53:51 +0000630void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000631
632void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
633 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000634 Scope *CurScope, SourceLocation Loc) {
635 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000636 PushExpressionEvaluationContext(PotentiallyEvaluated);
637}
638
Alexey Bataev39f915b82015-05-08 10:41:21 +0000639void Sema::StartOpenMPClauses() {
640 DSAStack->setFromParent(/*Flag=*/true);
641}
642
643void Sema::EndOpenMPClauses() {
644 DSAStack->setFromParent(/*Flag=*/false);
645}
646
Alexey Bataev758e55e2013-09-06 18:03:48 +0000647void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000648 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
649 // A variable of class type (or array thereof) that appears in a lastprivate
650 // clause requires an accessible, unambiguous default constructor for the
651 // class type, unless the list item is also specified in a firstprivate
652 // clause.
653 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000654 for (auto *C : D->clauses()) {
655 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
656 SmallVector<Expr *, 8> PrivateCopies;
657 for (auto *DE : Clause->varlists()) {
658 if (DE->isValueDependent() || DE->isTypeDependent()) {
659 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000660 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000661 }
662 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000663 QualType Type = VD->getType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000664 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000665 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000666 // Generate helper private variable and initialize it with the
667 // default value. The address of the original variable is replaced
668 // by the address of the new private variable in CodeGen. This new
669 // variable is not added to IdResolver, so the code in the OpenMP
670 // region uses original variable for proper diagnostics.
Alexey Bataev39f915b82015-05-08 10:41:21 +0000671 auto *VDPrivate =
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000672 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
673 VD->getName());
Alexey Bataev38e89532015-04-16 04:54:05 +0000674 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
675 if (VDPrivate->isInvalidDecl())
676 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000677 PrivateCopies.push_back(buildDeclRefExpr(
678 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000679 } else {
680 // The variable is also a firstprivate, so initialization sequence
681 // for private copy is generated already.
682 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000683 }
684 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000685 // Set initializers to private copies if no errors were found.
686 if (PrivateCopies.size() == Clause->varlist_size()) {
687 Clause->setPrivateCopies(PrivateCopies);
688 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000689 }
690 }
691 }
692
Alexey Bataev758e55e2013-09-06 18:03:48 +0000693 DSAStack->pop();
694 DiscardCleanupsInEvaluationContext();
695 PopExpressionEvaluationContext();
696}
697
Alexander Musman3276a272015-03-21 10:12:56 +0000698static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
699 Expr *NumIterations, Sema &SemaRef,
700 Scope *S);
701
Alexey Bataeva769e072013-03-22 06:34:35 +0000702namespace {
703
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000704class VarDeclFilterCCC : public CorrectionCandidateCallback {
705private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000706 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000707
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000708public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000709 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000710 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000711 NamedDecl *ND = Candidate.getCorrectionDecl();
712 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
713 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000714 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
715 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000716 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000717 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000718 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000719};
Alexey Bataeved09d242014-05-28 05:53:51 +0000720} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000721
722ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
723 CXXScopeSpec &ScopeSpec,
724 const DeclarationNameInfo &Id) {
725 LookupResult Lookup(*this, Id, LookupOrdinaryName);
726 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
727
728 if (Lookup.isAmbiguous())
729 return ExprError();
730
731 VarDecl *VD;
732 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000733 if (TypoCorrection Corrected = CorrectTypo(
734 Id, LookupOrdinaryName, CurScope, nullptr,
735 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000736 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000737 PDiag(Lookup.empty()
738 ? diag::err_undeclared_var_use_suggest
739 : diag::err_omp_expected_var_arg_suggest)
740 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000741 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000742 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000743 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
744 : diag::err_omp_expected_var_arg)
745 << Id.getName();
746 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000747 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000748 } else {
749 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000750 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000751 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
752 return ExprError();
753 }
754 }
755 Lookup.suppressDiagnostics();
756
757 // OpenMP [2.9.2, Syntax, C/C++]
758 // Variables must be file-scope, namespace-scope, or static block-scope.
759 if (!VD->hasGlobalStorage()) {
760 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000761 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
762 bool IsDecl =
763 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000764 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
766 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000767 return ExprError();
768 }
769
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000770 VarDecl *CanonicalVD = VD->getCanonicalDecl();
771 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000772 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
773 // A threadprivate directive for file-scope variables must appear outside
774 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000775 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
776 !getCurLexicalContext()->isTranslationUnit()) {
777 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000778 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
779 bool IsDecl =
780 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
781 Diag(VD->getLocation(),
782 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
783 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000784 return ExprError();
785 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000786 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
787 // A threadprivate directive for static class member variables must appear
788 // in the class definition, in the same scope in which the member
789 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000790 if (CanonicalVD->isStaticDataMember() &&
791 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
792 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000793 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
794 bool IsDecl =
795 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
796 Diag(VD->getLocation(),
797 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
798 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000799 return ExprError();
800 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000801 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
802 // A threadprivate directive for namespace-scope variables must appear
803 // outside any definition or declaration other than the namespace
804 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000805 if (CanonicalVD->getDeclContext()->isNamespace() &&
806 (!getCurLexicalContext()->isFileContext() ||
807 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
808 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000809 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
810 bool IsDecl =
811 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
812 Diag(VD->getLocation(),
813 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
814 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000815 return ExprError();
816 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000817 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
818 // A threadprivate directive for static block-scope variables must appear
819 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000820 if (CanonicalVD->isStaticLocal() && CurScope &&
821 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000822 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000823 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
824 bool IsDecl =
825 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
826 Diag(VD->getLocation(),
827 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
828 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000829 return ExprError();
830 }
831
832 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
833 // A threadprivate directive must lexically precede all references to any
834 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000835 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000836 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000837 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000838 return ExprError();
839 }
840
841 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +0000842 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000843 return DE;
844}
845
Alexey Bataeved09d242014-05-28 05:53:51 +0000846Sema::DeclGroupPtrTy
847Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
848 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000849 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000850 CurContext->addDecl(D);
851 return DeclGroupPtrTy::make(DeclGroupRef(D));
852 }
853 return DeclGroupPtrTy();
854}
855
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000856namespace {
857class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
858 Sema &SemaRef;
859
860public:
861 bool VisitDeclRefExpr(const DeclRefExpr *E) {
862 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
863 if (VD->hasLocalStorage()) {
864 SemaRef.Diag(E->getLocStart(),
865 diag::err_omp_local_var_in_threadprivate_init)
866 << E->getSourceRange();
867 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
868 << VD << VD->getSourceRange();
869 return true;
870 }
871 }
872 return false;
873 }
874 bool VisitStmt(const Stmt *S) {
875 for (auto Child : S->children()) {
876 if (Child && Visit(Child))
877 return true;
878 }
879 return false;
880 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000881 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000882};
883} // namespace
884
Alexey Bataeved09d242014-05-28 05:53:51 +0000885OMPThreadPrivateDecl *
886Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000887 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000888 for (auto &RefExpr : VarList) {
889 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000890 VarDecl *VD = cast<VarDecl>(DE->getDecl());
891 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000892
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000893 QualType QType = VD->getType();
894 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
895 // It will be analyzed later.
896 Vars.push_back(DE);
897 continue;
898 }
899
Alexey Bataeva769e072013-03-22 06:34:35 +0000900 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
901 // A threadprivate variable must not have an incomplete type.
902 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000903 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000904 continue;
905 }
906
907 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
908 // A threadprivate variable must not have a reference type.
909 if (VD->getType()->isReferenceType()) {
910 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000911 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
912 bool IsDecl =
913 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
914 Diag(VD->getLocation(),
915 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
916 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000917 continue;
918 }
919
Richard Smithfd3834f2013-04-13 02:43:54 +0000920 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000921 if (VD->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000922 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
923 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +0000924 Diag(ILoc, diag::err_omp_var_thread_local)
925 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000926 bool IsDecl =
927 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
928 Diag(VD->getLocation(),
929 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
930 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000931 continue;
932 }
933
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000934 // Check if initial value of threadprivate variable reference variable with
935 // local storage (it is not supported by runtime).
936 if (auto Init = VD->getAnyInitializer()) {
937 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000938 if (Checker.Visit(Init))
939 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000940 }
941
Alexey Bataeved09d242014-05-28 05:53:51 +0000942 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000943 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000944 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
945 Context, SourceRange(Loc, Loc)));
946 if (auto *ML = Context.getASTMutationListener())
947 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000948 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000949 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000950 if (!Vars.empty()) {
951 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
952 Vars);
953 D->setAccess(AS_public);
954 }
955 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000956}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000957
Alexey Bataev7ff55242014-06-19 09:13:45 +0000958static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
959 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
960 bool IsLoopIterVar = false) {
961 if (DVar.RefExpr) {
962 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
963 << getOpenMPClauseName(DVar.CKind);
964 return;
965 }
966 enum {
967 PDSA_StaticMemberShared,
968 PDSA_StaticLocalVarShared,
969 PDSA_LoopIterVarPrivate,
970 PDSA_LoopIterVarLinear,
971 PDSA_LoopIterVarLastprivate,
972 PDSA_ConstVarShared,
973 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000974 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000975 PDSA_LocalVarPrivate,
976 PDSA_Implicit
977 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000978 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000979 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000980 if (IsLoopIterVar) {
981 if (DVar.CKind == OMPC_private)
982 Reason = PDSA_LoopIterVarPrivate;
983 else if (DVar.CKind == OMPC_lastprivate)
984 Reason = PDSA_LoopIterVarLastprivate;
985 else
986 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000987 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
988 Reason = PDSA_TaskVarFirstprivate;
989 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000990 } else if (VD->isStaticLocal())
991 Reason = PDSA_StaticLocalVarShared;
992 else if (VD->isStaticDataMember())
993 Reason = PDSA_StaticMemberShared;
994 else if (VD->isFileVarDecl())
995 Reason = PDSA_GlobalVarShared;
996 else if (VD->getType().isConstant(SemaRef.getASTContext()))
997 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000998 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000999 ReportHint = true;
1000 Reason = PDSA_LocalVarPrivate;
1001 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001002 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001003 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001004 << Reason << ReportHint
1005 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1006 } else if (DVar.ImplicitDSALoc.isValid()) {
1007 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1008 << getOpenMPClauseName(DVar.CKind);
1009 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001010}
1011
Alexey Bataev758e55e2013-09-06 18:03:48 +00001012namespace {
1013class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1014 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001015 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001016 bool ErrorFound;
1017 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001018 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001019 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001020
Alexey Bataev758e55e2013-09-06 18:03:48 +00001021public:
1022 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001023 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001024 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001025 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1026 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001027
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001028 auto DVar = Stack->getTopDSA(VD, false);
1029 // Check if the variable has explicit DSA set and stop analysis if it so.
1030 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001031
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001032 auto ELoc = E->getExprLoc();
1033 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034 // The default(none) clause requires that each variable that is referenced
1035 // in the construct, and does not have a predetermined data-sharing
1036 // attribute, must have its data-sharing attribute explicitly determined
1037 // by being listed in a data-sharing attribute clause.
1038 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001039 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001040 VarsWithInheritedDSA.count(VD) == 0) {
1041 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001042 return;
1043 }
1044
1045 // OpenMP [2.9.3.6, Restrictions, p.2]
1046 // A list item that appears in a reduction clause of the innermost
1047 // enclosing worksharing or parallel construct may not be accessed in an
1048 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001049 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001050 [](OpenMPDirectiveKind K) -> bool {
1051 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001052 isOpenMPWorksharingDirective(K) ||
1053 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001054 },
1055 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001056 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1057 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001058 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1059 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001060 return;
1061 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001062
1063 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001064 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001065 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001066 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001067 }
1068 }
1069 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001070 for (auto *C : S->clauses()) {
1071 // Skip analysis of arguments of implicitly defined firstprivate clause
1072 // for task directives.
1073 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1074 for (auto *CC : C->children()) {
1075 if (CC)
1076 Visit(CC);
1077 }
1078 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001079 }
1080 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001081 for (auto *C : S->children()) {
1082 if (C && !isa<OMPExecutableDirective>(C))
1083 Visit(C);
1084 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001085 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001086
1087 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001088 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001089 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1090 return VarsWithInheritedDSA;
1091 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001092
Alexey Bataev7ff55242014-06-19 09:13:45 +00001093 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1094 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001095};
Alexey Bataeved09d242014-05-28 05:53:51 +00001096} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001097
Alexey Bataevbae9a792014-06-27 10:37:06 +00001098void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001099 switch (DKind) {
1100 case OMPD_parallel: {
1101 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1102 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001103 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001104 std::make_pair(".global_tid.", KmpInt32PtrTy),
1105 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1106 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001107 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001108 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1109 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001110 break;
1111 }
1112 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001113 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001114 std::make_pair(StringRef(), QualType()) // __context with shared vars
1115 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001116 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1117 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001118 break;
1119 }
1120 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001121 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001122 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001123 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001124 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1125 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001126 break;
1127 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001128 case OMPD_for_simd: {
1129 Sema::CapturedParamNameType Params[] = {
1130 std::make_pair(StringRef(), QualType()) // __context with shared vars
1131 };
1132 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1133 Params);
1134 break;
1135 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001136 case OMPD_sections: {
1137 Sema::CapturedParamNameType Params[] = {
1138 std::make_pair(StringRef(), QualType()) // __context with shared vars
1139 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001140 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1141 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001142 break;
1143 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001144 case OMPD_section: {
1145 Sema::CapturedParamNameType Params[] = {
1146 std::make_pair(StringRef(), QualType()) // __context with shared vars
1147 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001148 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1149 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001150 break;
1151 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001152 case OMPD_single: {
1153 Sema::CapturedParamNameType Params[] = {
1154 std::make_pair(StringRef(), QualType()) // __context with shared vars
1155 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001156 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1157 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001158 break;
1159 }
Alexander Musman80c22892014-07-17 08:54:58 +00001160 case OMPD_master: {
1161 Sema::CapturedParamNameType Params[] = {
1162 std::make_pair(StringRef(), QualType()) // __context with shared vars
1163 };
1164 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1165 Params);
1166 break;
1167 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001168 case OMPD_critical: {
1169 Sema::CapturedParamNameType Params[] = {
1170 std::make_pair(StringRef(), QualType()) // __context with shared vars
1171 };
1172 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1173 Params);
1174 break;
1175 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001176 case OMPD_parallel_for: {
1177 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1178 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1179 Sema::CapturedParamNameType Params[] = {
1180 std::make_pair(".global_tid.", KmpInt32PtrTy),
1181 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1182 std::make_pair(StringRef(), QualType()) // __context with shared vars
1183 };
1184 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1185 Params);
1186 break;
1187 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001188 case OMPD_parallel_for_simd: {
1189 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1190 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1191 Sema::CapturedParamNameType Params[] = {
1192 std::make_pair(".global_tid.", KmpInt32PtrTy),
1193 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1194 std::make_pair(StringRef(), QualType()) // __context with shared vars
1195 };
1196 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1197 Params);
1198 break;
1199 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001200 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001201 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1202 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001203 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001204 std::make_pair(".global_tid.", KmpInt32PtrTy),
1205 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001206 std::make_pair(StringRef(), QualType()) // __context with shared vars
1207 };
1208 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1209 Params);
1210 break;
1211 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001212 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001213 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001214 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1215 FunctionProtoType::ExtProtoInfo EPI;
1216 EPI.Variadic = true;
1217 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001218 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001219 std::make_pair(".global_tid.", KmpInt32Ty),
1220 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001221 std::make_pair(".privates.",
1222 Context.VoidPtrTy.withConst().withRestrict()),
1223 std::make_pair(
1224 ".copy_fn.",
1225 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001226 std::make_pair(StringRef(), QualType()) // __context with shared vars
1227 };
1228 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1229 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001230 // Mark this captured region as inlined, because we don't use outlined
1231 // function directly.
1232 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1233 AlwaysInlineAttr::CreateImplicit(
1234 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001235 break;
1236 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001237 case OMPD_ordered: {
1238 Sema::CapturedParamNameType Params[] = {
1239 std::make_pair(StringRef(), QualType()) // __context with shared vars
1240 };
1241 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1242 Params);
1243 break;
1244 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001245 case OMPD_atomic: {
1246 Sema::CapturedParamNameType Params[] = {
1247 std::make_pair(StringRef(), QualType()) // __context with shared vars
1248 };
1249 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1250 Params);
1251 break;
1252 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001253 case OMPD_target: {
1254 Sema::CapturedParamNameType Params[] = {
1255 std::make_pair(StringRef(), QualType()) // __context with shared vars
1256 };
1257 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1258 Params);
1259 break;
1260 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001261 case OMPD_teams: {
1262 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1263 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1264 Sema::CapturedParamNameType Params[] = {
1265 std::make_pair(".global_tid.", KmpInt32PtrTy),
1266 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1267 std::make_pair(StringRef(), QualType()) // __context with shared vars
1268 };
1269 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1270 Params);
1271 break;
1272 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001273 case OMPD_taskgroup: {
1274 Sema::CapturedParamNameType Params[] = {
1275 std::make_pair(StringRef(), QualType()) // __context with shared vars
1276 };
1277 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1278 Params);
1279 break;
1280 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001281 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001282 case OMPD_taskyield:
1283 case OMPD_barrier:
1284 case OMPD_taskwait:
1285 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001286 llvm_unreachable("OpenMP Directive is not allowed");
1287 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001288 llvm_unreachable("Unknown OpenMP directive");
1289 }
1290}
1291
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001292StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1293 ArrayRef<OMPClause *> Clauses) {
1294 if (!S.isUsable()) {
1295 ActOnCapturedRegionError();
1296 return StmtError();
1297 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001298 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001299 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001300 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1301 Clause->getClauseKind() == OMPC_copyprivate) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001302 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001303 for (auto *VarRef : Clause->children()) {
1304 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001305 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001306 }
1307 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001308 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1309 Clause->getClauseKind() == OMPC_schedule) {
1310 // Mark all variables in private list clauses as used in inner region.
1311 // Required for proper codegen of combined directives.
1312 // TODO: add processing for other clauses.
1313 if (auto *E = cast_or_null<Expr>(
1314 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1315 MarkDeclarationsReferencedInExpr(E);
1316 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001317 }
1318 }
1319 return ActOnCapturedRegionEnd(S.get());
1320}
1321
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001322static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1323 OpenMPDirectiveKind CurrentRegion,
1324 const DeclarationNameInfo &CurrentName,
1325 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001326 // Allowed nesting of constructs
1327 // +------------------+-----------------+------------------------------------+
1328 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1329 // +------------------+-----------------+------------------------------------+
1330 // | parallel | parallel | * |
1331 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001332 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001333 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001334 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001335 // | parallel | simd | * |
1336 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001337 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001338 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001339 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001340 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001341 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001342 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001343 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001344 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001345 // | parallel | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001346 // | parallel | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001347 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001348 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001349 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001350 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001351 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001352 // +------------------+-----------------+------------------------------------+
1353 // | for | parallel | * |
1354 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001355 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001356 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001357 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001358 // | for | simd | * |
1359 // | for | sections | + |
1360 // | for | section | + |
1361 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001362 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001363 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001364 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001365 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001366 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001367 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001368 // | for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001369 // | for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001370 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001371 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001372 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001373 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001374 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001375 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001376 // | master | parallel | * |
1377 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001378 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001379 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001380 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001381 // | master | simd | * |
1382 // | master | sections | + |
1383 // | master | section | + |
1384 // | master | single | + |
1385 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001386 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001387 // | master |parallel sections| * |
1388 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001389 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001390 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001391 // | master | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001392 // | master | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001393 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001394 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001395 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001396 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001397 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001398 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001399 // | critical | parallel | * |
1400 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001401 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001402 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001403 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001404 // | critical | simd | * |
1405 // | critical | sections | + |
1406 // | critical | section | + |
1407 // | critical | single | + |
1408 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001409 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001410 // | critical |parallel sections| * |
1411 // | critical | task | * |
1412 // | critical | taskyield | * |
1413 // | critical | barrier | + |
1414 // | critical | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001415 // | critical | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001416 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001417 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001418 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001419 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001420 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001421 // | simd | parallel | |
1422 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001423 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001424 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001425 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001426 // | simd | simd | |
1427 // | simd | sections | |
1428 // | simd | section | |
1429 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001430 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001431 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001432 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001433 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001434 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001435 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001436 // | simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001437 // | simd | taskgroup | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001438 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001439 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001440 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001441 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001442 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001443 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001444 // | for simd | parallel | |
1445 // | for simd | for | |
1446 // | for simd | for simd | |
1447 // | for simd | master | |
1448 // | for simd | critical | |
1449 // | for simd | simd | |
1450 // | for simd | sections | |
1451 // | for simd | section | |
1452 // | for simd | single | |
1453 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001454 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001455 // | for simd |parallel sections| |
1456 // | for simd | task | |
1457 // | for simd | taskyield | |
1458 // | for simd | barrier | |
1459 // | for simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001460 // | for simd | taskgroup | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001461 // | for simd | flush | |
1462 // | for simd | ordered | |
1463 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001464 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001465 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001466 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001467 // | parallel for simd| parallel | |
1468 // | parallel for simd| for | |
1469 // | parallel for simd| for simd | |
1470 // | parallel for simd| master | |
1471 // | parallel for simd| critical | |
1472 // | parallel for simd| simd | |
1473 // | parallel for simd| sections | |
1474 // | parallel for simd| section | |
1475 // | parallel for simd| single | |
1476 // | parallel for simd| parallel for | |
1477 // | parallel for simd|parallel for simd| |
1478 // | parallel for simd|parallel sections| |
1479 // | parallel for simd| task | |
1480 // | parallel for simd| taskyield | |
1481 // | parallel for simd| barrier | |
1482 // | parallel for simd| taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001483 // | parallel for simd| taskgroup | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001484 // | parallel for simd| flush | |
1485 // | parallel for simd| ordered | |
1486 // | parallel for simd| atomic | |
1487 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001488 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001489 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001490 // | sections | parallel | * |
1491 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001492 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001493 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001494 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001495 // | sections | simd | * |
1496 // | sections | sections | + |
1497 // | sections | section | * |
1498 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001499 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001500 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001501 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001502 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001503 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001504 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001505 // | sections | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001506 // | sections | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001507 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001508 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001509 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001510 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001511 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001512 // +------------------+-----------------+------------------------------------+
1513 // | section | parallel | * |
1514 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001515 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001516 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001517 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001518 // | section | simd | * |
1519 // | section | sections | + |
1520 // | section | section | + |
1521 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001522 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001523 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001524 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001525 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001526 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001527 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001528 // | section | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001529 // | section | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001530 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001531 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001532 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001533 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001534 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001535 // +------------------+-----------------+------------------------------------+
1536 // | single | parallel | * |
1537 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001538 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001539 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001540 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001541 // | single | simd | * |
1542 // | single | sections | + |
1543 // | single | section | + |
1544 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001545 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001546 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001547 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001548 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001549 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001550 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001551 // | single | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001552 // | single | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001553 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001554 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001555 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001556 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001557 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001558 // +------------------+-----------------+------------------------------------+
1559 // | parallel for | parallel | * |
1560 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001561 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001562 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001563 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001564 // | parallel for | simd | * |
1565 // | parallel for | sections | + |
1566 // | parallel for | section | + |
1567 // | parallel for | single | + |
1568 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001569 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001570 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001571 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001572 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001573 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001574 // | parallel for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001575 // | parallel for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001576 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001577 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001578 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001579 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001580 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001581 // +------------------+-----------------+------------------------------------+
1582 // | parallel sections| parallel | * |
1583 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001584 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001585 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001586 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001587 // | parallel sections| simd | * |
1588 // | parallel sections| sections | + |
1589 // | parallel sections| section | * |
1590 // | parallel sections| single | + |
1591 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001592 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001593 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001594 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001595 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001596 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001597 // | parallel sections| taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001598 // | parallel sections| taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001599 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001600 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001601 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001602 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001603 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001604 // +------------------+-----------------+------------------------------------+
1605 // | task | parallel | * |
1606 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001607 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001608 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001609 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001610 // | task | simd | * |
1611 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001612 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001613 // | task | single | + |
1614 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001615 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001616 // | task |parallel sections| * |
1617 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001618 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001619 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001620 // | task | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001621 // | task | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001622 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001623 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001624 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001625 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001626 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001627 // +------------------+-----------------+------------------------------------+
1628 // | ordered | parallel | * |
1629 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001630 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001631 // | ordered | master | * |
1632 // | ordered | critical | * |
1633 // | ordered | simd | * |
1634 // | ordered | sections | + |
1635 // | ordered | section | + |
1636 // | ordered | single | + |
1637 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001638 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001639 // | ordered |parallel sections| * |
1640 // | ordered | task | * |
1641 // | ordered | taskyield | * |
1642 // | ordered | barrier | + |
1643 // | ordered | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001644 // | ordered | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001645 // | ordered | flush | * |
1646 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001647 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001648 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001649 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001650 // +------------------+-----------------+------------------------------------+
1651 // | atomic | parallel | |
1652 // | atomic | for | |
1653 // | atomic | for simd | |
1654 // | atomic | master | |
1655 // | atomic | critical | |
1656 // | atomic | simd | |
1657 // | atomic | sections | |
1658 // | atomic | section | |
1659 // | atomic | single | |
1660 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001661 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001662 // | atomic |parallel sections| |
1663 // | atomic | task | |
1664 // | atomic | taskyield | |
1665 // | atomic | barrier | |
1666 // | atomic | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001667 // | atomic | taskgroup | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001668 // | atomic | flush | |
1669 // | atomic | ordered | |
1670 // | atomic | atomic | |
1671 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001672 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001673 // +------------------+-----------------+------------------------------------+
1674 // | target | parallel | * |
1675 // | target | for | * |
1676 // | target | for simd | * |
1677 // | target | master | * |
1678 // | target | critical | * |
1679 // | target | simd | * |
1680 // | target | sections | * |
1681 // | target | section | * |
1682 // | target | single | * |
1683 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001684 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001685 // | target |parallel sections| * |
1686 // | target | task | * |
1687 // | target | taskyield | * |
1688 // | target | barrier | * |
1689 // | target | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001690 // | target | taskgroup | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001691 // | target | flush | * |
1692 // | target | ordered | * |
1693 // | target | atomic | * |
1694 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001695 // | target | teams | * |
1696 // +------------------+-----------------+------------------------------------+
1697 // | teams | parallel | * |
1698 // | teams | for | + |
1699 // | teams | for simd | + |
1700 // | teams | master | + |
1701 // | teams | critical | + |
1702 // | teams | simd | + |
1703 // | teams | sections | + |
1704 // | teams | section | + |
1705 // | teams | single | + |
1706 // | teams | parallel for | * |
1707 // | teams |parallel for simd| * |
1708 // | teams |parallel sections| * |
1709 // | teams | task | + |
1710 // | teams | taskyield | + |
1711 // | teams | barrier | + |
1712 // | teams | taskwait | + |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001713 // | teams | taskgroup | + |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001714 // | teams | flush | + |
1715 // | teams | ordered | + |
1716 // | teams | atomic | + |
1717 // | teams | target | + |
1718 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001719 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001720 if (Stack->getCurScope()) {
1721 auto ParentRegion = Stack->getParentDirective();
1722 bool NestingProhibited = false;
1723 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001724 enum {
1725 NoRecommend,
1726 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001727 ShouldBeInOrderedRegion,
1728 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001729 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001730 if (isOpenMPSimdDirective(ParentRegion)) {
1731 // OpenMP [2.16, Nesting of Regions]
1732 // OpenMP constructs may not be nested inside a simd region.
1733 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1734 return true;
1735 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001736 if (ParentRegion == OMPD_atomic) {
1737 // OpenMP [2.16, Nesting of Regions]
1738 // OpenMP constructs may not be nested inside an atomic region.
1739 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1740 return true;
1741 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001742 if (CurrentRegion == OMPD_section) {
1743 // OpenMP [2.7.2, sections Construct, Restrictions]
1744 // Orphaned section directives are prohibited. That is, the section
1745 // directives must appear within the sections construct and must not be
1746 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001747 if (ParentRegion != OMPD_sections &&
1748 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001749 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1750 << (ParentRegion != OMPD_unknown)
1751 << getOpenMPDirectiveName(ParentRegion);
1752 return true;
1753 }
1754 return false;
1755 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001756 // Allow some constructs to be orphaned (they could be used in functions,
1757 // called from OpenMP regions with the required preconditions).
1758 if (ParentRegion == OMPD_unknown)
1759 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001760 if (CurrentRegion == OMPD_master) {
1761 // OpenMP [2.16, Nesting of Regions]
1762 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001763 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001764 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1765 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001766 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1767 // OpenMP [2.16, Nesting of Regions]
1768 // A critical region may not be nested (closely or otherwise) inside a
1769 // critical region with the same name. Note that this restriction is not
1770 // sufficient to prevent deadlock.
1771 SourceLocation PreviousCriticalLoc;
1772 bool DeadLock =
1773 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1774 OpenMPDirectiveKind K,
1775 const DeclarationNameInfo &DNI,
1776 SourceLocation Loc)
1777 ->bool {
1778 if (K == OMPD_critical &&
1779 DNI.getName() == CurrentName.getName()) {
1780 PreviousCriticalLoc = Loc;
1781 return true;
1782 } else
1783 return false;
1784 },
1785 false /* skip top directive */);
1786 if (DeadLock) {
1787 SemaRef.Diag(StartLoc,
1788 diag::err_omp_prohibited_region_critical_same_name)
1789 << CurrentName.getName();
1790 if (PreviousCriticalLoc.isValid())
1791 SemaRef.Diag(PreviousCriticalLoc,
1792 diag::note_omp_previous_critical_region);
1793 return true;
1794 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001795 } else if (CurrentRegion == OMPD_barrier) {
1796 // OpenMP [2.16, Nesting of Regions]
1797 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001798 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001799 NestingProhibited =
1800 isOpenMPWorksharingDirective(ParentRegion) ||
1801 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1802 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001803 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001804 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001805 // OpenMP [2.16, Nesting of Regions]
1806 // A worksharing region may not be closely nested inside a worksharing,
1807 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001808 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001809 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001810 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1811 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1812 Recommend = ShouldBeInParallelRegion;
1813 } else if (CurrentRegion == OMPD_ordered) {
1814 // OpenMP [2.16, Nesting of Regions]
1815 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001816 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001817 // An ordered region must be closely nested inside a loop region (or
1818 // parallel loop region) with an ordered clause.
1819 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001820 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001821 !Stack->isParentOrderedRegion();
1822 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001823 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1824 // OpenMP [2.16, Nesting of Regions]
1825 // If specified, a teams construct must be contained within a target
1826 // construct.
1827 NestingProhibited = ParentRegion != OMPD_target;
1828 Recommend = ShouldBeInTargetRegion;
1829 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1830 }
1831 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1832 // OpenMP [2.16, Nesting of Regions]
1833 // distribute, parallel, parallel sections, parallel workshare, and the
1834 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1835 // constructs that can be closely nested in the teams region.
1836 // TODO: add distribute directive.
1837 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1838 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001839 }
1840 if (NestingProhibited) {
1841 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001842 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1843 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001844 return true;
1845 }
1846 }
1847 return false;
1848}
1849
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001850StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001851 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001852 ArrayRef<OMPClause *> Clauses,
1853 Stmt *AStmt,
1854 SourceLocation StartLoc,
1855 SourceLocation EndLoc) {
1856 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001857 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001858 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001859
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001860 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001861 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001862 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001863 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001864 if (AStmt) {
1865 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1866
1867 // Check default data sharing attributes for referenced variables.
1868 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1869 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1870 if (DSAChecker.isErrorFound())
1871 return StmtError();
1872 // Generate list of implicitly defined firstprivate variables.
1873 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001874
1875 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1876 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1877 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1878 SourceLocation(), SourceLocation())) {
1879 ClausesWithImplicit.push_back(Implicit);
1880 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1881 DSAChecker.getImplicitFirstprivate().size();
1882 } else
1883 ErrorFound = true;
1884 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001885 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001886
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001887 switch (Kind) {
1888 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001889 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1890 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001891 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001892 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001893 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1894 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001895 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001896 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001897 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1898 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001899 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001900 case OMPD_for_simd:
1901 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1902 EndLoc, VarsWithInheritedDSA);
1903 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001904 case OMPD_sections:
1905 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1906 EndLoc);
1907 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001908 case OMPD_section:
1909 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001910 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001911 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1912 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001913 case OMPD_single:
1914 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1915 EndLoc);
1916 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001917 case OMPD_master:
1918 assert(ClausesWithImplicit.empty() &&
1919 "No clauses are allowed for 'omp master' directive");
1920 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1921 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001922 case OMPD_critical:
1923 assert(ClausesWithImplicit.empty() &&
1924 "No clauses are allowed for 'omp critical' directive");
1925 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1926 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001927 case OMPD_parallel_for:
1928 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1929 EndLoc, VarsWithInheritedDSA);
1930 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001931 case OMPD_parallel_for_simd:
1932 Res = ActOnOpenMPParallelForSimdDirective(
1933 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1934 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001935 case OMPD_parallel_sections:
1936 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1937 StartLoc, EndLoc);
1938 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001939 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001940 Res =
1941 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1942 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001943 case OMPD_taskyield:
1944 assert(ClausesWithImplicit.empty() &&
1945 "No clauses are allowed for 'omp taskyield' directive");
1946 assert(AStmt == nullptr &&
1947 "No associated statement allowed for 'omp taskyield' directive");
1948 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1949 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001950 case OMPD_barrier:
1951 assert(ClausesWithImplicit.empty() &&
1952 "No clauses are allowed for 'omp barrier' directive");
1953 assert(AStmt == nullptr &&
1954 "No associated statement allowed for 'omp barrier' directive");
1955 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1956 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001957 case OMPD_taskwait:
1958 assert(ClausesWithImplicit.empty() &&
1959 "No clauses are allowed for 'omp taskwait' directive");
1960 assert(AStmt == nullptr &&
1961 "No associated statement allowed for 'omp taskwait' directive");
1962 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1963 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001964 case OMPD_taskgroup:
1965 assert(ClausesWithImplicit.empty() &&
1966 "No clauses are allowed for 'omp taskgroup' directive");
1967 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
1968 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001969 case OMPD_flush:
1970 assert(AStmt == nullptr &&
1971 "No associated statement allowed for 'omp flush' directive");
1972 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1973 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001974 case OMPD_ordered:
1975 assert(ClausesWithImplicit.empty() &&
1976 "No clauses are allowed for 'omp ordered' directive");
1977 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1978 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001979 case OMPD_atomic:
1980 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1981 EndLoc);
1982 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001983 case OMPD_teams:
1984 Res =
1985 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1986 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001987 case OMPD_target:
1988 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1989 EndLoc);
1990 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001991 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001992 llvm_unreachable("OpenMP Directive is not allowed");
1993 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001994 llvm_unreachable("Unknown OpenMP directive");
1995 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001996
Alexey Bataev4acb8592014-07-07 13:01:15 +00001997 for (auto P : VarsWithInheritedDSA) {
1998 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1999 << P.first << P.second->getSourceRange();
2000 }
2001 if (!VarsWithInheritedDSA.empty())
2002 return StmtError();
2003
Alexey Bataeved09d242014-05-28 05:53:51 +00002004 if (ErrorFound)
2005 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002006 return Res;
2007}
2008
2009StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2010 Stmt *AStmt,
2011 SourceLocation StartLoc,
2012 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002013 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2014 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2015 // 1.2.2 OpenMP Language Terminology
2016 // Structured block - An executable statement with a single entry at the
2017 // top and a single exit at the bottom.
2018 // The point of exit cannot be a branch out of the structured block.
2019 // longjmp() and throw() must not violate the entry/exit criteria.
2020 CS->getCapturedDecl()->setNothrow();
2021
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002022 getCurFunction()->setHasBranchProtectedScope();
2023
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002024 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
2025 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002026}
2027
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002028namespace {
2029/// \brief Helper class for checking canonical form of the OpenMP loops and
2030/// extracting iteration space of each loop in the loop nest, that will be used
2031/// for IR generation.
2032class OpenMPIterationSpaceChecker {
2033 /// \brief Reference to Sema.
2034 Sema &SemaRef;
2035 /// \brief A location for diagnostics (when there is no some better location).
2036 SourceLocation DefaultLoc;
2037 /// \brief A location for diagnostics (when increment is not compatible).
2038 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002039 /// \brief A source location for referring to loop init later.
2040 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002041 /// \brief A source location for referring to condition later.
2042 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002043 /// \brief A source location for referring to increment later.
2044 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002045 /// \brief Loop variable.
2046 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002047 /// \brief Reference to loop variable.
2048 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002049 /// \brief Lower bound (initializer for the var).
2050 Expr *LB;
2051 /// \brief Upper bound.
2052 Expr *UB;
2053 /// \brief Loop step (increment).
2054 Expr *Step;
2055 /// \brief This flag is true when condition is one of:
2056 /// Var < UB
2057 /// Var <= UB
2058 /// UB > Var
2059 /// UB >= Var
2060 bool TestIsLessOp;
2061 /// \brief This flag is true when condition is strict ( < or > ).
2062 bool TestIsStrictOp;
2063 /// \brief This flag is true when step is subtracted on each iteration.
2064 bool SubtractStep;
2065
2066public:
2067 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2068 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002069 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2070 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002071 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2072 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002073 /// \brief Check init-expr for canonical loop form and save loop counter
2074 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002075 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002076 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2077 /// for less/greater and for strict/non-strict comparison.
2078 bool CheckCond(Expr *S);
2079 /// \brief Check incr-expr for canonical loop form and return true if it
2080 /// does not conform, otherwise save loop step (#Step).
2081 bool CheckInc(Expr *S);
2082 /// \brief Return the loop counter variable.
2083 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002084 /// \brief Return the reference expression to loop counter variable.
2085 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002086 /// \brief Source range of the loop init.
2087 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2088 /// \brief Source range of the loop condition.
2089 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2090 /// \brief Source range of the loop increment.
2091 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2092 /// \brief True if the step should be subtracted.
2093 bool ShouldSubtractStep() const { return SubtractStep; }
2094 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002095 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002096 /// \brief Build the precondition expression for the loops.
2097 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002098 /// \brief Build reference expression to the counter be used for codegen.
2099 Expr *BuildCounterVar() const;
2100 /// \brief Build initization of the counter be used for codegen.
2101 Expr *BuildCounterInit() const;
2102 /// \brief Build step of the counter be used for codegen.
2103 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002104 /// \brief Return true if any expression is dependent.
2105 bool Dependent() const;
2106
2107private:
2108 /// \brief Check the right-hand side of an assignment in the increment
2109 /// expression.
2110 bool CheckIncRHS(Expr *RHS);
2111 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002112 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002113 /// \brief Helper to set upper bound.
2114 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2115 const SourceLocation &SL);
2116 /// \brief Helper to set loop increment.
2117 bool SetStep(Expr *NewStep, bool Subtract);
2118};
2119
2120bool OpenMPIterationSpaceChecker::Dependent() const {
2121 if (!Var) {
2122 assert(!LB && !UB && !Step);
2123 return false;
2124 }
2125 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2126 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2127}
2128
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002129bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2130 DeclRefExpr *NewVarRefExpr,
2131 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002132 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002133 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2134 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002135 if (!NewVar || !NewLB)
2136 return true;
2137 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002138 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002139 LB = NewLB;
2140 return false;
2141}
2142
2143bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2144 const SourceRange &SR,
2145 const SourceLocation &SL) {
2146 // State consistency checking to ensure correct usage.
2147 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2148 !TestIsLessOp && !TestIsStrictOp);
2149 if (!NewUB)
2150 return true;
2151 UB = NewUB;
2152 TestIsLessOp = LessOp;
2153 TestIsStrictOp = StrictOp;
2154 ConditionSrcRange = SR;
2155 ConditionLoc = SL;
2156 return false;
2157}
2158
2159bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2160 // State consistency checking to ensure correct usage.
2161 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2162 if (!NewStep)
2163 return true;
2164 if (!NewStep->isValueDependent()) {
2165 // Check that the step is integer expression.
2166 SourceLocation StepLoc = NewStep->getLocStart();
2167 ExprResult Val =
2168 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2169 if (Val.isInvalid())
2170 return true;
2171 NewStep = Val.get();
2172
2173 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2174 // If test-expr is of form var relational-op b and relational-op is < or
2175 // <= then incr-expr must cause var to increase on each iteration of the
2176 // loop. If test-expr is of form var relational-op b and relational-op is
2177 // > or >= then incr-expr must cause var to decrease on each iteration of
2178 // the loop.
2179 // If test-expr is of form b relational-op var and relational-op is < or
2180 // <= then incr-expr must cause var to decrease on each iteration of the
2181 // loop. If test-expr is of form b relational-op var and relational-op is
2182 // > or >= then incr-expr must cause var to increase on each iteration of
2183 // the loop.
2184 llvm::APSInt Result;
2185 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2186 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2187 bool IsConstNeg =
2188 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002189 bool IsConstPos =
2190 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002191 bool IsConstZero = IsConstant && !Result.getBoolValue();
2192 if (UB && (IsConstZero ||
2193 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002194 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002195 SemaRef.Diag(NewStep->getExprLoc(),
2196 diag::err_omp_loop_incr_not_compatible)
2197 << Var << TestIsLessOp << NewStep->getSourceRange();
2198 SemaRef.Diag(ConditionLoc,
2199 diag::note_omp_loop_cond_requres_compatible_incr)
2200 << TestIsLessOp << ConditionSrcRange;
2201 return true;
2202 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002203 if (TestIsLessOp == Subtract) {
2204 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2205 NewStep).get();
2206 Subtract = !Subtract;
2207 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002208 }
2209
2210 Step = NewStep;
2211 SubtractStep = Subtract;
2212 return false;
2213}
2214
Alexey Bataev9c821032015-04-30 04:23:23 +00002215bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002216 // Check init-expr for canonical loop form and save loop counter
2217 // variable - #Var and its initialization value - #LB.
2218 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2219 // var = lb
2220 // integer-type var = lb
2221 // random-access-iterator-type var = lb
2222 // pointer-type var = lb
2223 //
2224 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002225 if (EmitDiags) {
2226 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2227 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002228 return true;
2229 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002230 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002231 if (Expr *E = dyn_cast<Expr>(S))
2232 S = E->IgnoreParens();
2233 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2234 if (BO->getOpcode() == BO_Assign)
2235 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002236 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002237 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002238 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2239 if (DS->isSingleDecl()) {
2240 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2241 if (Var->hasInit()) {
2242 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002243 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002244 SemaRef.Diag(S->getLocStart(),
2245 diag::ext_omp_loop_not_canonical_init)
2246 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002247 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002248 }
2249 }
2250 }
2251 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2252 if (CE->getOperator() == OO_Equal)
2253 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002254 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2255 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002256
Alexey Bataev9c821032015-04-30 04:23:23 +00002257 if (EmitDiags) {
2258 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2259 << S->getSourceRange();
2260 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002261 return true;
2262}
2263
Alexey Bataev23b69422014-06-18 07:08:49 +00002264/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002265/// variable (which may be the loop variable) if possible.
2266static const VarDecl *GetInitVarDecl(const Expr *E) {
2267 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002268 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002269 E = E->IgnoreParenImpCasts();
2270 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2271 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2272 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2273 CE->getArg(0) != nullptr)
2274 E = CE->getArg(0)->IgnoreParenImpCasts();
2275 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2276 if (!DRE)
2277 return nullptr;
2278 return dyn_cast<VarDecl>(DRE->getDecl());
2279}
2280
2281bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2282 // Check test-expr for canonical form, save upper-bound UB, flags for
2283 // less/greater and for strict/non-strict comparison.
2284 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2285 // var relational-op b
2286 // b relational-op var
2287 //
2288 if (!S) {
2289 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2290 return true;
2291 }
2292 S = S->IgnoreParenImpCasts();
2293 SourceLocation CondLoc = S->getLocStart();
2294 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2295 if (BO->isRelationalOp()) {
2296 if (GetInitVarDecl(BO->getLHS()) == Var)
2297 return SetUB(BO->getRHS(),
2298 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2299 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2300 BO->getSourceRange(), BO->getOperatorLoc());
2301 if (GetInitVarDecl(BO->getRHS()) == Var)
2302 return SetUB(BO->getLHS(),
2303 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2304 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2305 BO->getSourceRange(), BO->getOperatorLoc());
2306 }
2307 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2308 if (CE->getNumArgs() == 2) {
2309 auto Op = CE->getOperator();
2310 switch (Op) {
2311 case OO_Greater:
2312 case OO_GreaterEqual:
2313 case OO_Less:
2314 case OO_LessEqual:
2315 if (GetInitVarDecl(CE->getArg(0)) == Var)
2316 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2317 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2318 CE->getOperatorLoc());
2319 if (GetInitVarDecl(CE->getArg(1)) == Var)
2320 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2321 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2322 CE->getOperatorLoc());
2323 break;
2324 default:
2325 break;
2326 }
2327 }
2328 }
2329 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2330 << S->getSourceRange() << Var;
2331 return true;
2332}
2333
2334bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2335 // RHS of canonical loop form increment can be:
2336 // var + incr
2337 // incr + var
2338 // var - incr
2339 //
2340 RHS = RHS->IgnoreParenImpCasts();
2341 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2342 if (BO->isAdditiveOp()) {
2343 bool IsAdd = BO->getOpcode() == BO_Add;
2344 if (GetInitVarDecl(BO->getLHS()) == Var)
2345 return SetStep(BO->getRHS(), !IsAdd);
2346 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2347 return SetStep(BO->getLHS(), false);
2348 }
2349 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2350 bool IsAdd = CE->getOperator() == OO_Plus;
2351 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2352 if (GetInitVarDecl(CE->getArg(0)) == Var)
2353 return SetStep(CE->getArg(1), !IsAdd);
2354 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2355 return SetStep(CE->getArg(0), false);
2356 }
2357 }
2358 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2359 << RHS->getSourceRange() << Var;
2360 return true;
2361}
2362
2363bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2364 // Check incr-expr for canonical loop form and return true if it
2365 // does not conform.
2366 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2367 // ++var
2368 // var++
2369 // --var
2370 // var--
2371 // var += incr
2372 // var -= incr
2373 // var = var + incr
2374 // var = incr + var
2375 // var = var - incr
2376 //
2377 if (!S) {
2378 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2379 return true;
2380 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002381 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002382 S = S->IgnoreParens();
2383 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2384 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2385 return SetStep(
2386 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2387 (UO->isDecrementOp() ? -1 : 1)).get(),
2388 false);
2389 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2390 switch (BO->getOpcode()) {
2391 case BO_AddAssign:
2392 case BO_SubAssign:
2393 if (GetInitVarDecl(BO->getLHS()) == Var)
2394 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2395 break;
2396 case BO_Assign:
2397 if (GetInitVarDecl(BO->getLHS()) == Var)
2398 return CheckIncRHS(BO->getRHS());
2399 break;
2400 default:
2401 break;
2402 }
2403 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2404 switch (CE->getOperator()) {
2405 case OO_PlusPlus:
2406 case OO_MinusMinus:
2407 if (GetInitVarDecl(CE->getArg(0)) == Var)
2408 return SetStep(
2409 SemaRef.ActOnIntegerConstant(
2410 CE->getLocStart(),
2411 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2412 false);
2413 break;
2414 case OO_PlusEqual:
2415 case OO_MinusEqual:
2416 if (GetInitVarDecl(CE->getArg(0)) == Var)
2417 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2418 break;
2419 case OO_Equal:
2420 if (GetInitVarDecl(CE->getArg(0)) == Var)
2421 return CheckIncRHS(CE->getArg(1));
2422 break;
2423 default:
2424 break;
2425 }
2426 }
2427 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2428 << S->getSourceRange() << Var;
2429 return true;
2430}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002431
2432/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002433Expr *
2434OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2435 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002436 ExprResult Diff;
2437 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2438 SemaRef.getLangOpts().CPlusPlus) {
2439 // Upper - Lower
2440 Expr *Upper = TestIsLessOp ? UB : LB;
2441 Expr *Lower = TestIsLessOp ? LB : UB;
2442
2443 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2444
2445 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2446 // BuildBinOp already emitted error, this one is to point user to upper
2447 // and lower bound, and to tell what is passed to 'operator-'.
2448 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2449 << Upper->getSourceRange() << Lower->getSourceRange();
2450 return nullptr;
2451 }
2452 }
2453
2454 if (!Diff.isUsable())
2455 return nullptr;
2456
2457 // Upper - Lower [- 1]
2458 if (TestIsStrictOp)
2459 Diff = SemaRef.BuildBinOp(
2460 S, DefaultLoc, BO_Sub, Diff.get(),
2461 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2462 if (!Diff.isUsable())
2463 return nullptr;
2464
2465 // Upper - Lower [- 1] + Step
2466 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2467 Step->IgnoreImplicit());
2468 if (!Diff.isUsable())
2469 return nullptr;
2470
2471 // Parentheses (for dumping/debugging purposes only).
2472 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2473 if (!Diff.isUsable())
2474 return nullptr;
2475
2476 // (Upper - Lower [- 1] + Step) / Step
2477 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2478 Step->IgnoreImplicit());
2479 if (!Diff.isUsable())
2480 return nullptr;
2481
Alexander Musman174b3ca2014-10-06 11:16:29 +00002482 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2483 if (LimitedType) {
2484 auto &C = SemaRef.Context;
2485 QualType Type = Diff.get()->getType();
2486 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2487 if (NewSize != C.getTypeSize(Type)) {
2488 if (NewSize < C.getTypeSize(Type)) {
2489 assert(NewSize == 64 && "incorrect loop var size");
2490 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2491 << InitSrcRange << ConditionSrcRange;
2492 }
2493 QualType NewType = C.getIntTypeForBitwidth(
2494 NewSize, Type->hasSignedIntegerRepresentation());
2495 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2496 Sema::AA_Converting, true);
2497 if (!Diff.isUsable())
2498 return nullptr;
2499 }
2500 }
2501
Alexander Musmana5f070a2014-10-01 06:03:56 +00002502 return Diff.get();
2503}
2504
Alexey Bataev62dbb972015-04-22 11:59:37 +00002505Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2506 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2507 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2508 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2509 auto CondExpr = SemaRef.BuildBinOp(
2510 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2511 : (TestIsStrictOp ? BO_GT : BO_GE),
2512 LB, UB);
2513 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2514 // Otherwise use original loop conditon and evaluate it in runtime.
2515 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2516}
2517
Alexander Musmana5f070a2014-10-01 06:03:56 +00002518/// \brief Build reference expression to the counter be used for codegen.
2519Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002520 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002521}
2522
2523/// \brief Build initization of the counter be used for codegen.
2524Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2525
2526/// \brief Build step of the counter be used for codegen.
2527Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2528
2529/// \brief Iteration space of a single for loop.
2530struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002531 /// \brief Condition of the loop.
2532 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002533 /// \brief This expression calculates the number of iterations in the loop.
2534 /// It is always possible to calculate it before starting the loop.
2535 Expr *NumIterations;
2536 /// \brief The loop counter variable.
2537 Expr *CounterVar;
2538 /// \brief This is initializer for the initial value of #CounterVar.
2539 Expr *CounterInit;
2540 /// \brief This is step for the #CounterVar used to generate its update:
2541 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2542 Expr *CounterStep;
2543 /// \brief Should step be subtracted?
2544 bool Subtract;
2545 /// \brief Source range of the loop init.
2546 SourceRange InitSrcRange;
2547 /// \brief Source range of the loop condition.
2548 SourceRange CondSrcRange;
2549 /// \brief Source range of the loop increment.
2550 SourceRange IncSrcRange;
2551};
2552
Alexey Bataev23b69422014-06-18 07:08:49 +00002553} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002554
Alexey Bataev9c821032015-04-30 04:23:23 +00002555void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2556 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2557 assert(Init && "Expected loop in canonical form.");
2558 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2559 if (CollapseIteration > 0 &&
2560 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2561 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2562 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2563 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2564 }
2565 DSAStack->setCollapseNumber(CollapseIteration - 1);
2566 }
2567}
2568
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002569/// \brief Called on a for stmt to check and extract its iteration space
2570/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002571static bool CheckOpenMPIterationSpace(
2572 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2573 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2574 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002575 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2576 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002577 // OpenMP [2.6, Canonical Loop Form]
2578 // for (init-expr; test-expr; incr-expr) structured-block
2579 auto For = dyn_cast_or_null<ForStmt>(S);
2580 if (!For) {
2581 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002582 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2583 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2584 << CurrentNestedLoopCount;
2585 if (NestedLoopCount > 1)
2586 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2587 diag::note_omp_collapse_expr)
2588 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002589 return true;
2590 }
2591 assert(For->getBody());
2592
2593 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2594
2595 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002596 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002597 if (ISC.CheckInit(Init)) {
2598 return true;
2599 }
2600
2601 bool HasErrors = false;
2602
2603 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002604 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002605
2606 // OpenMP [2.6, Canonical Loop Form]
2607 // Var is one of the following:
2608 // A variable of signed or unsigned integer type.
2609 // For C++, a variable of a random access iterator type.
2610 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002611 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002612 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2613 !VarType->isPointerType() &&
2614 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2615 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2616 << SemaRef.getLangOpts().CPlusPlus;
2617 HasErrors = true;
2618 }
2619
Alexey Bataev4acb8592014-07-07 13:01:15 +00002620 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2621 // Construct
2622 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2623 // parallel for construct is (are) private.
2624 // The loop iteration variable in the associated for-loop of a simd construct
2625 // with just one associated for-loop is linear with a constant-linear-step
2626 // that is the increment of the associated for-loop.
2627 // Exclude loop var from the list of variables with implicitly defined data
2628 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002629 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002630
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002631 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2632 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002633 // The loop iteration variable in the associated for-loop of a simd construct
2634 // with just one associated for-loop may be listed in a linear clause with a
2635 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002636 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2637 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002638 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002639 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2640 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2641 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002642 auto PredeterminedCKind =
2643 isOpenMPSimdDirective(DKind)
2644 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2645 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002646 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002647 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002648 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2649 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002650 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2651 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2652 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002653 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002654 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2655 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00002656 if (DVar.RefExpr == nullptr)
2657 DVar.CKind = PredeterminedCKind;
2658 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002659 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002660 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002661 // Make the loop iteration variable private (for worksharing constructs),
2662 // linear (for simd directives with the only one associated loop) or
2663 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002664 if (DVar.CKind == OMPC_unknown)
2665 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2666 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00002667 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002668 }
2669
Alexey Bataev7ff55242014-06-19 09:13:45 +00002670 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002671
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002672 // Check test-expr.
2673 HasErrors |= ISC.CheckCond(For->getCond());
2674
2675 // Check incr-expr.
2676 HasErrors |= ISC.CheckInc(For->getInc());
2677
Alexander Musmana5f070a2014-10-01 06:03:56 +00002678 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002679 return HasErrors;
2680
Alexander Musmana5f070a2014-10-01 06:03:56 +00002681 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002682 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00002683 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2684 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002685 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2686 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2687 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2688 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2689 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2690 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2691 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2692
Alexey Bataev62dbb972015-04-22 11:59:37 +00002693 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2694 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002695 ResultIterSpace.CounterVar == nullptr ||
2696 ResultIterSpace.CounterInit == nullptr ||
2697 ResultIterSpace.CounterStep == nullptr);
2698
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002699 return HasErrors;
2700}
2701
Alexander Musmana5f070a2014-10-01 06:03:56 +00002702/// \brief Build 'VarRef = Start + Iter * Step'.
2703static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2704 SourceLocation Loc, ExprResult VarRef,
2705 ExprResult Start, ExprResult Iter,
2706 ExprResult Step, bool Subtract) {
2707 // Add parentheses (for debugging purposes only).
2708 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2709 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2710 !Step.isUsable())
2711 return ExprError();
2712
2713 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2714 Step.get()->IgnoreImplicit());
2715 if (!Update.isUsable())
2716 return ExprError();
2717
2718 // Build 'VarRef = Start + Iter * Step'.
2719 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2720 Start.get()->IgnoreImplicit(), Update.get());
2721 if (!Update.isUsable())
2722 return ExprError();
2723
2724 Update = SemaRef.PerformImplicitConversion(
2725 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2726 if (!Update.isUsable())
2727 return ExprError();
2728
2729 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2730 return Update;
2731}
2732
2733/// \brief Convert integer expression \a E to make it have at least \a Bits
2734/// bits.
2735static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2736 Sema &SemaRef) {
2737 if (E == nullptr)
2738 return ExprError();
2739 auto &C = SemaRef.Context;
2740 QualType OldType = E->getType();
2741 unsigned HasBits = C.getTypeSize(OldType);
2742 if (HasBits >= Bits)
2743 return ExprResult(E);
2744 // OK to convert to signed, because new type has more bits than old.
2745 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2746 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2747 true);
2748}
2749
2750/// \brief Check if the given expression \a E is a constant integer that fits
2751/// into \a Bits bits.
2752static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2753 if (E == nullptr)
2754 return false;
2755 llvm::APSInt Result;
2756 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2757 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2758 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002759}
2760
2761/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002762/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2763/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002764static unsigned
2765CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2766 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002767 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002768 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002769 unsigned NestedLoopCount = 1;
2770 if (NestedLoopCountExpr) {
2771 // Found 'collapse' clause - calculate collapse number.
2772 llvm::APSInt Result;
2773 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2774 NestedLoopCount = Result.getLimitedValue();
2775 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002776 // This is helper routine for loop directives (e.g., 'for', 'simd',
2777 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002778 SmallVector<LoopIterationSpace, 4> IterSpaces;
2779 IterSpaces.resize(NestedLoopCount);
2780 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002781 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002782 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002783 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002784 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002785 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002786 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002787 // OpenMP [2.8.1, simd construct, Restrictions]
2788 // All loops associated with the construct must be perfectly nested; that
2789 // is, there must be no intervening code nor any OpenMP directive between
2790 // any two loops.
2791 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002792 }
2793
Alexander Musmana5f070a2014-10-01 06:03:56 +00002794 Built.clear(/* size */ NestedLoopCount);
2795
2796 if (SemaRef.CurContext->isDependentContext())
2797 return NestedLoopCount;
2798
2799 // An example of what is generated for the following code:
2800 //
2801 // #pragma omp simd collapse(2)
2802 // for (i = 0; i < NI; ++i)
2803 // for (j = J0; j < NJ; j+=2) {
2804 // <loop body>
2805 // }
2806 //
2807 // We generate the code below.
2808 // Note: the loop body may be outlined in CodeGen.
2809 // Note: some counters may be C++ classes, operator- is used to find number of
2810 // iterations and operator+= to calculate counter value.
2811 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2812 // or i64 is currently supported).
2813 //
2814 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2815 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2816 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2817 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2818 // // similar updates for vars in clauses (e.g. 'linear')
2819 // <loop body (using local i and j)>
2820 // }
2821 // i = NI; // assign final values of counters
2822 // j = NJ;
2823 //
2824
2825 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2826 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002827 // Precondition tests if there is at least one iteration (all conditions are
2828 // true).
2829 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002830 auto N0 = IterSpaces[0].NumIterations;
2831 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2832 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2833
2834 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2835 return NestedLoopCount;
2836
2837 auto &C = SemaRef.Context;
2838 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2839
2840 Scope *CurScope = DSA.getCurScope();
2841 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002842 if (PreCond.isUsable()) {
2843 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2844 PreCond.get(), IterSpaces[Cnt].PreCond);
2845 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002846 auto N = IterSpaces[Cnt].NumIterations;
2847 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2848 if (LastIteration32.isUsable())
2849 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2850 LastIteration32.get(), N);
2851 if (LastIteration64.isUsable())
2852 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2853 LastIteration64.get(), N);
2854 }
2855
2856 // Choose either the 32-bit or 64-bit version.
2857 ExprResult LastIteration = LastIteration64;
2858 if (LastIteration32.isUsable() &&
2859 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2860 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2861 FitsInto(
2862 32 /* Bits */,
2863 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2864 LastIteration64.get(), SemaRef)))
2865 LastIteration = LastIteration32;
2866
2867 if (!LastIteration.isUsable())
2868 return 0;
2869
2870 // Save the number of iterations.
2871 ExprResult NumIterations = LastIteration;
2872 {
2873 LastIteration = SemaRef.BuildBinOp(
2874 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2875 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2876 if (!LastIteration.isUsable())
2877 return 0;
2878 }
2879
2880 // Calculate the last iteration number beforehand instead of doing this on
2881 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2882 llvm::APSInt Result;
2883 bool IsConstant =
2884 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2885 ExprResult CalcLastIteration;
2886 if (!IsConstant) {
2887 SourceLocation SaveLoc;
2888 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00002889 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002890 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00002891 ExprResult SaveRef = buildDeclRefExpr(
2892 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002893 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2894 SaveRef.get(), LastIteration.get());
2895 LastIteration = SaveRef;
2896
2897 // Prepare SaveRef + 1.
2898 NumIterations = SemaRef.BuildBinOp(
2899 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2900 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2901 if (!NumIterations.isUsable())
2902 return 0;
2903 }
2904
2905 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2906
Alexander Musmanc6388682014-12-15 07:07:06 +00002907 QualType VType = LastIteration.get()->getType();
2908 // Build variables passed into runtime, nesessary for worksharing directives.
2909 ExprResult LB, UB, IL, ST, EUB;
2910 if (isOpenMPWorksharingDirective(DKind)) {
2911 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002912 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2913 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002914 SemaRef.AddInitializerToDecl(
2915 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2916 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2917
2918 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002919 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2920 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002921 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2922 /*DirectInit*/ false,
2923 /*TypeMayContainAuto*/ false);
2924
2925 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2926 // This will be used to implement clause 'lastprivate'.
2927 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002928 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2929 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002930 SemaRef.AddInitializerToDecl(
2931 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2932 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2933
2934 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00002935 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2936 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002937 SemaRef.AddInitializerToDecl(
2938 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2939 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2940
2941 // Build expression: UB = min(UB, LastIteration)
2942 // It is nesessary for CodeGen of directives with static scheduling.
2943 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2944 UB.get(), LastIteration.get());
2945 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2946 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2947 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2948 CondOp.get());
2949 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2950 }
2951
2952 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002953 ExprResult IV;
2954 ExprResult Init;
2955 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002956 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2957 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002958 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2959 ? LB.get()
2960 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2961 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2962 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002963 }
2964
Alexander Musmanc6388682014-12-15 07:07:06 +00002965 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002966 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002967 ExprResult Cond =
2968 isOpenMPWorksharingDirective(DKind)
2969 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2970 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2971 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002972
2973 // Loop increment (IV = IV + 1)
2974 SourceLocation IncLoc;
2975 ExprResult Inc =
2976 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2977 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2978 if (!Inc.isUsable())
2979 return 0;
2980 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002981 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2982 if (!Inc.isUsable())
2983 return 0;
2984
2985 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2986 // Used for directives with static scheduling.
2987 ExprResult NextLB, NextUB;
2988 if (isOpenMPWorksharingDirective(DKind)) {
2989 // LB + ST
2990 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2991 if (!NextLB.isUsable())
2992 return 0;
2993 // LB = LB + ST
2994 NextLB =
2995 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2996 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2997 if (!NextLB.isUsable())
2998 return 0;
2999 // UB + ST
3000 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3001 if (!NextUB.isUsable())
3002 return 0;
3003 // UB = UB + ST
3004 NextUB =
3005 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3006 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3007 if (!NextUB.isUsable())
3008 return 0;
3009 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003010
3011 // Build updates and final values of the loop counters.
3012 bool HasErrors = false;
3013 Built.Counters.resize(NestedLoopCount);
3014 Built.Updates.resize(NestedLoopCount);
3015 Built.Finals.resize(NestedLoopCount);
3016 {
3017 ExprResult Div;
3018 // Go from inner nested loop to outer.
3019 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3020 LoopIterationSpace &IS = IterSpaces[Cnt];
3021 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3022 // Build: Iter = (IV / Div) % IS.NumIters
3023 // where Div is product of previous iterations' IS.NumIters.
3024 ExprResult Iter;
3025 if (Div.isUsable()) {
3026 Iter =
3027 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3028 } else {
3029 Iter = IV;
3030 assert((Cnt == (int)NestedLoopCount - 1) &&
3031 "unusable div expected on first iteration only");
3032 }
3033
3034 if (Cnt != 0 && Iter.isUsable())
3035 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3036 IS.NumIterations);
3037 if (!Iter.isUsable()) {
3038 HasErrors = true;
3039 break;
3040 }
3041
Alexey Bataev39f915b82015-05-08 10:41:21 +00003042 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3043 auto *CounterVar = buildDeclRefExpr(
3044 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3045 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3046 /*RefersToCapture=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003047 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003048 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003049 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3050 if (!Update.isUsable()) {
3051 HasErrors = true;
3052 break;
3053 }
3054
3055 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3056 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003057 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003058 IS.NumIterations, IS.CounterStep, IS.Subtract);
3059 if (!Final.isUsable()) {
3060 HasErrors = true;
3061 break;
3062 }
3063
3064 // Build Div for the next iteration: Div <- Div * IS.NumIters
3065 if (Cnt != 0) {
3066 if (Div.isUnset())
3067 Div = IS.NumIterations;
3068 else
3069 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3070 IS.NumIterations);
3071
3072 // Add parentheses (for debugging purposes only).
3073 if (Div.isUsable())
3074 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3075 if (!Div.isUsable()) {
3076 HasErrors = true;
3077 break;
3078 }
3079 }
3080 if (!Update.isUsable() || !Final.isUsable()) {
3081 HasErrors = true;
3082 break;
3083 }
3084 // Save results
3085 Built.Counters[Cnt] = IS.CounterVar;
3086 Built.Updates[Cnt] = Update.get();
3087 Built.Finals[Cnt] = Final.get();
3088 }
3089 }
3090
3091 if (HasErrors)
3092 return 0;
3093
3094 // Save results
3095 Built.IterationVarRef = IV.get();
3096 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003097 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003098 Built.CalcLastIteration = CalcLastIteration.get();
3099 Built.PreCond = PreCond.get();
3100 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003101 Built.Init = Init.get();
3102 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003103 Built.LB = LB.get();
3104 Built.UB = UB.get();
3105 Built.IL = IL.get();
3106 Built.ST = ST.get();
3107 Built.EUB = EUB.get();
3108 Built.NLB = NextLB.get();
3109 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003110
Alexey Bataevabfc0692014-06-25 06:52:00 +00003111 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003112}
3113
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003114static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevc925aa32015-04-27 08:00:32 +00003115 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003116 return C->getClauseKind() == OMPC_collapse;
3117 };
3118 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
Alexey Bataevc925aa32015-04-27 08:00:32 +00003119 Clauses, std::move(CollapseFilter));
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003120 if (I)
3121 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3122 return nullptr;
3123}
3124
Alexey Bataev4acb8592014-07-07 13:01:15 +00003125StmtResult Sema::ActOnOpenMPSimdDirective(
3126 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3127 SourceLocation EndLoc,
3128 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003129 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003130 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003131 unsigned NestedLoopCount =
3132 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003133 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003134 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003135 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003136
Alexander Musmana5f070a2014-10-01 06:03:56 +00003137 assert((CurContext->isDependentContext() || B.builtAll()) &&
3138 "omp simd loop exprs were not built");
3139
Alexander Musman3276a272015-03-21 10:12:56 +00003140 if (!CurContext->isDependentContext()) {
3141 // Finalize the clauses that need pre-built expressions for CodeGen.
3142 for (auto C : Clauses) {
3143 if (auto LC = dyn_cast<OMPLinearClause>(C))
3144 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3145 B.NumIterations, *this, CurScope))
3146 return StmtError();
3147 }
3148 }
3149
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003150 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003151 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3152 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003153}
3154
Alexey Bataev4acb8592014-07-07 13:01:15 +00003155StmtResult Sema::ActOnOpenMPForDirective(
3156 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3157 SourceLocation EndLoc,
3158 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003159 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003160 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003161 unsigned NestedLoopCount =
3162 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003163 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003164 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003165 return StmtError();
3166
Alexander Musmana5f070a2014-10-01 06:03:56 +00003167 assert((CurContext->isDependentContext() || B.builtAll()) &&
3168 "omp for loop exprs were not built");
3169
Alexey Bataevf29276e2014-06-18 04:14:57 +00003170 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003171 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3172 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003173}
3174
Alexander Musmanf82886e2014-09-18 05:12:34 +00003175StmtResult Sema::ActOnOpenMPForSimdDirective(
3176 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3177 SourceLocation EndLoc,
3178 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003179 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003180 // In presence of clause 'collapse', it will define the nested loops number.
3181 unsigned NestedLoopCount =
3182 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003183 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003184 if (NestedLoopCount == 0)
3185 return StmtError();
3186
Alexander Musmanc6388682014-12-15 07:07:06 +00003187 assert((CurContext->isDependentContext() || B.builtAll()) &&
3188 "omp for simd loop exprs were not built");
3189
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00003190 if (!CurContext->isDependentContext()) {
3191 // Finalize the clauses that need pre-built expressions for CodeGen.
3192 for (auto C : Clauses) {
3193 if (auto LC = dyn_cast<OMPLinearClause>(C))
3194 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3195 B.NumIterations, *this, CurScope))
3196 return StmtError();
3197 }
3198 }
3199
Alexander Musmanf82886e2014-09-18 05:12:34 +00003200 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003201 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3202 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003203}
3204
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003205StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3206 Stmt *AStmt,
3207 SourceLocation StartLoc,
3208 SourceLocation EndLoc) {
3209 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3210 auto BaseStmt = AStmt;
3211 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3212 BaseStmt = CS->getCapturedStmt();
3213 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3214 auto S = C->children();
3215 if (!S)
3216 return StmtError();
3217 // All associated statements must be '#pragma omp section' except for
3218 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003219 for (++S; S; ++S) {
3220 auto SectionStmt = *S;
3221 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3222 if (SectionStmt)
3223 Diag(SectionStmt->getLocStart(),
3224 diag::err_omp_sections_substmt_not_section);
3225 return StmtError();
3226 }
3227 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003228 } else {
3229 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3230 return StmtError();
3231 }
3232
3233 getCurFunction()->setHasBranchProtectedScope();
3234
3235 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3236 AStmt);
3237}
3238
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003239StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3240 SourceLocation StartLoc,
3241 SourceLocation EndLoc) {
3242 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3243
3244 getCurFunction()->setHasBranchProtectedScope();
3245
3246 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3247}
3248
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003249StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3250 Stmt *AStmt,
3251 SourceLocation StartLoc,
3252 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003253 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3254
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003255 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003256
Alexey Bataev3255bf32015-01-19 05:20:46 +00003257 // OpenMP [2.7.3, single Construct, Restrictions]
3258 // The copyprivate clause must not be used with the nowait clause.
3259 OMPClause *Nowait = nullptr;
3260 OMPClause *Copyprivate = nullptr;
3261 for (auto *Clause : Clauses) {
3262 if (Clause->getClauseKind() == OMPC_nowait)
3263 Nowait = Clause;
3264 else if (Clause->getClauseKind() == OMPC_copyprivate)
3265 Copyprivate = Clause;
3266 if (Copyprivate && Nowait) {
3267 Diag(Copyprivate->getLocStart(),
3268 diag::err_omp_single_copyprivate_with_nowait);
3269 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3270 return StmtError();
3271 }
3272 }
3273
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003274 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3275}
3276
Alexander Musman80c22892014-07-17 08:54:58 +00003277StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3278 SourceLocation StartLoc,
3279 SourceLocation EndLoc) {
3280 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3281
3282 getCurFunction()->setHasBranchProtectedScope();
3283
3284 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3285}
3286
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003287StmtResult
3288Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3289 Stmt *AStmt, SourceLocation StartLoc,
3290 SourceLocation EndLoc) {
3291 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3292
3293 getCurFunction()->setHasBranchProtectedScope();
3294
3295 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3296 AStmt);
3297}
3298
Alexey Bataev4acb8592014-07-07 13:01:15 +00003299StmtResult Sema::ActOnOpenMPParallelForDirective(
3300 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3301 SourceLocation EndLoc,
3302 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3303 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3304 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3305 // 1.2.2 OpenMP Language Terminology
3306 // Structured block - An executable statement with a single entry at the
3307 // top and a single exit at the bottom.
3308 // The point of exit cannot be a branch out of the structured block.
3309 // longjmp() and throw() must not violate the entry/exit criteria.
3310 CS->getCapturedDecl()->setNothrow();
3311
Alexander Musmanc6388682014-12-15 07:07:06 +00003312 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003313 // In presence of clause 'collapse', it will define the nested loops number.
3314 unsigned NestedLoopCount =
3315 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003316 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003317 if (NestedLoopCount == 0)
3318 return StmtError();
3319
Alexander Musmana5f070a2014-10-01 06:03:56 +00003320 assert((CurContext->isDependentContext() || B.builtAll()) &&
3321 "omp parallel for loop exprs were not built");
3322
Alexey Bataev4acb8592014-07-07 13:01:15 +00003323 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003324 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3325 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003326}
3327
Alexander Musmane4e893b2014-09-23 09:33:00 +00003328StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3329 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3330 SourceLocation EndLoc,
3331 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3332 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3333 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3334 // 1.2.2 OpenMP Language Terminology
3335 // Structured block - An executable statement with a single entry at the
3336 // top and a single exit at the bottom.
3337 // The point of exit cannot be a branch out of the structured block.
3338 // longjmp() and throw() must not violate the entry/exit criteria.
3339 CS->getCapturedDecl()->setNothrow();
3340
Alexander Musmanc6388682014-12-15 07:07:06 +00003341 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003342 // In presence of clause 'collapse', it will define the nested loops number.
3343 unsigned NestedLoopCount =
3344 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003345 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003346 if (NestedLoopCount == 0)
3347 return StmtError();
3348
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00003349 if (!CurContext->isDependentContext()) {
3350 // Finalize the clauses that need pre-built expressions for CodeGen.
3351 for (auto C : Clauses) {
3352 if (auto LC = dyn_cast<OMPLinearClause>(C))
3353 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3354 B.NumIterations, *this, CurScope))
3355 return StmtError();
3356 }
3357 }
3358
Alexander Musmane4e893b2014-09-23 09:33:00 +00003359 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003360 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003361 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003362}
3363
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003364StmtResult
3365Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3366 Stmt *AStmt, SourceLocation StartLoc,
3367 SourceLocation EndLoc) {
3368 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3369 auto BaseStmt = AStmt;
3370 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3371 BaseStmt = CS->getCapturedStmt();
3372 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3373 auto S = C->children();
3374 if (!S)
3375 return StmtError();
3376 // All associated statements must be '#pragma omp section' except for
3377 // the first one.
3378 for (++S; S; ++S) {
3379 auto SectionStmt = *S;
3380 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3381 if (SectionStmt)
3382 Diag(SectionStmt->getLocStart(),
3383 diag::err_omp_parallel_sections_substmt_not_section);
3384 return StmtError();
3385 }
3386 }
3387 } else {
3388 Diag(AStmt->getLocStart(),
3389 diag::err_omp_parallel_sections_not_compound_stmt);
3390 return StmtError();
3391 }
3392
3393 getCurFunction()->setHasBranchProtectedScope();
3394
3395 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3396 Clauses, AStmt);
3397}
3398
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003399StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3400 Stmt *AStmt, SourceLocation StartLoc,
3401 SourceLocation EndLoc) {
3402 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3403 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3404 // 1.2.2 OpenMP Language Terminology
3405 // Structured block - An executable statement with a single entry at the
3406 // top and a single exit at the bottom.
3407 // The point of exit cannot be a branch out of the structured block.
3408 // longjmp() and throw() must not violate the entry/exit criteria.
3409 CS->getCapturedDecl()->setNothrow();
3410
3411 getCurFunction()->setHasBranchProtectedScope();
3412
3413 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3414}
3415
Alexey Bataev68446b72014-07-18 07:47:19 +00003416StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3417 SourceLocation EndLoc) {
3418 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3419}
3420
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003421StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3422 SourceLocation EndLoc) {
3423 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3424}
3425
Alexey Bataev2df347a2014-07-18 10:17:07 +00003426StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3427 SourceLocation EndLoc) {
3428 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3429}
3430
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003431StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
3432 SourceLocation StartLoc,
3433 SourceLocation EndLoc) {
3434 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3435
3436 getCurFunction()->setHasBranchProtectedScope();
3437
3438 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
3439}
3440
Alexey Bataev6125da92014-07-21 11:26:11 +00003441StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3442 SourceLocation StartLoc,
3443 SourceLocation EndLoc) {
3444 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3445 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3446}
3447
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003448StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3449 SourceLocation StartLoc,
3450 SourceLocation EndLoc) {
3451 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3452
3453 getCurFunction()->setHasBranchProtectedScope();
3454
3455 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3456}
3457
Alexey Bataev1d160b12015-03-13 12:27:31 +00003458namespace {
3459/// \brief Helper class for checking expression in 'omp atomic [update]'
3460/// construct.
3461class OpenMPAtomicUpdateChecker {
3462 /// \brief Error results for atomic update expressions.
3463 enum ExprAnalysisErrorCode {
3464 /// \brief A statement is not an expression statement.
3465 NotAnExpression,
3466 /// \brief Expression is not builtin binary or unary operation.
3467 NotABinaryOrUnaryExpression,
3468 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3469 NotAnUnaryIncDecExpression,
3470 /// \brief An expression is not of scalar type.
3471 NotAScalarType,
3472 /// \brief A binary operation is not an assignment operation.
3473 NotAnAssignmentOp,
3474 /// \brief RHS part of the binary operation is not a binary expression.
3475 NotABinaryExpression,
3476 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3477 /// expression.
3478 NotABinaryOperator,
3479 /// \brief RHS binary operation does not have reference to the updated LHS
3480 /// part.
3481 NotAnUpdateExpression,
3482 /// \brief No errors is found.
3483 NoError
3484 };
3485 /// \brief Reference to Sema.
3486 Sema &SemaRef;
3487 /// \brief A location for note diagnostics (when error is found).
3488 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003489 /// \brief 'x' lvalue part of the source atomic expression.
3490 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003491 /// \brief 'expr' rvalue part of the source atomic expression.
3492 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003493 /// \brief Helper expression of the form
3494 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3495 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3496 Expr *UpdateExpr;
3497 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3498 /// important for non-associative operations.
3499 bool IsXLHSInRHSPart;
3500 BinaryOperatorKind Op;
3501 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003502 /// \brief true if the source expression is a postfix unary operation, false
3503 /// if it is a prefix unary operation.
3504 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003505
3506public:
3507 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003508 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003509 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003510 /// \brief Check specified statement that it is suitable for 'atomic update'
3511 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003512 /// expression. If DiagId and NoteId == 0, then only check is performed
3513 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003514 /// \param DiagId Diagnostic which should be emitted if error is found.
3515 /// \param NoteId Diagnostic note for the main error message.
3516 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003517 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003518 /// \brief Return the 'x' lvalue part of the source atomic expression.
3519 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003520 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3521 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003522 /// \brief Return the update expression used in calculation of the updated
3523 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3524 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3525 Expr *getUpdateExpr() const { return UpdateExpr; }
3526 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3527 /// false otherwise.
3528 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3529
Alexey Bataevb78ca832015-04-01 03:33:17 +00003530 /// \brief true if the source expression is a postfix unary operation, false
3531 /// if it is a prefix unary operation.
3532 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3533
Alexey Bataev1d160b12015-03-13 12:27:31 +00003534private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003535 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3536 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003537};
3538} // namespace
3539
3540bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3541 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3542 ExprAnalysisErrorCode ErrorFound = NoError;
3543 SourceLocation ErrorLoc, NoteLoc;
3544 SourceRange ErrorRange, NoteRange;
3545 // Allowed constructs are:
3546 // x = x binop expr;
3547 // x = expr binop x;
3548 if (AtomicBinOp->getOpcode() == BO_Assign) {
3549 X = AtomicBinOp->getLHS();
3550 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3551 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3552 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3553 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3554 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003555 Op = AtomicInnerBinOp->getOpcode();
3556 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003557 auto *LHS = AtomicInnerBinOp->getLHS();
3558 auto *RHS = AtomicInnerBinOp->getRHS();
3559 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3560 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3561 /*Canonical=*/true);
3562 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3563 /*Canonical=*/true);
3564 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3565 /*Canonical=*/true);
3566 if (XId == LHSId) {
3567 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003568 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003569 } else if (XId == RHSId) {
3570 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003571 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003572 } else {
3573 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3574 ErrorRange = AtomicInnerBinOp->getSourceRange();
3575 NoteLoc = X->getExprLoc();
3576 NoteRange = X->getSourceRange();
3577 ErrorFound = NotAnUpdateExpression;
3578 }
3579 } else {
3580 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3581 ErrorRange = AtomicInnerBinOp->getSourceRange();
3582 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3583 NoteRange = SourceRange(NoteLoc, NoteLoc);
3584 ErrorFound = NotABinaryOperator;
3585 }
3586 } else {
3587 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3588 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3589 ErrorFound = NotABinaryExpression;
3590 }
3591 } else {
3592 ErrorLoc = AtomicBinOp->getExprLoc();
3593 ErrorRange = AtomicBinOp->getSourceRange();
3594 NoteLoc = AtomicBinOp->getOperatorLoc();
3595 NoteRange = SourceRange(NoteLoc, NoteLoc);
3596 ErrorFound = NotAnAssignmentOp;
3597 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003598 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003599 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3600 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3601 return true;
3602 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003603 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003604 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003605}
3606
3607bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3608 unsigned NoteId) {
3609 ExprAnalysisErrorCode ErrorFound = NoError;
3610 SourceLocation ErrorLoc, NoteLoc;
3611 SourceRange ErrorRange, NoteRange;
3612 // Allowed constructs are:
3613 // x++;
3614 // x--;
3615 // ++x;
3616 // --x;
3617 // x binop= expr;
3618 // x = x binop expr;
3619 // x = expr binop x;
3620 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3621 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3622 if (AtomicBody->getType()->isScalarType() ||
3623 AtomicBody->isInstantiationDependent()) {
3624 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3625 AtomicBody->IgnoreParenImpCasts())) {
3626 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003627 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003628 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003629 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003630 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003631 X = AtomicCompAssignOp->getLHS();
3632 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003633 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3634 AtomicBody->IgnoreParenImpCasts())) {
3635 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003636 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3637 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003638 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003639 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3640 // Check for Unary Operation
3641 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003642 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003643 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3644 OpLoc = AtomicUnaryOp->getOperatorLoc();
3645 X = AtomicUnaryOp->getSubExpr();
3646 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3647 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003648 } else {
3649 ErrorFound = NotAnUnaryIncDecExpression;
3650 ErrorLoc = AtomicUnaryOp->getExprLoc();
3651 ErrorRange = AtomicUnaryOp->getSourceRange();
3652 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3653 NoteRange = SourceRange(NoteLoc, NoteLoc);
3654 }
3655 } else {
3656 ErrorFound = NotABinaryOrUnaryExpression;
3657 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3658 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3659 }
3660 } else {
3661 ErrorFound = NotAScalarType;
3662 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3663 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3664 }
3665 } else {
3666 ErrorFound = NotAnExpression;
3667 NoteLoc = ErrorLoc = S->getLocStart();
3668 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3669 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003670 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003671 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3672 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3673 return true;
3674 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003675 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003676 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003677 // Build an update expression of form 'OpaqueValueExpr(x) binop
3678 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3679 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3680 auto *OVEX = new (SemaRef.getASTContext())
3681 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3682 auto *OVEExpr = new (SemaRef.getASTContext())
3683 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3684 auto Update =
3685 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3686 IsXLHSInRHSPart ? OVEExpr : OVEX);
3687 if (Update.isInvalid())
3688 return true;
3689 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3690 Sema::AA_Casting);
3691 if (Update.isInvalid())
3692 return true;
3693 UpdateExpr = Update.get();
3694 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003695 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003696}
3697
Alexey Bataev0162e452014-07-22 10:10:35 +00003698StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3699 Stmt *AStmt,
3700 SourceLocation StartLoc,
3701 SourceLocation EndLoc) {
3702 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003703 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003704 // 1.2.2 OpenMP Language Terminology
3705 // Structured block - An executable statement with a single entry at the
3706 // top and a single exit at the bottom.
3707 // The point of exit cannot be a branch out of the structured block.
3708 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003709 OpenMPClauseKind AtomicKind = OMPC_unknown;
3710 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003711 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003712 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003713 C->getClauseKind() == OMPC_update ||
3714 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003715 if (AtomicKind != OMPC_unknown) {
3716 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3717 << SourceRange(C->getLocStart(), C->getLocEnd());
3718 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3719 << getOpenMPClauseName(AtomicKind);
3720 } else {
3721 AtomicKind = C->getClauseKind();
3722 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003723 }
3724 }
3725 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003726
Alexey Bataev459dec02014-07-24 06:46:57 +00003727 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003728 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3729 Body = EWC->getSubExpr();
3730
Alexey Bataev62cec442014-11-18 10:14:22 +00003731 Expr *X = nullptr;
3732 Expr *V = nullptr;
3733 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003734 Expr *UE = nullptr;
3735 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003736 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003737 // OpenMP [2.12.6, atomic Construct]
3738 // In the next expressions:
3739 // * x and v (as applicable) are both l-value expressions with scalar type.
3740 // * During the execution of an atomic region, multiple syntactic
3741 // occurrences of x must designate the same storage location.
3742 // * Neither of v and expr (as applicable) may access the storage location
3743 // designated by x.
3744 // * Neither of x and expr (as applicable) may access the storage location
3745 // designated by v.
3746 // * expr is an expression with scalar type.
3747 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3748 // * binop, binop=, ++, and -- are not overloaded operators.
3749 // * The expression x binop expr must be numerically equivalent to x binop
3750 // (expr). This requirement is satisfied if the operators in expr have
3751 // precedence greater than binop, or by using parentheses around expr or
3752 // subexpressions of expr.
3753 // * The expression expr binop x must be numerically equivalent to (expr)
3754 // binop x. This requirement is satisfied if the operators in expr have
3755 // precedence equal to or greater than binop, or by using parentheses around
3756 // expr or subexpressions of expr.
3757 // * For forms that allow multiple occurrences of x, the number of times
3758 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003759 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003760 enum {
3761 NotAnExpression,
3762 NotAnAssignmentOp,
3763 NotAScalarType,
3764 NotAnLValue,
3765 NoError
3766 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003767 SourceLocation ErrorLoc, NoteLoc;
3768 SourceRange ErrorRange, NoteRange;
3769 // If clause is read:
3770 // v = x;
3771 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3772 auto AtomicBinOp =
3773 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3774 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3775 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3776 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3777 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3778 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3779 if (!X->isLValue() || !V->isLValue()) {
3780 auto NotLValueExpr = X->isLValue() ? V : X;
3781 ErrorFound = NotAnLValue;
3782 ErrorLoc = AtomicBinOp->getExprLoc();
3783 ErrorRange = AtomicBinOp->getSourceRange();
3784 NoteLoc = NotLValueExpr->getExprLoc();
3785 NoteRange = NotLValueExpr->getSourceRange();
3786 }
3787 } else if (!X->isInstantiationDependent() ||
3788 !V->isInstantiationDependent()) {
3789 auto NotScalarExpr =
3790 (X->isInstantiationDependent() || X->getType()->isScalarType())
3791 ? V
3792 : X;
3793 ErrorFound = NotAScalarType;
3794 ErrorLoc = AtomicBinOp->getExprLoc();
3795 ErrorRange = AtomicBinOp->getSourceRange();
3796 NoteLoc = NotScalarExpr->getExprLoc();
3797 NoteRange = NotScalarExpr->getSourceRange();
3798 }
3799 } else {
3800 ErrorFound = NotAnAssignmentOp;
3801 ErrorLoc = AtomicBody->getExprLoc();
3802 ErrorRange = AtomicBody->getSourceRange();
3803 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3804 : AtomicBody->getExprLoc();
3805 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3806 : AtomicBody->getSourceRange();
3807 }
3808 } else {
3809 ErrorFound = NotAnExpression;
3810 NoteLoc = ErrorLoc = Body->getLocStart();
3811 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003812 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003813 if (ErrorFound != NoError) {
3814 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3815 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003816 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3817 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003818 return StmtError();
3819 } else if (CurContext->isDependentContext())
3820 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003821 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003822 enum {
3823 NotAnExpression,
3824 NotAnAssignmentOp,
3825 NotAScalarType,
3826 NotAnLValue,
3827 NoError
3828 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003829 SourceLocation ErrorLoc, NoteLoc;
3830 SourceRange ErrorRange, NoteRange;
3831 // If clause is write:
3832 // x = expr;
3833 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3834 auto AtomicBinOp =
3835 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3836 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003837 X = AtomicBinOp->getLHS();
3838 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003839 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3840 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3841 if (!X->isLValue()) {
3842 ErrorFound = NotAnLValue;
3843 ErrorLoc = AtomicBinOp->getExprLoc();
3844 ErrorRange = AtomicBinOp->getSourceRange();
3845 NoteLoc = X->getExprLoc();
3846 NoteRange = X->getSourceRange();
3847 }
3848 } else if (!X->isInstantiationDependent() ||
3849 !E->isInstantiationDependent()) {
3850 auto NotScalarExpr =
3851 (X->isInstantiationDependent() || X->getType()->isScalarType())
3852 ? E
3853 : X;
3854 ErrorFound = NotAScalarType;
3855 ErrorLoc = AtomicBinOp->getExprLoc();
3856 ErrorRange = AtomicBinOp->getSourceRange();
3857 NoteLoc = NotScalarExpr->getExprLoc();
3858 NoteRange = NotScalarExpr->getSourceRange();
3859 }
3860 } else {
3861 ErrorFound = NotAnAssignmentOp;
3862 ErrorLoc = AtomicBody->getExprLoc();
3863 ErrorRange = AtomicBody->getSourceRange();
3864 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3865 : AtomicBody->getExprLoc();
3866 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3867 : AtomicBody->getSourceRange();
3868 }
3869 } else {
3870 ErrorFound = NotAnExpression;
3871 NoteLoc = ErrorLoc = Body->getLocStart();
3872 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003873 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003874 if (ErrorFound != NoError) {
3875 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3876 << ErrorRange;
3877 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3878 << NoteRange;
3879 return StmtError();
3880 } else if (CurContext->isDependentContext())
3881 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003882 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003883 // If clause is update:
3884 // x++;
3885 // x--;
3886 // ++x;
3887 // --x;
3888 // x binop= expr;
3889 // x = x binop expr;
3890 // x = expr binop x;
3891 OpenMPAtomicUpdateChecker Checker(*this);
3892 if (Checker.checkStatement(
3893 Body, (AtomicKind == OMPC_update)
3894 ? diag::err_omp_atomic_update_not_expression_statement
3895 : diag::err_omp_atomic_not_expression_statement,
3896 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003897 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003898 if (!CurContext->isDependentContext()) {
3899 E = Checker.getExpr();
3900 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003901 UE = Checker.getUpdateExpr();
3902 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003903 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003904 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003905 enum {
3906 NotAnAssignmentOp,
3907 NotACompoundStatement,
3908 NotTwoSubstatements,
3909 NotASpecificExpression,
3910 NoError
3911 } ErrorFound = NoError;
3912 SourceLocation ErrorLoc, NoteLoc;
3913 SourceRange ErrorRange, NoteRange;
3914 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3915 // If clause is a capture:
3916 // v = x++;
3917 // v = x--;
3918 // v = ++x;
3919 // v = --x;
3920 // v = x binop= expr;
3921 // v = x = x binop expr;
3922 // v = x = expr binop x;
3923 auto *AtomicBinOp =
3924 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3925 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3926 V = AtomicBinOp->getLHS();
3927 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3928 OpenMPAtomicUpdateChecker Checker(*this);
3929 if (Checker.checkStatement(
3930 Body, diag::err_omp_atomic_capture_not_expression_statement,
3931 diag::note_omp_atomic_update))
3932 return StmtError();
3933 E = Checker.getExpr();
3934 X = Checker.getX();
3935 UE = Checker.getUpdateExpr();
3936 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3937 IsPostfixUpdate = Checker.isPostfixUpdate();
3938 } else {
3939 ErrorLoc = AtomicBody->getExprLoc();
3940 ErrorRange = AtomicBody->getSourceRange();
3941 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3942 : AtomicBody->getExprLoc();
3943 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3944 : AtomicBody->getSourceRange();
3945 ErrorFound = NotAnAssignmentOp;
3946 }
3947 if (ErrorFound != NoError) {
3948 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3949 << ErrorRange;
3950 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3951 return StmtError();
3952 } else if (CurContext->isDependentContext()) {
3953 UE = V = E = X = nullptr;
3954 }
3955 } else {
3956 // If clause is a capture:
3957 // { v = x; x = expr; }
3958 // { v = x; x++; }
3959 // { v = x; x--; }
3960 // { v = x; ++x; }
3961 // { v = x; --x; }
3962 // { v = x; x binop= expr; }
3963 // { v = x; x = x binop expr; }
3964 // { v = x; x = expr binop x; }
3965 // { x++; v = x; }
3966 // { x--; v = x; }
3967 // { ++x; v = x; }
3968 // { --x; v = x; }
3969 // { x binop= expr; v = x; }
3970 // { x = x binop expr; v = x; }
3971 // { x = expr binop x; v = x; }
3972 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3973 // Check that this is { expr1; expr2; }
3974 if (CS->size() == 2) {
3975 auto *First = CS->body_front();
3976 auto *Second = CS->body_back();
3977 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3978 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3979 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3980 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3981 // Need to find what subexpression is 'v' and what is 'x'.
3982 OpenMPAtomicUpdateChecker Checker(*this);
3983 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3984 BinaryOperator *BinOp = nullptr;
3985 if (IsUpdateExprFound) {
3986 BinOp = dyn_cast<BinaryOperator>(First);
3987 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3988 }
3989 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3990 // { v = x; x++; }
3991 // { v = x; x--; }
3992 // { v = x; ++x; }
3993 // { v = x; --x; }
3994 // { v = x; x binop= expr; }
3995 // { v = x; x = x binop expr; }
3996 // { v = x; x = expr binop x; }
3997 // Check that the first expression has form v = x.
3998 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3999 llvm::FoldingSetNodeID XId, PossibleXId;
4000 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4001 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4002 IsUpdateExprFound = XId == PossibleXId;
4003 if (IsUpdateExprFound) {
4004 V = BinOp->getLHS();
4005 X = Checker.getX();
4006 E = Checker.getExpr();
4007 UE = Checker.getUpdateExpr();
4008 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004009 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004010 }
4011 }
4012 if (!IsUpdateExprFound) {
4013 IsUpdateExprFound = !Checker.checkStatement(First);
4014 BinOp = nullptr;
4015 if (IsUpdateExprFound) {
4016 BinOp = dyn_cast<BinaryOperator>(Second);
4017 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4018 }
4019 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4020 // { x++; v = x; }
4021 // { x--; v = x; }
4022 // { ++x; v = x; }
4023 // { --x; v = x; }
4024 // { x binop= expr; v = x; }
4025 // { x = x binop expr; v = x; }
4026 // { x = expr binop x; v = x; }
4027 // Check that the second expression has form v = x.
4028 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4029 llvm::FoldingSetNodeID XId, PossibleXId;
4030 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4031 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4032 IsUpdateExprFound = XId == PossibleXId;
4033 if (IsUpdateExprFound) {
4034 V = BinOp->getLHS();
4035 X = Checker.getX();
4036 E = Checker.getExpr();
4037 UE = Checker.getUpdateExpr();
4038 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004039 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004040 }
4041 }
4042 }
4043 if (!IsUpdateExprFound) {
4044 // { v = x; x = expr; }
4045 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4046 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
4047 ErrorFound = NotAnAssignmentOp;
4048 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4049 : First->getLocStart();
4050 NoteRange = ErrorRange = FirstBinOp
4051 ? FirstBinOp->getSourceRange()
4052 : SourceRange(ErrorLoc, ErrorLoc);
4053 } else {
4054 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4055 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4056 ErrorFound = NotAnAssignmentOp;
4057 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
4058 : Second->getLocStart();
4059 NoteRange = ErrorRange = SecondBinOp
4060 ? SecondBinOp->getSourceRange()
4061 : SourceRange(ErrorLoc, ErrorLoc);
4062 } else {
4063 auto *PossibleXRHSInFirst =
4064 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4065 auto *PossibleXLHSInSecond =
4066 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4067 llvm::FoldingSetNodeID X1Id, X2Id;
4068 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4069 PossibleXLHSInSecond->Profile(X2Id, Context,
4070 /*Canonical=*/true);
4071 IsUpdateExprFound = X1Id == X2Id;
4072 if (IsUpdateExprFound) {
4073 V = FirstBinOp->getLHS();
4074 X = SecondBinOp->getLHS();
4075 E = SecondBinOp->getRHS();
4076 UE = nullptr;
4077 IsXLHSInRHSPart = false;
4078 IsPostfixUpdate = true;
4079 } else {
4080 ErrorFound = NotASpecificExpression;
4081 ErrorLoc = FirstBinOp->getExprLoc();
4082 ErrorRange = FirstBinOp->getSourceRange();
4083 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4084 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4085 }
4086 }
4087 }
4088 }
4089 } else {
4090 NoteLoc = ErrorLoc = Body->getLocStart();
4091 NoteRange = ErrorRange =
4092 SourceRange(Body->getLocStart(), Body->getLocStart());
4093 ErrorFound = NotTwoSubstatements;
4094 }
4095 } else {
4096 NoteLoc = ErrorLoc = Body->getLocStart();
4097 NoteRange = ErrorRange =
4098 SourceRange(Body->getLocStart(), Body->getLocStart());
4099 ErrorFound = NotACompoundStatement;
4100 }
4101 if (ErrorFound != NoError) {
4102 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4103 << ErrorRange;
4104 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4105 return StmtError();
4106 } else if (CurContext->isDependentContext()) {
4107 UE = V = E = X = nullptr;
4108 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004109 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004110 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004111
4112 getCurFunction()->setHasBranchProtectedScope();
4113
Alexey Bataev62cec442014-11-18 10:14:22 +00004114 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004115 X, V, E, UE, IsXLHSInRHSPart,
4116 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004117}
4118
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004119StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4120 Stmt *AStmt,
4121 SourceLocation StartLoc,
4122 SourceLocation EndLoc) {
4123 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4124
Alexey Bataev13314bf2014-10-09 04:18:56 +00004125 // OpenMP [2.16, Nesting of Regions]
4126 // If specified, a teams construct must be contained within a target
4127 // construct. That target construct must contain no statements or directives
4128 // outside of the teams construct.
4129 if (DSAStack->hasInnerTeamsRegion()) {
4130 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4131 bool OMPTeamsFound = true;
4132 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4133 auto I = CS->body_begin();
4134 while (I != CS->body_end()) {
4135 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4136 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4137 OMPTeamsFound = false;
4138 break;
4139 }
4140 ++I;
4141 }
4142 assert(I != CS->body_end() && "Not found statement");
4143 S = *I;
4144 }
4145 if (!OMPTeamsFound) {
4146 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4147 Diag(DSAStack->getInnerTeamsRegionLoc(),
4148 diag::note_omp_nested_teams_construct_here);
4149 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4150 << isa<OMPExecutableDirective>(S);
4151 return StmtError();
4152 }
4153 }
4154
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004155 getCurFunction()->setHasBranchProtectedScope();
4156
4157 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4158}
4159
Alexey Bataev13314bf2014-10-09 04:18:56 +00004160StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4161 Stmt *AStmt, SourceLocation StartLoc,
4162 SourceLocation EndLoc) {
4163 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4164 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4165 // 1.2.2 OpenMP Language Terminology
4166 // Structured block - An executable statement with a single entry at the
4167 // top and a single exit at the bottom.
4168 // The point of exit cannot be a branch out of the structured block.
4169 // longjmp() and throw() must not violate the entry/exit criteria.
4170 CS->getCapturedDecl()->setNothrow();
4171
4172 getCurFunction()->setHasBranchProtectedScope();
4173
4174 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4175}
4176
Alexey Bataeved09d242014-05-28 05:53:51 +00004177OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004178 SourceLocation StartLoc,
4179 SourceLocation LParenLoc,
4180 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004181 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004182 switch (Kind) {
4183 case OMPC_if:
4184 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4185 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004186 case OMPC_final:
4187 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4188 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004189 case OMPC_num_threads:
4190 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4191 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004192 case OMPC_safelen:
4193 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4194 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004195 case OMPC_collapse:
4196 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4197 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004198 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004199 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004200 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004201 case OMPC_private:
4202 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004203 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004204 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004205 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004206 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004207 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004208 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004209 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004210 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004211 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004212 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004213 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004214 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004215 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004216 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004217 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004218 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004219 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004220 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004221 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004222 llvm_unreachable("Clause is not allowed.");
4223 }
4224 return Res;
4225}
4226
Alexey Bataeved09d242014-05-28 05:53:51 +00004227OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004228 SourceLocation LParenLoc,
4229 SourceLocation EndLoc) {
4230 Expr *ValExpr = Condition;
4231 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4232 !Condition->isInstantiationDependent() &&
4233 !Condition->containsUnexpandedParameterPack()) {
4234 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004235 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004236 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004237 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004238
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004239 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004240 }
4241
4242 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4243}
4244
Alexey Bataev3778b602014-07-17 07:32:53 +00004245OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4246 SourceLocation StartLoc,
4247 SourceLocation LParenLoc,
4248 SourceLocation EndLoc) {
4249 Expr *ValExpr = Condition;
4250 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4251 !Condition->isInstantiationDependent() &&
4252 !Condition->containsUnexpandedParameterPack()) {
4253 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4254 Condition->getExprLoc(), Condition);
4255 if (Val.isInvalid())
4256 return nullptr;
4257
4258 ValExpr = Val.get();
4259 }
4260
4261 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4262}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004263ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4264 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004265 if (!Op)
4266 return ExprError();
4267
4268 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4269 public:
4270 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004271 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004272 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4273 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004274 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4275 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004276 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4277 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004278 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4279 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004280 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4281 QualType T,
4282 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004283 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4284 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004285 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4286 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004287 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004288 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004289 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004290 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4291 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004292 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4293 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004294 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4295 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004296 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004297 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004298 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004299 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4300 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004301 llvm_unreachable("conversion functions are permitted");
4302 }
4303 } ConvertDiagnoser;
4304 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4305}
4306
4307OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4308 SourceLocation StartLoc,
4309 SourceLocation LParenLoc,
4310 SourceLocation EndLoc) {
4311 Expr *ValExpr = NumThreads;
4312 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004313 !NumThreads->containsUnexpandedParameterPack()) {
4314 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4315 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004316 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004317 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004318 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004319
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004320 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004321
4322 // OpenMP [2.5, Restrictions]
4323 // The num_threads expression must evaluate to a positive integer value.
4324 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004325 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4326 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004327 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4328 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004329 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004330 }
4331 }
4332
Alexey Bataeved09d242014-05-28 05:53:51 +00004333 return new (Context)
4334 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004335}
4336
Alexey Bataev62c87d22014-03-21 04:51:18 +00004337ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4338 OpenMPClauseKind CKind) {
4339 if (!E)
4340 return ExprError();
4341 if (E->isValueDependent() || E->isTypeDependent() ||
4342 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004343 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004344 llvm::APSInt Result;
4345 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4346 if (ICE.isInvalid())
4347 return ExprError();
4348 if (!Result.isStrictlyPositive()) {
4349 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4350 << getOpenMPClauseName(CKind) << E->getSourceRange();
4351 return ExprError();
4352 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004353 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4354 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4355 << E->getSourceRange();
4356 return ExprError();
4357 }
Alexey Bataev9c821032015-04-30 04:23:23 +00004358 if (CKind == OMPC_collapse) {
4359 DSAStack->setCollapseNumber(Result.getExtValue());
4360 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004361 return ICE;
4362}
4363
4364OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4365 SourceLocation LParenLoc,
4366 SourceLocation EndLoc) {
4367 // OpenMP [2.8.1, simd construct, Description]
4368 // The parameter of the safelen clause must be a constant
4369 // positive integer expression.
4370 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4371 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004372 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004373 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004374 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004375}
4376
Alexander Musman64d33f12014-06-04 07:53:32 +00004377OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4378 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004379 SourceLocation LParenLoc,
4380 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004381 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004382 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004383 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004384 // The parameter of the collapse clause must be a constant
4385 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004386 ExprResult NumForLoopsResult =
4387 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4388 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004389 return nullptr;
4390 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004391 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004392}
4393
Alexey Bataeved09d242014-05-28 05:53:51 +00004394OMPClause *Sema::ActOnOpenMPSimpleClause(
4395 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4396 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004397 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004398 switch (Kind) {
4399 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004400 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004401 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4402 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004403 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004404 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004405 Res = ActOnOpenMPProcBindClause(
4406 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4407 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004408 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004409 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004410 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004411 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004412 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004413 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004414 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004415 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004416 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004417 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004418 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004419 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004420 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004421 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004422 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004423 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004424 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004425 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004426 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004427 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004428 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004429 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004430 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004431 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004432 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004433 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004434 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004435 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004436 llvm_unreachable("Clause is not allowed.");
4437 }
4438 return Res;
4439}
4440
4441OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4442 SourceLocation KindKwLoc,
4443 SourceLocation StartLoc,
4444 SourceLocation LParenLoc,
4445 SourceLocation EndLoc) {
4446 if (Kind == OMPC_DEFAULT_unknown) {
4447 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004448 static_assert(OMPC_DEFAULT_unknown > 0,
4449 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004450 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004451 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004452 Values += "'";
4453 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4454 Values += "'";
4455 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004456 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004457 Values += " or ";
4458 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004459 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004460 break;
4461 default:
4462 Values += Sep;
4463 break;
4464 }
4465 }
4466 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004467 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004468 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004469 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004470 switch (Kind) {
4471 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004472 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004473 break;
4474 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004475 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004476 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004477 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004478 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004479 break;
4480 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004481 return new (Context)
4482 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004483}
4484
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004485OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4486 SourceLocation KindKwLoc,
4487 SourceLocation StartLoc,
4488 SourceLocation LParenLoc,
4489 SourceLocation EndLoc) {
4490 if (Kind == OMPC_PROC_BIND_unknown) {
4491 std::string Values;
4492 std::string Sep(", ");
4493 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4494 Values += "'";
4495 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4496 Values += "'";
4497 switch (i) {
4498 case OMPC_PROC_BIND_unknown - 2:
4499 Values += " or ";
4500 break;
4501 case OMPC_PROC_BIND_unknown - 1:
4502 break;
4503 default:
4504 Values += Sep;
4505 break;
4506 }
4507 }
4508 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004509 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004510 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004511 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004512 return new (Context)
4513 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004514}
4515
Alexey Bataev56dafe82014-06-20 07:16:17 +00004516OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4517 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4518 SourceLocation StartLoc, SourceLocation LParenLoc,
4519 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4520 SourceLocation EndLoc) {
4521 OMPClause *Res = nullptr;
4522 switch (Kind) {
4523 case OMPC_schedule:
4524 Res = ActOnOpenMPScheduleClause(
4525 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4526 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4527 break;
4528 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004529 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004530 case OMPC_num_threads:
4531 case OMPC_safelen:
4532 case OMPC_collapse:
4533 case OMPC_default:
4534 case OMPC_proc_bind:
4535 case OMPC_private:
4536 case OMPC_firstprivate:
4537 case OMPC_lastprivate:
4538 case OMPC_shared:
4539 case OMPC_reduction:
4540 case OMPC_linear:
4541 case OMPC_aligned:
4542 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004543 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004544 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004545 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004546 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004547 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004548 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004549 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004550 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004551 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004552 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004553 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004554 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004555 case OMPC_unknown:
4556 llvm_unreachable("Clause is not allowed.");
4557 }
4558 return Res;
4559}
4560
4561OMPClause *Sema::ActOnOpenMPScheduleClause(
4562 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4563 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4564 SourceLocation EndLoc) {
4565 if (Kind == OMPC_SCHEDULE_unknown) {
4566 std::string Values;
4567 std::string Sep(", ");
4568 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4569 Values += "'";
4570 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4571 Values += "'";
4572 switch (i) {
4573 case OMPC_SCHEDULE_unknown - 2:
4574 Values += " or ";
4575 break;
4576 case OMPC_SCHEDULE_unknown - 1:
4577 break;
4578 default:
4579 Values += Sep;
4580 break;
4581 }
4582 }
4583 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4584 << Values << getOpenMPClauseName(OMPC_schedule);
4585 return nullptr;
4586 }
4587 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00004588 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004589 if (ChunkSize) {
4590 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4591 !ChunkSize->isInstantiationDependent() &&
4592 !ChunkSize->containsUnexpandedParameterPack()) {
4593 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4594 ExprResult Val =
4595 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4596 if (Val.isInvalid())
4597 return nullptr;
4598
4599 ValExpr = Val.get();
4600
4601 // OpenMP [2.7.1, Restrictions]
4602 // chunk_size must be a loop invariant integer expression with a positive
4603 // value.
4604 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00004605 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4606 if (Result.isSigned() && !Result.isStrictlyPositive()) {
4607 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4608 << "schedule" << ChunkSize->getSourceRange();
4609 return nullptr;
4610 }
4611 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4612 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4613 ChunkSize->getType(), ".chunk.");
4614 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4615 ChunkSize->getExprLoc(),
4616 /*RefersToCapture=*/true);
4617 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004618 }
4619 }
4620 }
4621
4622 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00004623 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00004624}
4625
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004626OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4627 SourceLocation StartLoc,
4628 SourceLocation EndLoc) {
4629 OMPClause *Res = nullptr;
4630 switch (Kind) {
4631 case OMPC_ordered:
4632 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4633 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004634 case OMPC_nowait:
4635 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4636 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004637 case OMPC_untied:
4638 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4639 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004640 case OMPC_mergeable:
4641 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4642 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004643 case OMPC_read:
4644 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4645 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004646 case OMPC_write:
4647 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4648 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004649 case OMPC_update:
4650 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4651 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004652 case OMPC_capture:
4653 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4654 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004655 case OMPC_seq_cst:
4656 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4657 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004658 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004659 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004660 case OMPC_num_threads:
4661 case OMPC_safelen:
4662 case OMPC_collapse:
4663 case OMPC_schedule:
4664 case OMPC_private:
4665 case OMPC_firstprivate:
4666 case OMPC_lastprivate:
4667 case OMPC_shared:
4668 case OMPC_reduction:
4669 case OMPC_linear:
4670 case OMPC_aligned:
4671 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004672 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004673 case OMPC_default:
4674 case OMPC_proc_bind:
4675 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004676 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004677 case OMPC_unknown:
4678 llvm_unreachable("Clause is not allowed.");
4679 }
4680 return Res;
4681}
4682
4683OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4684 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004685 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004686 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4687}
4688
Alexey Bataev236070f2014-06-20 11:19:47 +00004689OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4690 SourceLocation EndLoc) {
4691 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4692}
4693
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004694OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4695 SourceLocation EndLoc) {
4696 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4697}
4698
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004699OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4700 SourceLocation EndLoc) {
4701 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4702}
4703
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004704OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4705 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004706 return new (Context) OMPReadClause(StartLoc, EndLoc);
4707}
4708
Alexey Bataevdea47612014-07-23 07:46:59 +00004709OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4710 SourceLocation EndLoc) {
4711 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4712}
4713
Alexey Bataev67a4f222014-07-23 10:25:33 +00004714OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4715 SourceLocation EndLoc) {
4716 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4717}
4718
Alexey Bataev459dec02014-07-24 06:46:57 +00004719OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4720 SourceLocation EndLoc) {
4721 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4722}
4723
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004724OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4725 SourceLocation EndLoc) {
4726 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4727}
4728
Alexey Bataevc5e02582014-06-16 07:08:35 +00004729OMPClause *Sema::ActOnOpenMPVarListClause(
4730 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4731 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4732 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4733 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004734 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004735 switch (Kind) {
4736 case OMPC_private:
4737 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4738 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004739 case OMPC_firstprivate:
4740 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4741 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004742 case OMPC_lastprivate:
4743 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4744 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004745 case OMPC_shared:
4746 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4747 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004748 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004749 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4750 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004751 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004752 case OMPC_linear:
4753 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4754 ColonLoc, EndLoc);
4755 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004756 case OMPC_aligned:
4757 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4758 ColonLoc, EndLoc);
4759 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004760 case OMPC_copyin:
4761 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4762 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004763 case OMPC_copyprivate:
4764 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4765 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004766 case OMPC_flush:
4767 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4768 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004769 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004770 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004771 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004772 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004773 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004774 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004775 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004776 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004777 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004778 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004779 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004780 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004781 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004782 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004783 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004784 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004785 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004786 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004787 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004788 llvm_unreachable("Clause is not allowed.");
4789 }
4790 return Res;
4791}
4792
4793OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4794 SourceLocation StartLoc,
4795 SourceLocation LParenLoc,
4796 SourceLocation EndLoc) {
4797 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004798 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004799 for (auto &RefExpr : VarList) {
4800 assert(RefExpr && "NULL expr in OpenMP private clause.");
4801 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004802 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004803 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004804 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004805 continue;
4806 }
4807
Alexey Bataeved09d242014-05-28 05:53:51 +00004808 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004809 // OpenMP [2.1, C/C++]
4810 // A list item is a variable name.
4811 // OpenMP [2.9.3.3, Restrictions, p.1]
4812 // A variable that is part of another variable (as an array or
4813 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004814 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004815 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004816 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004817 continue;
4818 }
4819 Decl *D = DE->getDecl();
4820 VarDecl *VD = cast<VarDecl>(D);
4821
4822 QualType Type = VD->getType();
4823 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4824 // It will be analyzed later.
4825 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004826 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004827 continue;
4828 }
4829
4830 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4831 // A variable that appears in a private clause must not have an incomplete
4832 // type or a reference type.
4833 if (RequireCompleteType(ELoc, Type,
4834 diag::err_omp_private_incomplete_type)) {
4835 continue;
4836 }
4837 if (Type->isReferenceType()) {
4838 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004839 << getOpenMPClauseName(OMPC_private) << Type;
4840 bool IsDecl =
4841 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4842 Diag(VD->getLocation(),
4843 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4844 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004845 continue;
4846 }
4847
Alexey Bataev758e55e2013-09-06 18:03:48 +00004848 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4849 // in a Construct]
4850 // Variables with the predetermined data-sharing attributes may not be
4851 // listed in data-sharing attributes clauses, except for the cases
4852 // listed below. For these exceptions only, listing a predetermined
4853 // variable in a data-sharing attribute clause is allowed and overrides
4854 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004855 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004856 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004857 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4858 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004859 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004860 continue;
4861 }
4862
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004863 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00004864 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004865 DSAStack->getCurrentDirective() == OMPD_task) {
4866 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
4867 << getOpenMPClauseName(OMPC_private) << Type
4868 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4869 bool IsDecl =
4870 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4871 Diag(VD->getLocation(),
4872 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4873 << VD;
4874 continue;
4875 }
4876
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004877 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4878 // A variable of class type (or array thereof) that appears in a private
4879 // clause requires an accessible, unambiguous default constructor for the
4880 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004881 // Generate helper private variable and initialize it with the default
4882 // value. The address of the original variable is replaced by the address of
4883 // the new private variable in CodeGen. This new variable is not added to
4884 // IdResolver, so the code in the OpenMP region uses original variable for
4885 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004886 Type = Type.getUnqualifiedType();
4887 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
Alexey Bataev39f915b82015-05-08 10:41:21 +00004888 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004889 if (VDPrivate->isInvalidDecl())
4890 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004891 auto VDPrivateRefExpr = buildDeclRefExpr(
4892 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00004893
Alexey Bataev758e55e2013-09-06 18:03:48 +00004894 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004895 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004896 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004897 }
4898
Alexey Bataeved09d242014-05-28 05:53:51 +00004899 if (Vars.empty())
4900 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004901
Alexey Bataev03b340a2014-10-21 03:16:40 +00004902 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4903 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004904}
4905
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004906namespace {
4907class DiagsUninitializedSeveretyRAII {
4908private:
4909 DiagnosticsEngine &Diags;
4910 SourceLocation SavedLoc;
4911 bool IsIgnored;
4912
4913public:
4914 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4915 bool IsIgnored)
4916 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4917 if (!IsIgnored) {
4918 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4919 /*Map*/ diag::Severity::Ignored, Loc);
4920 }
4921 }
4922 ~DiagsUninitializedSeveretyRAII() {
4923 if (!IsIgnored)
4924 Diags.popMappings(SavedLoc);
4925 }
4926};
4927}
4928
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004929OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4930 SourceLocation StartLoc,
4931 SourceLocation LParenLoc,
4932 SourceLocation EndLoc) {
4933 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004934 SmallVector<Expr *, 8> PrivateCopies;
4935 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004936 bool IsImplicitClause =
4937 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4938 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4939
Alexey Bataeved09d242014-05-28 05:53:51 +00004940 for (auto &RefExpr : VarList) {
4941 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4942 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004943 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004944 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004945 PrivateCopies.push_back(nullptr);
4946 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004947 continue;
4948 }
4949
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004950 SourceLocation ELoc =
4951 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004952 // OpenMP [2.1, C/C++]
4953 // A list item is a variable name.
4954 // OpenMP [2.9.3.3, Restrictions, p.1]
4955 // A variable that is part of another variable (as an array or
4956 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004957 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004958 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004959 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004960 continue;
4961 }
4962 Decl *D = DE->getDecl();
4963 VarDecl *VD = cast<VarDecl>(D);
4964
4965 QualType Type = VD->getType();
4966 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4967 // It will be analyzed later.
4968 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004969 PrivateCopies.push_back(nullptr);
4970 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004971 continue;
4972 }
4973
4974 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4975 // A variable that appears in a private clause must not have an incomplete
4976 // type or a reference type.
4977 if (RequireCompleteType(ELoc, Type,
4978 diag::err_omp_firstprivate_incomplete_type)) {
4979 continue;
4980 }
4981 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004982 if (IsImplicitClause) {
4983 Diag(ImplicitClauseLoc,
4984 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4985 << Type;
4986 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4987 } else {
4988 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4989 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4990 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004991 bool IsDecl =
4992 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4993 Diag(VD->getLocation(),
4994 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4995 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004996 continue;
4997 }
4998
4999 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5000 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00005001 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005002 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005003 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005004
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005005 // If an implicit firstprivate variable found it was checked already.
5006 if (!IsImplicitClause) {
5007 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005008 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005009 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5010 // A list item that specifies a given variable may not appear in more
5011 // than one clause on the same directive, except that a variable may be
5012 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005013 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00005014 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005015 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005016 << getOpenMPClauseName(DVar.CKind)
5017 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005018 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005019 continue;
5020 }
5021
5022 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5023 // in a Construct]
5024 // Variables with the predetermined data-sharing attributes may not be
5025 // listed in data-sharing attributes clauses, except for the cases
5026 // listed below. For these exceptions only, listing a predetermined
5027 // variable in a data-sharing attribute clause is allowed and overrides
5028 // the variable's predetermined data-sharing attributes.
5029 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5030 // in a Construct, C/C++, p.2]
5031 // Variables with const-qualified type having no mutable member may be
5032 // listed in a firstprivate clause, even if they are static data members.
5033 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5034 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
5035 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005036 << getOpenMPClauseName(DVar.CKind)
5037 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005038 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005039 continue;
5040 }
5041
Alexey Bataevf29276e2014-06-18 04:14:57 +00005042 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005043 // OpenMP [2.9.3.4, Restrictions, p.2]
5044 // A list item that is private within a parallel region must not appear
5045 // in a firstprivate clause on a worksharing construct if any of the
5046 // worksharing regions arising from the worksharing construct ever bind
5047 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00005048 if (isOpenMPWorksharingDirective(CurrDir) &&
5049 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005050 DVar = DSAStack->getImplicitDSA(VD, true);
5051 if (DVar.CKind != OMPC_shared &&
5052 (isOpenMPParallelDirective(DVar.DKind) ||
5053 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005054 Diag(ELoc, diag::err_omp_required_access)
5055 << getOpenMPClauseName(OMPC_firstprivate)
5056 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005057 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005058 continue;
5059 }
5060 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005061 // OpenMP [2.9.3.4, Restrictions, p.3]
5062 // A list item that appears in a reduction clause of a parallel construct
5063 // must not appear in a firstprivate clause on a worksharing or task
5064 // construct if any of the worksharing or task regions arising from the
5065 // worksharing or task construct ever bind to any of the parallel regions
5066 // arising from the parallel construct.
5067 // OpenMP [2.9.3.4, Restrictions, p.4]
5068 // A list item that appears in a reduction clause in worksharing
5069 // construct must not appear in a firstprivate clause in a task construct
5070 // encountered during execution of any of the worksharing regions arising
5071 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005072 if (CurrDir == OMPD_task) {
5073 DVar =
5074 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5075 [](OpenMPDirectiveKind K) -> bool {
5076 return isOpenMPParallelDirective(K) ||
5077 isOpenMPWorksharingDirective(K);
5078 },
5079 false);
5080 if (DVar.CKind == OMPC_reduction &&
5081 (isOpenMPParallelDirective(DVar.DKind) ||
5082 isOpenMPWorksharingDirective(DVar.DKind))) {
5083 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5084 << getOpenMPDirectiveName(DVar.DKind);
5085 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5086 continue;
5087 }
5088 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005089 }
5090
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005091 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005092 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005093 DSAStack->getCurrentDirective() == OMPD_task) {
5094 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5095 << getOpenMPClauseName(OMPC_firstprivate) << Type
5096 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5097 bool IsDecl =
5098 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5099 Diag(VD->getLocation(),
5100 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5101 << VD;
5102 continue;
5103 }
5104
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005105 Type = Type.getUnqualifiedType();
5106 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005107 // Generate helper private variable and initialize it with the value of the
5108 // original variable. The address of the original variable is replaced by
5109 // the address of the new private variable in the CodeGen. This new variable
5110 // is not added to IdResolver, so the code in the OpenMP region uses
5111 // original variable for proper diagnostics and variable capturing.
5112 Expr *VDInitRefExpr = nullptr;
5113 // For arrays generate initializer for single element and replace it by the
5114 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005115 if (Type->isArrayType()) {
5116 auto VDInit =
5117 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5118 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005119 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005120 ElemType = ElemType.getUnqualifiedType();
5121 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5122 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00005123 InitializedEntity Entity =
5124 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005125 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5126
5127 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5128 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5129 if (Result.isInvalid())
5130 VDPrivate->setInvalidDecl();
5131 else
5132 VDPrivate->setInit(Result.getAs<Expr>());
5133 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00005134 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005135 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005136 VDInitRefExpr =
5137 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00005138 AddInitializerToDecl(VDPrivate,
5139 DefaultLvalueConversion(VDInitRefExpr).get(),
5140 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005141 }
5142 if (VDPrivate->isInvalidDecl()) {
5143 if (IsImplicitClause) {
5144 Diag(DE->getExprLoc(),
5145 diag::note_omp_task_predetermined_firstprivate_here);
5146 }
5147 continue;
5148 }
5149 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005150 auto VDPrivateRefExpr = buildDeclRefExpr(
5151 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005152 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5153 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005154 PrivateCopies.push_back(VDPrivateRefExpr);
5155 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005156 }
5157
Alexey Bataeved09d242014-05-28 05:53:51 +00005158 if (Vars.empty())
5159 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005160
5161 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005162 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005163}
5164
Alexander Musman1bb328c2014-06-04 13:06:39 +00005165OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5166 SourceLocation StartLoc,
5167 SourceLocation LParenLoc,
5168 SourceLocation EndLoc) {
5169 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00005170 SmallVector<Expr *, 8> SrcExprs;
5171 SmallVector<Expr *, 8> DstExprs;
5172 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005173 for (auto &RefExpr : VarList) {
5174 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5175 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5176 // It will be analyzed later.
5177 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00005178 SrcExprs.push_back(nullptr);
5179 DstExprs.push_back(nullptr);
5180 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005181 continue;
5182 }
5183
5184 SourceLocation ELoc = RefExpr->getExprLoc();
5185 // OpenMP [2.1, C/C++]
5186 // A list item is a variable name.
5187 // OpenMP [2.14.3.5, Restrictions, p.1]
5188 // A variable that is part of another variable (as an array or structure
5189 // element) cannot appear in a lastprivate clause.
5190 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5191 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5192 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5193 continue;
5194 }
5195 Decl *D = DE->getDecl();
5196 VarDecl *VD = cast<VarDecl>(D);
5197
5198 QualType Type = VD->getType();
5199 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5200 // It will be analyzed later.
5201 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005202 SrcExprs.push_back(nullptr);
5203 DstExprs.push_back(nullptr);
5204 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005205 continue;
5206 }
5207
5208 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5209 // A variable that appears in a lastprivate clause must not have an
5210 // incomplete type or a reference type.
5211 if (RequireCompleteType(ELoc, Type,
5212 diag::err_omp_lastprivate_incomplete_type)) {
5213 continue;
5214 }
5215 if (Type->isReferenceType()) {
5216 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5217 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5218 bool IsDecl =
5219 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5220 Diag(VD->getLocation(),
5221 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5222 << VD;
5223 continue;
5224 }
5225
5226 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5227 // in a Construct]
5228 // Variables with the predetermined data-sharing attributes may not be
5229 // listed in data-sharing attributes clauses, except for the cases
5230 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005231 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005232 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5233 DVar.CKind != OMPC_firstprivate &&
5234 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5235 Diag(ELoc, diag::err_omp_wrong_dsa)
5236 << getOpenMPClauseName(DVar.CKind)
5237 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005238 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005239 continue;
5240 }
5241
Alexey Bataevf29276e2014-06-18 04:14:57 +00005242 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5243 // OpenMP [2.14.3.5, Restrictions, p.2]
5244 // A list item that is private within a parallel region, or that appears in
5245 // the reduction clause of a parallel construct, must not appear in a
5246 // lastprivate clause on a worksharing construct if any of the corresponding
5247 // worksharing regions ever binds to any of the corresponding parallel
5248 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005249 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00005250 if (isOpenMPWorksharingDirective(CurrDir) &&
5251 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005252 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005253 if (DVar.CKind != OMPC_shared) {
5254 Diag(ELoc, diag::err_omp_required_access)
5255 << getOpenMPClauseName(OMPC_lastprivate)
5256 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005257 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005258 continue;
5259 }
5260 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005261 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005262 // A variable of class type (or array thereof) that appears in a
5263 // lastprivate clause requires an accessible, unambiguous default
5264 // constructor for the class type, unless the list item is also specified
5265 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005266 // A variable of class type (or array thereof) that appears in a
5267 // lastprivate clause requires an accessible, unambiguous copy assignment
5268 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005269 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005270 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev38e89532015-04-16 04:54:05 +00005271 Type.getUnqualifiedType(), ".lastprivate.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00005272 auto *PseudoSrcExpr = buildDeclRefExpr(
5273 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005274 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005275 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
Alexey Bataev38e89532015-04-16 04:54:05 +00005276 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005277 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005278 // For arrays generate assignment operation for single element and replace
5279 // it by the original array element in CodeGen.
5280 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5281 PseudoDstExpr, PseudoSrcExpr);
5282 if (AssignmentOp.isInvalid())
5283 continue;
5284 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5285 /*DiscardedValue=*/true);
5286 if (AssignmentOp.isInvalid())
5287 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005288
Alexey Bataev39f915b82015-05-08 10:41:21 +00005289 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005290 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005291 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005292 SrcExprs.push_back(PseudoSrcExpr);
5293 DstExprs.push_back(PseudoDstExpr);
5294 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005295 }
5296
5297 if (Vars.empty())
5298 return nullptr;
5299
5300 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005301 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005302}
5303
Alexey Bataev758e55e2013-09-06 18:03:48 +00005304OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5305 SourceLocation StartLoc,
5306 SourceLocation LParenLoc,
5307 SourceLocation EndLoc) {
5308 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005309 for (auto &RefExpr : VarList) {
5310 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5311 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005312 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005313 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005314 continue;
5315 }
5316
Alexey Bataeved09d242014-05-28 05:53:51 +00005317 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005318 // OpenMP [2.1, C/C++]
5319 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005320 // OpenMP [2.14.3.2, Restrictions, p.1]
5321 // A variable that is part of another variable (as an array or structure
5322 // element) cannot appear in a shared unless it is a static data member
5323 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005324 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005325 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005326 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005327 continue;
5328 }
5329 Decl *D = DE->getDecl();
5330 VarDecl *VD = cast<VarDecl>(D);
5331
5332 QualType Type = VD->getType();
5333 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5334 // It will be analyzed later.
5335 Vars.push_back(DE);
5336 continue;
5337 }
5338
5339 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5340 // in a Construct]
5341 // Variables with the predetermined data-sharing attributes may not be
5342 // listed in data-sharing attributes clauses, except for the cases
5343 // listed below. For these exceptions only, listing a predetermined
5344 // variable in a data-sharing attribute clause is allowed and overrides
5345 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005346 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005347 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5348 DVar.RefExpr) {
5349 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5350 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005351 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005352 continue;
5353 }
5354
5355 DSAStack->addDSA(VD, DE, OMPC_shared);
5356 Vars.push_back(DE);
5357 }
5358
Alexey Bataeved09d242014-05-28 05:53:51 +00005359 if (Vars.empty())
5360 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005361
5362 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5363}
5364
Alexey Bataevc5e02582014-06-16 07:08:35 +00005365namespace {
5366class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5367 DSAStackTy *Stack;
5368
5369public:
5370 bool VisitDeclRefExpr(DeclRefExpr *E) {
5371 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005372 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005373 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5374 return false;
5375 if (DVar.CKind != OMPC_unknown)
5376 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005377 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005378 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005379 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005380 return true;
5381 return false;
5382 }
5383 return false;
5384 }
5385 bool VisitStmt(Stmt *S) {
5386 for (auto Child : S->children()) {
5387 if (Child && Visit(Child))
5388 return true;
5389 }
5390 return false;
5391 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005392 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005393};
Alexey Bataev23b69422014-06-18 07:08:49 +00005394} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005395
5396OMPClause *Sema::ActOnOpenMPReductionClause(
5397 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5398 SourceLocation ColonLoc, SourceLocation EndLoc,
5399 CXXScopeSpec &ReductionIdScopeSpec,
5400 const DeclarationNameInfo &ReductionId) {
5401 // TODO: Allow scope specification search when 'declare reduction' is
5402 // supported.
5403 assert(ReductionIdScopeSpec.isEmpty() &&
5404 "No support for scoped reduction identifiers yet.");
5405
5406 auto DN = ReductionId.getName();
5407 auto OOK = DN.getCXXOverloadedOperator();
5408 BinaryOperatorKind BOK = BO_Comma;
5409
5410 // OpenMP [2.14.3.6, reduction clause]
5411 // C
5412 // reduction-identifier is either an identifier or one of the following
5413 // operators: +, -, *, &, |, ^, && and ||
5414 // C++
5415 // reduction-identifier is either an id-expression or one of the following
5416 // operators: +, -, *, &, |, ^, && and ||
5417 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5418 switch (OOK) {
5419 case OO_Plus:
5420 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005421 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005422 break;
5423 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005424 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005425 break;
5426 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005427 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005428 break;
5429 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005430 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005431 break;
5432 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005433 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005434 break;
5435 case OO_AmpAmp:
5436 BOK = BO_LAnd;
5437 break;
5438 case OO_PipePipe:
5439 BOK = BO_LOr;
5440 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005441 case OO_New:
5442 case OO_Delete:
5443 case OO_Array_New:
5444 case OO_Array_Delete:
5445 case OO_Slash:
5446 case OO_Percent:
5447 case OO_Tilde:
5448 case OO_Exclaim:
5449 case OO_Equal:
5450 case OO_Less:
5451 case OO_Greater:
5452 case OO_LessEqual:
5453 case OO_GreaterEqual:
5454 case OO_PlusEqual:
5455 case OO_MinusEqual:
5456 case OO_StarEqual:
5457 case OO_SlashEqual:
5458 case OO_PercentEqual:
5459 case OO_CaretEqual:
5460 case OO_AmpEqual:
5461 case OO_PipeEqual:
5462 case OO_LessLess:
5463 case OO_GreaterGreater:
5464 case OO_LessLessEqual:
5465 case OO_GreaterGreaterEqual:
5466 case OO_EqualEqual:
5467 case OO_ExclaimEqual:
5468 case OO_PlusPlus:
5469 case OO_MinusMinus:
5470 case OO_Comma:
5471 case OO_ArrowStar:
5472 case OO_Arrow:
5473 case OO_Call:
5474 case OO_Subscript:
5475 case OO_Conditional:
5476 case NUM_OVERLOADED_OPERATORS:
5477 llvm_unreachable("Unexpected reduction identifier");
5478 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005479 if (auto II = DN.getAsIdentifierInfo()) {
5480 if (II->isStr("max"))
5481 BOK = BO_GT;
5482 else if (II->isStr("min"))
5483 BOK = BO_LT;
5484 }
5485 break;
5486 }
5487 SourceRange ReductionIdRange;
5488 if (ReductionIdScopeSpec.isValid()) {
5489 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5490 }
5491 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5492 if (BOK == BO_Comma) {
5493 // Not allowed reduction identifier is found.
5494 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5495 << ReductionIdRange;
5496 return nullptr;
5497 }
5498
5499 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005500 SmallVector<Expr *, 8> LHSs;
5501 SmallVector<Expr *, 8> RHSs;
5502 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005503 for (auto RefExpr : VarList) {
5504 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5505 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5506 // It will be analyzed later.
5507 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005508 LHSs.push_back(nullptr);
5509 RHSs.push_back(nullptr);
5510 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005511 continue;
5512 }
5513
5514 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5515 RefExpr->isInstantiationDependent() ||
5516 RefExpr->containsUnexpandedParameterPack()) {
5517 // It will be analyzed later.
5518 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005519 LHSs.push_back(nullptr);
5520 RHSs.push_back(nullptr);
5521 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005522 continue;
5523 }
5524
5525 auto ELoc = RefExpr->getExprLoc();
5526 auto ERange = RefExpr->getSourceRange();
5527 // OpenMP [2.1, C/C++]
5528 // A list item is a variable or array section, subject to the restrictions
5529 // specified in Section 2.4 on page 42 and in each of the sections
5530 // describing clauses and directives for which a list appears.
5531 // OpenMP [2.14.3.3, Restrictions, p.1]
5532 // A variable that is part of another variable (as an array or
5533 // structure element) cannot appear in a private clause.
5534 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5535 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5536 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5537 continue;
5538 }
5539 auto D = DE->getDecl();
5540 auto VD = cast<VarDecl>(D);
5541 auto Type = VD->getType();
5542 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5543 // A variable that appears in a private clause must not have an incomplete
5544 // type or a reference type.
5545 if (RequireCompleteType(ELoc, Type,
5546 diag::err_omp_reduction_incomplete_type))
5547 continue;
5548 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5549 // Arrays may not appear in a reduction clause.
5550 if (Type.getNonReferenceType()->isArrayType()) {
5551 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5552 bool IsDecl =
5553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5554 Diag(VD->getLocation(),
5555 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5556 << VD;
5557 continue;
5558 }
5559 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5560 // A list item that appears in a reduction clause must not be
5561 // const-qualified.
5562 if (Type.getNonReferenceType().isConstant(Context)) {
5563 Diag(ELoc, diag::err_omp_const_variable)
5564 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5565 bool IsDecl =
5566 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5567 Diag(VD->getLocation(),
5568 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5569 << VD;
5570 continue;
5571 }
5572 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5573 // If a list-item is a reference type then it must bind to the same object
5574 // for all threads of the team.
5575 VarDecl *VDDef = VD->getDefinition();
5576 if (Type->isReferenceType() && VDDef) {
5577 DSARefChecker Check(DSAStack);
5578 if (Check.Visit(VDDef->getInit())) {
5579 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5580 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5581 continue;
5582 }
5583 }
5584 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5585 // The type of a list item that appears in a reduction clause must be valid
5586 // for the reduction-identifier. For a max or min reduction in C, the type
5587 // of the list item must be an allowed arithmetic data type: char, int,
5588 // float, double, or _Bool, possibly modified with long, short, signed, or
5589 // unsigned. For a max or min reduction in C++, the type of the list item
5590 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5591 // double, or bool, possibly modified with long, short, signed, or unsigned.
5592 if ((BOK == BO_GT || BOK == BO_LT) &&
5593 !(Type->isScalarType() ||
5594 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5595 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5596 << getLangOpts().CPlusPlus;
5597 bool IsDecl =
5598 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5599 Diag(VD->getLocation(),
5600 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5601 << VD;
5602 continue;
5603 }
5604 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5605 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5606 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5607 bool IsDecl =
5608 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5609 Diag(VD->getLocation(),
5610 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5611 << VD;
5612 continue;
5613 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005614 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5615 // in a Construct]
5616 // Variables with the predetermined data-sharing attributes may not be
5617 // listed in data-sharing attributes clauses, except for the cases
5618 // listed below. For these exceptions only, listing a predetermined
5619 // variable in a data-sharing attribute clause is allowed and overrides
5620 // the variable's predetermined data-sharing attributes.
5621 // OpenMP [2.14.3.6, Restrictions, p.3]
5622 // Any number of reduction clauses can be specified on the directive,
5623 // but a list item can appear only once in the reduction clauses for that
5624 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005625 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005626 if (DVar.CKind == OMPC_reduction) {
5627 Diag(ELoc, diag::err_omp_once_referenced)
5628 << getOpenMPClauseName(OMPC_reduction);
5629 if (DVar.RefExpr) {
5630 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5631 }
5632 } else if (DVar.CKind != OMPC_unknown) {
5633 Diag(ELoc, diag::err_omp_wrong_dsa)
5634 << getOpenMPClauseName(DVar.CKind)
5635 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005636 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005637 continue;
5638 }
5639
5640 // OpenMP [2.14.3.6, Restrictions, p.1]
5641 // A list item that appears in a reduction clause of a worksharing
5642 // construct must be shared in the parallel regions to which any of the
5643 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005644 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005645 if (isOpenMPWorksharingDirective(CurrDir) &&
5646 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005647 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005648 if (DVar.CKind != OMPC_shared) {
5649 Diag(ELoc, diag::err_omp_required_access)
5650 << getOpenMPClauseName(OMPC_reduction)
5651 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005652 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005653 continue;
5654 }
5655 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005656 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005657 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5658 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005659 // Add initializer for private variable.
5660 Expr *Init = nullptr;
5661 switch (BOK) {
5662 case BO_Add:
5663 case BO_Xor:
5664 case BO_Or:
5665 case BO_LOr:
5666 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5667 if (Type->isScalarType() || Type->isAnyComplexType()) {
5668 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005669 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005670 break;
5671 case BO_Mul:
5672 case BO_LAnd:
5673 if (Type->isScalarType() || Type->isAnyComplexType()) {
5674 // '*' and '&&' reduction ops - initializer is '1'.
5675 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5676 }
5677 break;
5678 case BO_And: {
5679 // '&' reduction op - initializer is '~0'.
5680 QualType OrigType = Type;
5681 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5682 Type = ComplexTy->getElementType();
5683 }
5684 if (Type->isRealFloatingType()) {
5685 llvm::APFloat InitValue =
5686 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5687 /*isIEEE=*/true);
5688 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5689 Type, ELoc);
5690 } else if (Type->isScalarType()) {
5691 auto Size = Context.getTypeSize(Type);
5692 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5693 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5694 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5695 }
5696 if (Init && OrigType->isAnyComplexType()) {
5697 // Init = 0xFFFF + 0xFFFFi;
5698 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5699 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5700 }
5701 Type = OrigType;
5702 break;
5703 }
5704 case BO_LT:
5705 case BO_GT: {
5706 // 'min' reduction op - initializer is 'Largest representable number in
5707 // the reduction list item type'.
5708 // 'max' reduction op - initializer is 'Least representable number in
5709 // the reduction list item type'.
5710 if (Type->isIntegerType() || Type->isPointerType()) {
5711 bool IsSigned = Type->hasSignedIntegerRepresentation();
5712 auto Size = Context.getTypeSize(Type);
5713 QualType IntTy =
5714 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5715 llvm::APInt InitValue =
5716 (BOK != BO_LT)
5717 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5718 : llvm::APInt::getMinValue(Size)
5719 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5720 : llvm::APInt::getMaxValue(Size);
5721 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5722 if (Type->isPointerType()) {
5723 // Cast to pointer type.
5724 auto CastExpr = BuildCStyleCastExpr(
5725 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5726 SourceLocation(), Init);
5727 if (CastExpr.isInvalid())
5728 continue;
5729 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005730 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005731 } else if (Type->isRealFloatingType()) {
5732 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5733 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5734 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5735 Type, ELoc);
5736 }
5737 break;
5738 }
5739 case BO_PtrMemD:
5740 case BO_PtrMemI:
5741 case BO_MulAssign:
5742 case BO_Div:
5743 case BO_Rem:
5744 case BO_Sub:
5745 case BO_Shl:
5746 case BO_Shr:
5747 case BO_LE:
5748 case BO_GE:
5749 case BO_EQ:
5750 case BO_NE:
5751 case BO_AndAssign:
5752 case BO_XorAssign:
5753 case BO_OrAssign:
5754 case BO_Assign:
5755 case BO_AddAssign:
5756 case BO_SubAssign:
5757 case BO_DivAssign:
5758 case BO_RemAssign:
5759 case BO_ShlAssign:
5760 case BO_ShrAssign:
5761 case BO_Comma:
5762 llvm_unreachable("Unexpected reduction operation");
5763 }
5764 if (Init) {
5765 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5766 /*TypeMayContainAuto=*/false);
5767 } else {
5768 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5769 }
5770 if (!RHSVD->hasInit()) {
5771 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5772 << ReductionIdRange;
5773 bool IsDecl =
5774 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5775 Diag(VD->getLocation(),
5776 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5777 << VD;
5778 continue;
5779 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00005780 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5781 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005782 ExprResult ReductionOp =
5783 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5784 LHSDRE, RHSDRE);
5785 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00005786 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005787 ReductionOp =
5788 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5789 BO_Assign, LHSDRE, ReductionOp.get());
5790 } else {
5791 auto *ConditionalOp = new (Context) ConditionalOperator(
5792 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5793 RHSDRE, Type, VK_LValue, OK_Ordinary);
5794 ReductionOp =
5795 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5796 BO_Assign, LHSDRE, ConditionalOp);
5797 }
5798 if (ReductionOp.isUsable()) {
5799 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005800 }
5801 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005802 if (ReductionOp.isInvalid())
5803 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005804
5805 DSAStack->addDSA(VD, DE, OMPC_reduction);
5806 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005807 LHSs.push_back(LHSDRE);
5808 RHSs.push_back(RHSDRE);
5809 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005810 }
5811
5812 if (Vars.empty())
5813 return nullptr;
5814
5815 return OMPReductionClause::Create(
5816 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005817 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5818 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005819}
5820
Alexander Musman8dba6642014-04-22 13:09:42 +00005821OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5822 SourceLocation StartLoc,
5823 SourceLocation LParenLoc,
5824 SourceLocation ColonLoc,
5825 SourceLocation EndLoc) {
5826 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005827 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005828 for (auto &RefExpr : VarList) {
5829 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5830 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005831 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005832 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005833 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005834 continue;
5835 }
5836
5837 // OpenMP [2.14.3.7, linear clause]
5838 // A list item that appears in a linear clause is subject to the private
5839 // clause semantics described in Section 2.14.3.3 on page 159 except as
5840 // noted. In addition, the value of the new list item on each iteration
5841 // of the associated loop(s) corresponds to the value of the original
5842 // list item before entering the construct plus the logical number of
5843 // the iteration times linear-step.
5844
Alexey Bataeved09d242014-05-28 05:53:51 +00005845 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005846 // OpenMP [2.1, C/C++]
5847 // A list item is a variable name.
5848 // OpenMP [2.14.3.3, Restrictions, p.1]
5849 // A variable that is part of another variable (as an array or
5850 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005851 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005852 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005853 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005854 continue;
5855 }
5856
5857 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5858
5859 // OpenMP [2.14.3.7, linear clause]
5860 // A list-item cannot appear in more than one linear clause.
5861 // A list-item that appears in a linear clause cannot appear in any
5862 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005863 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005864 if (DVar.RefExpr) {
5865 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5866 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005867 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005868 continue;
5869 }
5870
5871 QualType QType = VD->getType();
5872 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5873 // It will be analyzed later.
5874 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005875 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005876 continue;
5877 }
5878
5879 // A variable must not have an incomplete type or a reference type.
5880 if (RequireCompleteType(ELoc, QType,
5881 diag::err_omp_linear_incomplete_type)) {
5882 continue;
5883 }
5884 if (QType->isReferenceType()) {
5885 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5886 << getOpenMPClauseName(OMPC_linear) << QType;
5887 bool IsDecl =
5888 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5889 Diag(VD->getLocation(),
5890 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5891 << VD;
5892 continue;
5893 }
5894
5895 // A list item must not be const-qualified.
5896 if (QType.isConstant(Context)) {
5897 Diag(ELoc, diag::err_omp_const_variable)
5898 << getOpenMPClauseName(OMPC_linear);
5899 bool IsDecl =
5900 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5901 Diag(VD->getLocation(),
5902 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5903 << VD;
5904 continue;
5905 }
5906
5907 // A list item must be of integral or pointer type.
5908 QType = QType.getUnqualifiedType().getCanonicalType();
5909 const Type *Ty = QType.getTypePtrOrNull();
5910 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5911 !Ty->isPointerType())) {
5912 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5913 bool IsDecl =
5914 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5915 Diag(VD->getLocation(),
5916 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5917 << VD;
5918 continue;
5919 }
5920
Alexander Musman3276a272015-03-21 10:12:56 +00005921 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005922 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexander Musman3276a272015-03-21 10:12:56 +00005923 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5924 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005925 auto InitRef = buildDeclRefExpr(
5926 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00005927 DSAStack->addDSA(VD, DE, OMPC_linear);
5928 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005929 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005930 }
5931
5932 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005933 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005934
5935 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005936 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005937 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5938 !Step->isInstantiationDependent() &&
5939 !Step->containsUnexpandedParameterPack()) {
5940 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005941 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005942 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005943 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005944 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005945
Alexander Musman3276a272015-03-21 10:12:56 +00005946 // Build var to save the step value.
5947 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005948 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00005949 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005950 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00005951 ExprResult CalcStep =
5952 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5953
Alexander Musman8dba6642014-04-22 13:09:42 +00005954 // Warn about zero linear step (it would be probably better specified as
5955 // making corresponding variables 'const').
5956 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005957 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5958 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005959 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5960 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005961 if (!IsConstant && CalcStep.isUsable()) {
5962 // Calculate the step beforehand instead of doing this on each iteration.
5963 // (This is not used if the number of iterations may be kfold-ed).
5964 CalcStepExpr = CalcStep.get();
5965 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005966 }
5967
5968 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005969 Vars, Inits, StepExpr, CalcStepExpr);
5970}
5971
5972static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5973 Expr *NumIterations, Sema &SemaRef,
5974 Scope *S) {
5975 // Walk the vars and build update/final expressions for the CodeGen.
5976 SmallVector<Expr *, 8> Updates;
5977 SmallVector<Expr *, 8> Finals;
5978 Expr *Step = Clause.getStep();
5979 Expr *CalcStep = Clause.getCalcStep();
5980 // OpenMP [2.14.3.7, linear clause]
5981 // If linear-step is not specified it is assumed to be 1.
5982 if (Step == nullptr)
5983 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5984 else if (CalcStep)
5985 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5986 bool HasErrors = false;
5987 auto CurInit = Clause.inits().begin();
5988 for (auto &RefExpr : Clause.varlists()) {
5989 Expr *InitExpr = *CurInit;
5990
5991 // Build privatized reference to the current linear var.
5992 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005993 auto PrivateRef =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005994 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
5995 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
5996 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00005997
5998 // Build update: Var = InitExpr + IV * Step
5999 ExprResult Update =
6000 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6001 InitExpr, IV, Step, /* Subtract */ false);
6002 Update = SemaRef.ActOnFinishFullExpr(Update.get());
6003
6004 // Build final: Var = InitExpr + NumIterations * Step
6005 ExprResult Final =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006006 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6007 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexander Musman3276a272015-03-21 10:12:56 +00006008 Final = SemaRef.ActOnFinishFullExpr(Final.get());
6009 if (!Update.isUsable() || !Final.isUsable()) {
6010 Updates.push_back(nullptr);
6011 Finals.push_back(nullptr);
6012 HasErrors = true;
6013 } else {
6014 Updates.push_back(Update.get());
6015 Finals.push_back(Final.get());
6016 }
6017 ++CurInit;
6018 }
6019 Clause.setUpdates(Updates);
6020 Clause.setFinals(Finals);
6021 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00006022}
6023
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006024OMPClause *Sema::ActOnOpenMPAlignedClause(
6025 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
6026 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
6027
6028 SmallVector<Expr *, 8> Vars;
6029 for (auto &RefExpr : VarList) {
6030 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
6031 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6032 // It will be analyzed later.
6033 Vars.push_back(RefExpr);
6034 continue;
6035 }
6036
6037 SourceLocation ELoc = RefExpr->getExprLoc();
6038 // OpenMP [2.1, C/C++]
6039 // A list item is a variable name.
6040 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6041 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6042 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6043 continue;
6044 }
6045
6046 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6047
6048 // OpenMP [2.8.1, simd construct, Restrictions]
6049 // The type of list items appearing in the aligned clause must be
6050 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006051 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006052 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006053 const Type *Ty = QType.getTypePtrOrNull();
6054 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6055 !Ty->isPointerType())) {
6056 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6057 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6058 bool IsDecl =
6059 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6060 Diag(VD->getLocation(),
6061 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6062 << VD;
6063 continue;
6064 }
6065
6066 // OpenMP [2.8.1, simd construct, Restrictions]
6067 // A list-item cannot appear in more than one aligned clause.
6068 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6069 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6070 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6071 << getOpenMPClauseName(OMPC_aligned);
6072 continue;
6073 }
6074
6075 Vars.push_back(DE);
6076 }
6077
6078 // OpenMP [2.8.1, simd construct, Description]
6079 // The parameter of the aligned clause, alignment, must be a constant
6080 // positive integer expression.
6081 // If no optional parameter is specified, implementation-defined default
6082 // alignments for SIMD instructions on the target platforms are assumed.
6083 if (Alignment != nullptr) {
6084 ExprResult AlignResult =
6085 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6086 if (AlignResult.isInvalid())
6087 return nullptr;
6088 Alignment = AlignResult.get();
6089 }
6090 if (Vars.empty())
6091 return nullptr;
6092
6093 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6094 EndLoc, Vars, Alignment);
6095}
6096
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006097OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6098 SourceLocation StartLoc,
6099 SourceLocation LParenLoc,
6100 SourceLocation EndLoc) {
6101 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006102 SmallVector<Expr *, 8> SrcExprs;
6103 SmallVector<Expr *, 8> DstExprs;
6104 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00006105 for (auto &RefExpr : VarList) {
6106 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6107 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006108 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006109 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006110 SrcExprs.push_back(nullptr);
6111 DstExprs.push_back(nullptr);
6112 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006113 continue;
6114 }
6115
Alexey Bataeved09d242014-05-28 05:53:51 +00006116 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006117 // OpenMP [2.1, C/C++]
6118 // A list item is a variable name.
6119 // OpenMP [2.14.4.1, Restrictions, p.1]
6120 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00006121 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006122 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006123 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006124 continue;
6125 }
6126
6127 Decl *D = DE->getDecl();
6128 VarDecl *VD = cast<VarDecl>(D);
6129
6130 QualType Type = VD->getType();
6131 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6132 // It will be analyzed later.
6133 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006134 SrcExprs.push_back(nullptr);
6135 DstExprs.push_back(nullptr);
6136 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006137 continue;
6138 }
6139
6140 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6141 // A list item that appears in a copyin clause must be threadprivate.
6142 if (!DSAStack->isThreadPrivate(VD)) {
6143 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00006144 << getOpenMPClauseName(OMPC_copyin)
6145 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006146 continue;
6147 }
6148
6149 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6150 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00006151 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006152 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006153 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006154 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006155 ElemType.getUnqualifiedType(), ".copyin.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00006156 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006157 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6158 auto *DstVD =
6159 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006160 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006161 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006162 // For arrays generate assignment operation for single element and replace
6163 // it by the original array element in CodeGen.
6164 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6165 PseudoDstExpr, PseudoSrcExpr);
6166 if (AssignmentOp.isInvalid())
6167 continue;
6168 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6169 /*DiscardedValue=*/true);
6170 if (AssignmentOp.isInvalid())
6171 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006172
6173 DSAStack->addDSA(VD, DE, OMPC_copyin);
6174 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006175 SrcExprs.push_back(PseudoSrcExpr);
6176 DstExprs.push_back(PseudoDstExpr);
6177 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006178 }
6179
Alexey Bataeved09d242014-05-28 05:53:51 +00006180 if (Vars.empty())
6181 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006182
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006183 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6184 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006185}
6186
Alexey Bataevbae9a792014-06-27 10:37:06 +00006187OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6188 SourceLocation StartLoc,
6189 SourceLocation LParenLoc,
6190 SourceLocation EndLoc) {
6191 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006192 SmallVector<Expr *, 8> SrcExprs;
6193 SmallVector<Expr *, 8> DstExprs;
6194 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006195 for (auto &RefExpr : VarList) {
6196 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6197 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6198 // It will be analyzed later.
6199 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006200 SrcExprs.push_back(nullptr);
6201 DstExprs.push_back(nullptr);
6202 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006203 continue;
6204 }
6205
6206 SourceLocation ELoc = RefExpr->getExprLoc();
6207 // OpenMP [2.1, C/C++]
6208 // A list item is a variable name.
6209 // OpenMP [2.14.4.1, Restrictions, p.1]
6210 // A list item that appears in a copyin clause must be threadprivate.
6211 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6212 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6213 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6214 continue;
6215 }
6216
6217 Decl *D = DE->getDecl();
6218 VarDecl *VD = cast<VarDecl>(D);
6219
6220 QualType Type = VD->getType();
6221 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6222 // It will be analyzed later.
6223 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006224 SrcExprs.push_back(nullptr);
6225 DstExprs.push_back(nullptr);
6226 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006227 continue;
6228 }
6229
6230 // OpenMP [2.14.4.2, Restrictions, p.2]
6231 // A list item that appears in a copyprivate clause may not appear in a
6232 // private or firstprivate clause on the single construct.
6233 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006234 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006235 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6236 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006237 Diag(ELoc, diag::err_omp_wrong_dsa)
6238 << getOpenMPClauseName(DVar.CKind)
6239 << getOpenMPClauseName(OMPC_copyprivate);
6240 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6241 continue;
6242 }
6243
6244 // OpenMP [2.11.4.2, Restrictions, p.1]
6245 // All list items that appear in a copyprivate clause must be either
6246 // threadprivate or private in the enclosing context.
6247 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006248 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006249 if (DVar.CKind == OMPC_shared) {
6250 Diag(ELoc, diag::err_omp_required_access)
6251 << getOpenMPClauseName(OMPC_copyprivate)
6252 << "threadprivate or private in the enclosing context";
6253 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6254 continue;
6255 }
6256 }
6257 }
6258
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006259 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00006260 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006261 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006262 << getOpenMPClauseName(OMPC_copyprivate) << Type
6263 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006264 bool IsDecl =
6265 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6266 Diag(VD->getLocation(),
6267 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6268 << VD;
6269 continue;
6270 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006271
Alexey Bataevbae9a792014-06-27 10:37:06 +00006272 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6273 // A variable of class type (or array thereof) that appears in a
6274 // copyin clause requires an accessible, unambiguous copy assignment
6275 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006276 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6277 auto *SrcVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006278 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006279 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006280 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00006281 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006282 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006283 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006284 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00006285 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6286 PseudoDstExpr, PseudoSrcExpr);
6287 if (AssignmentOp.isInvalid())
6288 continue;
6289 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6290 /*DiscardedValue=*/true);
6291 if (AssignmentOp.isInvalid())
6292 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006293
6294 // No need to mark vars as copyprivate, they are already threadprivate or
6295 // implicitly private.
6296 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006297 SrcExprs.push_back(PseudoSrcExpr);
6298 DstExprs.push_back(PseudoDstExpr);
6299 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006300 }
6301
6302 if (Vars.empty())
6303 return nullptr;
6304
Alexey Bataeva63048e2015-03-23 06:18:07 +00006305 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6306 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006307}
6308
Alexey Bataev6125da92014-07-21 11:26:11 +00006309OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6310 SourceLocation StartLoc,
6311 SourceLocation LParenLoc,
6312 SourceLocation EndLoc) {
6313 if (VarList.empty())
6314 return nullptr;
6315
6316 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6317}
Alexey Bataevdea47612014-07-23 07:46:59 +00006318