blob: 4e45705ca1decbabbc4d4dd1a4fe2a5991bfd0f6 [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.
Alexey Bataevaac108a2015-06-23 04:51:00 +0000119 OpenMPClauseKind ClauseKindMode;
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 Bataevaac108a2015-06-23 04:51:00 +0000130 explicit DSAStackTy(Sema &S)
131 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000132
Alexey Bataevaac108a2015-06-23 04:51:00 +0000133 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
134 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000135
136 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000137 Scope *CurScope, SourceLocation Loc) {
138 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
139 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000140 }
141
142 void pop() {
143 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
144 Stack.pop_back();
145 }
146
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000147 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000148 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000149 /// for diagnostics.
150 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
151
Alexey Bataev9c821032015-04-30 04:23:23 +0000152 /// \brief Register specified variable as loop control variable.
153 void addLoopControlVariable(VarDecl *D);
154 /// \brief Check if the specified variable is a loop control variable for
155 /// current region.
156 bool isLoopControlVariable(VarDecl *D);
157
Alexey Bataev758e55e2013-09-06 18:03:48 +0000158 /// \brief Adds explicit data sharing attribute to the specified declaration.
159 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
160
Alexey Bataev758e55e2013-09-06 18:03:48 +0000161 /// \brief Returns data sharing attributes from top of the stack for the
162 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000163 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000164 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000165 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000166 /// \brief Checks if the specified variables has data-sharing attributes which
167 /// match specified \a CPred predicate in any directive which matches \a DPred
168 /// predicate.
169 template <class ClausesPredicate, class DirectivesPredicate>
170 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000171 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000172 /// \brief Checks if the specified variables has data-sharing attributes which
173 /// match specified \a CPred predicate in any innermost directive which
174 /// matches \a DPred predicate.
175 template <class ClausesPredicate, class DirectivesPredicate>
176 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000177 DirectivesPredicate DPred,
178 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000179 /// \brief Checks if the specified variables has explicit data-sharing
180 /// attributes which match specified \a CPred predicate at the specified
181 /// OpenMP region.
182 bool hasExplicitDSA(VarDecl *D,
183 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
184 unsigned Level);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000185 /// \brief Finds a directive which matches specified \a DPred predicate.
186 template <class NamedDirectivesPredicate>
187 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000188
Alexey Bataev758e55e2013-09-06 18:03:48 +0000189 /// \brief Returns currently analyzed directive.
190 OpenMPDirectiveKind getCurrentDirective() const {
191 return Stack.back().Directive;
192 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000193 /// \brief Returns parent directive.
194 OpenMPDirectiveKind getParentDirective() const {
195 if (Stack.size() > 2)
196 return Stack[Stack.size() - 2].Directive;
197 return OMPD_unknown;
198 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000199
200 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000201 void setDefaultDSANone(SourceLocation Loc) {
202 Stack.back().DefaultAttr = DSA_none;
203 Stack.back().DefaultAttrLoc = Loc;
204 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000205 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000206 void setDefaultDSAShared(SourceLocation Loc) {
207 Stack.back().DefaultAttr = DSA_shared;
208 Stack.back().DefaultAttrLoc = Loc;
209 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000210
211 DefaultDataSharingAttributes getDefaultDSA() const {
212 return Stack.back().DefaultAttr;
213 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000214 SourceLocation getDefaultDSALocation() const {
215 return Stack.back().DefaultAttrLoc;
216 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000217
Alexey Bataevf29276e2014-06-18 04:14:57 +0000218 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000219 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000220 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000221 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000222 }
223
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000224 /// \brief Marks current region as ordered (it has an 'ordered' clause).
225 void setOrderedRegion(bool IsOrdered = true) {
226 Stack.back().OrderedRegion = IsOrdered;
227 }
228 /// \brief Returns true, if parent region is ordered (has associated
229 /// 'ordered' clause), false - otherwise.
230 bool isParentOrderedRegion() const {
231 if (Stack.size() > 2)
232 return Stack[Stack.size() - 2].OrderedRegion;
233 return false;
234 }
235
Alexey Bataev9c821032015-04-30 04:23:23 +0000236 /// \brief Set collapse value for the region.
237 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
238 /// \brief Return collapse value for region.
239 unsigned getCollapseNumber() const {
240 return Stack.back().CollapseNumber;
241 }
242
Alexey Bataev13314bf2014-10-09 04:18:56 +0000243 /// \brief Marks current target region as one with closely nested teams
244 /// region.
245 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
246 if (Stack.size() > 2)
247 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
248 }
249 /// \brief Returns true, if current region has closely nested teams region.
250 bool hasInnerTeamsRegion() const {
251 return getInnerTeamsRegionLoc().isValid();
252 }
253 /// \brief Returns location of the nested teams region (if any).
254 SourceLocation getInnerTeamsRegionLoc() const {
255 if (Stack.size() > 1)
256 return Stack.back().InnerTeamsRegionLoc;
257 return SourceLocation();
258 }
259
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000261 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000262 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000263};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000264bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
265 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000266 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000267}
Alexey Bataeved09d242014-05-28 05:53:51 +0000268} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000269
270DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
271 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000272 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000273 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000274 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000275 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
276 // in a region but not in construct]
277 // File-scope or namespace-scope variables referenced in called routines
278 // in the region are shared unless they appear in a threadprivate
279 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000280 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000281 DVar.CKind = OMPC_shared;
282
283 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
284 // in a region but not in construct]
285 // Variables with static storage duration that are declared in called
286 // routines in the region are shared.
287 if (D->hasGlobalStorage())
288 DVar.CKind = OMPC_shared;
289
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290 return DVar;
291 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000292
Alexey Bataev758e55e2013-09-06 18:03:48 +0000293 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000294 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
295 // in a Construct, C/C++, predetermined, p.1]
296 // Variables with automatic storage duration that are declared in a scope
297 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000298 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
299 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
300 DVar.CKind = OMPC_private;
301 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000302 }
303
Alexey Bataev758e55e2013-09-06 18:03:48 +0000304 // Explicitly specified attributes and local variables with predetermined
305 // attributes.
306 if (Iter->SharingMap.count(D)) {
307 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
308 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000309 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000310 return DVar;
311 }
312
313 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
314 // in a Construct, C/C++, implicitly determined, p.1]
315 // In a parallel or task construct, the data-sharing attributes of these
316 // variables are determined by the default clause, if present.
317 switch (Iter->DefaultAttr) {
318 case DSA_shared:
319 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000320 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000321 return DVar;
322 case DSA_none:
323 return DVar;
324 case DSA_unspecified:
325 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
326 // in a Construct, implicitly determined, p.2]
327 // In a parallel construct, if no default clause is present, these
328 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000329 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000330 if (isOpenMPParallelDirective(DVar.DKind) ||
331 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000332 DVar.CKind = OMPC_shared;
333 return DVar;
334 }
335
336 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
337 // in a Construct, implicitly determined, p.4]
338 // In a task construct, if no default clause is present, a variable that in
339 // the enclosing context is determined to be shared by all implicit tasks
340 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000341 if (DVar.DKind == OMPD_task) {
342 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000343 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000344 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000345 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
346 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000347 // in a Construct, implicitly determined, p.6]
348 // In a task construct, if no default clause is present, a variable
349 // whose data-sharing attribute is not determined by the rules above is
350 // firstprivate.
351 DVarTemp = getDSA(I, D);
352 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000353 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000354 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000355 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000356 return DVar;
357 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000358 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000359 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000360 }
361 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000362 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000363 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000364 return DVar;
365 }
366 }
367 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
368 // in a Construct, implicitly determined, p.3]
369 // For constructs other than task, if no default clause is present, these
370 // variables inherit their data-sharing attributes from the enclosing
371 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000372 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000373}
374
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000375DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
376 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000377 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000378 auto It = Stack.back().AlignedMap.find(D);
379 if (It == Stack.back().AlignedMap.end()) {
380 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
381 Stack.back().AlignedMap[D] = NewDE;
382 return nullptr;
383 } else {
384 assert(It->second && "Unexpected nullptr expr in the aligned map");
385 return It->second;
386 }
387 return nullptr;
388}
389
Alexey Bataev9c821032015-04-30 04:23:23 +0000390void DSAStackTy::addLoopControlVariable(VarDecl *D) {
391 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
392 D = D->getCanonicalDecl();
393 Stack.back().LCVSet.insert(D);
394}
395
396bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
397 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
398 D = D->getCanonicalDecl();
399 return Stack.back().LCVSet.count(D) > 0;
400}
401
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000403 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000404 if (A == OMPC_threadprivate) {
405 Stack[0].SharingMap[D].Attributes = A;
406 Stack[0].SharingMap[D].RefExpr = E;
407 } else {
408 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
409 Stack.back().SharingMap[D].Attributes = A;
410 Stack.back().SharingMap[D].RefExpr = E;
411 }
412}
413
Alexey Bataeved09d242014-05-28 05:53:51 +0000414bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000415 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000416 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000417 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000418 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000419 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000420 ++I;
421 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000422 if (I == E)
423 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000424 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000425 Scope *CurScope = getCurScope();
426 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000427 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000428 }
429 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000430 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000431 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000432}
433
Alexey Bataev39f915b82015-05-08 10:41:21 +0000434/// \brief Build a variable declaration for OpenMP loop iteration variable.
435static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
436 StringRef Name) {
437 DeclContext *DC = SemaRef.CurContext;
438 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
439 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
440 VarDecl *Decl =
441 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
442 Decl->setImplicit();
443 return Decl;
444}
445
446static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
447 SourceLocation Loc,
448 bool RefersToCapture = false) {
449 D->setReferenced();
450 D->markUsed(S.Context);
451 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
452 SourceLocation(), D, RefersToCapture, Loc, Ty,
453 VK_LValue);
454}
455
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000456DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000457 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DSAVarData DVar;
459
460 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
461 // in a Construct, C/C++, predetermined, p.1]
462 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000463 if (D->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000464 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
465 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000466 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
467 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000468 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000469 }
470 if (Stack[0].SharingMap.count(D)) {
471 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
472 DVar.CKind = OMPC_threadprivate;
473 return DVar;
474 }
475
476 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
477 // in a Construct, C/C++, predetermined, p.1]
478 // Variables with automatic storage duration that are declared in a scope
479 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000480 OpenMPDirectiveKind Kind =
481 FromParent ? getParentDirective() : getCurrentDirective();
482 auto StartI = std::next(Stack.rbegin());
483 auto EndI = std::prev(Stack.rend());
484 if (FromParent && StartI != EndI) {
485 StartI = std::next(StartI);
486 }
487 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000488 if (isOpenMPLocal(D, StartI) &&
489 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
490 D->getStorageClass() == SC_None)) ||
491 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000492 DVar.CKind = OMPC_private;
493 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000494 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000495
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000496 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
497 // in a Construct, C/C++, predetermined, p.4]
498 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000499 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
500 // in a Construct, C/C++, predetermined, p.7]
501 // Variables with static storage duration that are declared in a scope
502 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000503 if (D->isStaticDataMember() || D->isStaticLocal()) {
504 DSAVarData DVarTemp =
505 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
506 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
507 return DVar;
508
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000509 DVar.CKind = OMPC_shared;
510 return DVar;
511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000512 }
513
514 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000515 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
516 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000517 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
518 // in a Construct, C/C++, predetermined, p.6]
519 // Variables with const qualified type having no mutable member are
520 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000521 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000522 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000523 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000524 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000525 // Variables with const-qualified type having no mutable member may be
526 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000527 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
528 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000529 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
530 return DVar;
531
Alexey Bataev758e55e2013-09-06 18:03:48 +0000532 DVar.CKind = OMPC_shared;
533 return DVar;
534 }
535
Alexey Bataev758e55e2013-09-06 18:03:48 +0000536 // Explicitly specified attributes and local variables with predetermined
537 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000538 auto I = std::prev(StartI);
539 if (I->SharingMap.count(D)) {
540 DVar.RefExpr = I->SharingMap[D].RefExpr;
541 DVar.CKind = I->SharingMap[D].Attributes;
542 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000543 }
544
545 return DVar;
546}
547
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000548DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000549 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000550 auto StartI = Stack.rbegin();
551 auto EndI = std::prev(Stack.rend());
552 if (FromParent && StartI != EndI) {
553 StartI = std::next(StartI);
554 }
555 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000556}
557
Alexey Bataevf29276e2014-06-18 04:14:57 +0000558template <class ClausesPredicate, class DirectivesPredicate>
559DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000560 DirectivesPredicate DPred,
561 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000562 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000563 auto StartI = std::next(Stack.rbegin());
564 auto EndI = std::prev(Stack.rend());
565 if (FromParent && StartI != EndI) {
566 StartI = std::next(StartI);
567 }
568 for (auto I = StartI, EE = EndI; I != EE; ++I) {
569 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000570 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000571 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000572 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000573 return DVar;
574 }
575 return DSAVarData();
576}
577
Alexey Bataevf29276e2014-06-18 04:14:57 +0000578template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000579DSAStackTy::DSAVarData
580DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
581 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000582 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000583 auto StartI = std::next(Stack.rbegin());
584 auto EndI = std::prev(Stack.rend());
585 if (FromParent && StartI != EndI) {
586 StartI = std::next(StartI);
587 }
588 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000589 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000590 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000591 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000592 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000593 return DVar;
594 return DSAVarData();
595 }
596 return DSAVarData();
597}
598
Alexey Bataevaac108a2015-06-23 04:51:00 +0000599bool DSAStackTy::hasExplicitDSA(
600 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
601 unsigned Level) {
602 if (CPred(ClauseKindMode))
603 return true;
604 if (isClauseParsingMode())
605 ++Level;
606 D = D->getCanonicalDecl();
607 auto StartI = Stack.rbegin();
608 auto EndI = std::prev(Stack.rend());
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000609 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000610 return false;
611 std::advance(StartI, Level);
612 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
613 CPred(StartI->SharingMap[D].Attributes);
614}
615
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000616template <class NamedDirectivesPredicate>
617bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
618 auto StartI = std::next(Stack.rbegin());
619 auto EndI = std::prev(Stack.rend());
620 if (FromParent && StartI != EndI) {
621 StartI = std::next(StartI);
622 }
623 for (auto I = StartI, EE = EndI; I != EE; ++I) {
624 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
625 return true;
626 }
627 return false;
628}
629
Alexey Bataev758e55e2013-09-06 18:03:48 +0000630void Sema::InitDataSharingAttributesStack() {
631 VarDataSharingAttributesStack = new DSAStackTy(*this);
632}
633
634#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
635
Alexey Bataevf841bd92014-12-16 07:00:22 +0000636bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
637 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000638 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000639 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000640 if (DSAStack->isLoopControlVariable(VD) ||
641 (VD->hasLocalStorage() &&
642 isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
Alexey Bataev9c821032015-04-30 04:23:23 +0000643 return true;
Alexey Bataevaac108a2015-06-23 04:51:00 +0000644 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000645 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
646 return true;
647 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataevaac108a2015-06-23 04:51:00 +0000648 DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000649 return DVarPrivate.CKind != OMPC_unknown;
650 }
651 return false;
652}
653
Alexey Bataevaac108a2015-06-23 04:51:00 +0000654bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
655 assert(LangOpts.OpenMP && "OpenMP is not allowed");
656 return DSAStack->hasExplicitDSA(
657 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
658}
659
Alexey Bataeved09d242014-05-28 05:53:51 +0000660void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000661
662void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
663 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000664 Scope *CurScope, SourceLocation Loc) {
665 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000666 PushExpressionEvaluationContext(PotentiallyEvaluated);
667}
668
Alexey Bataevaac108a2015-06-23 04:51:00 +0000669void Sema::StartOpenMPClause(OpenMPClauseKind K) {
670 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000671}
672
Alexey Bataevaac108a2015-06-23 04:51:00 +0000673void Sema::EndOpenMPClause() {
674 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000675}
676
Alexey Bataev758e55e2013-09-06 18:03:48 +0000677void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000678 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
679 // A variable of class type (or array thereof) that appears in a lastprivate
680 // clause requires an accessible, unambiguous default constructor for the
681 // class type, unless the list item is also specified in a firstprivate
682 // clause.
683 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000684 for (auto *C : D->clauses()) {
685 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
686 SmallVector<Expr *, 8> PrivateCopies;
687 for (auto *DE : Clause->varlists()) {
688 if (DE->isValueDependent() || DE->isTypeDependent()) {
689 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000690 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000691 }
692 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000693 QualType Type = VD->getType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000694 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000695 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000696 // Generate helper private variable and initialize it with the
697 // default value. The address of the original variable is replaced
698 // by the address of the new private variable in CodeGen. This new
699 // variable is not added to IdResolver, so the code in the OpenMP
700 // region uses original variable for proper diagnostics.
Alexey Bataev39f915b82015-05-08 10:41:21 +0000701 auto *VDPrivate =
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000702 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
703 VD->getName());
Alexey Bataev38e89532015-04-16 04:54:05 +0000704 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
705 if (VDPrivate->isInvalidDecl())
706 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000707 PrivateCopies.push_back(buildDeclRefExpr(
708 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000709 } else {
710 // The variable is also a firstprivate, so initialization sequence
711 // for private copy is generated already.
712 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000713 }
714 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000715 // Set initializers to private copies if no errors were found.
716 if (PrivateCopies.size() == Clause->varlist_size()) {
717 Clause->setPrivateCopies(PrivateCopies);
718 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000719 }
720 }
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 DSAStack->pop();
724 DiscardCleanupsInEvaluationContext();
725 PopExpressionEvaluationContext();
726}
727
Alexander Musman3276a272015-03-21 10:12:56 +0000728static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
729 Expr *NumIterations, Sema &SemaRef,
730 Scope *S);
731
Alexey Bataeva769e072013-03-22 06:34:35 +0000732namespace {
733
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000734class VarDeclFilterCCC : public CorrectionCandidateCallback {
735private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000736 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000737
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000738public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000739 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000740 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000741 NamedDecl *ND = Candidate.getCorrectionDecl();
742 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
743 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000744 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
745 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000746 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000747 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000748 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000749};
Alexey Bataeved09d242014-05-28 05:53:51 +0000750} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000751
752ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
753 CXXScopeSpec &ScopeSpec,
754 const DeclarationNameInfo &Id) {
755 LookupResult Lookup(*this, Id, LookupOrdinaryName);
756 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
757
758 if (Lookup.isAmbiguous())
759 return ExprError();
760
761 VarDecl *VD;
762 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000763 if (TypoCorrection Corrected = CorrectTypo(
764 Id, LookupOrdinaryName, CurScope, nullptr,
765 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000766 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000767 PDiag(Lookup.empty()
768 ? diag::err_undeclared_var_use_suggest
769 : diag::err_omp_expected_var_arg_suggest)
770 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000771 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000772 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000773 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
774 : diag::err_omp_expected_var_arg)
775 << Id.getName();
776 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000777 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000778 } else {
779 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000780 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000781 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
782 return ExprError();
783 }
784 }
785 Lookup.suppressDiagnostics();
786
787 // OpenMP [2.9.2, Syntax, C/C++]
788 // Variables must be file-scope, namespace-scope, or static block-scope.
789 if (!VD->hasGlobalStorage()) {
790 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000791 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
792 bool IsDecl =
793 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000794 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000795 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
796 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000797 return ExprError();
798 }
799
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000800 VarDecl *CanonicalVD = VD->getCanonicalDecl();
801 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000802 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
803 // A threadprivate directive for file-scope variables must appear outside
804 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000805 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
806 !getCurLexicalContext()->isTranslationUnit()) {
807 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000808 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
809 bool IsDecl =
810 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
811 Diag(VD->getLocation(),
812 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
813 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000814 return ExprError();
815 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000816 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
817 // A threadprivate directive for static class member variables must appear
818 // in the class definition, in the same scope in which the member
819 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000820 if (CanonicalVD->isStaticDataMember() &&
821 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
822 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 Bataev7d2960b2013-09-26 03:24:06 +0000829 return ExprError();
830 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000831 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
832 // A threadprivate directive for namespace-scope variables must appear
833 // outside any definition or declaration other than the namespace
834 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000835 if (CanonicalVD->getDeclContext()->isNamespace() &&
836 (!getCurLexicalContext()->isFileContext() ||
837 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
838 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000839 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
840 bool IsDecl =
841 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
842 Diag(VD->getLocation(),
843 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
844 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000845 return ExprError();
846 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000847 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
848 // A threadprivate directive for static block-scope variables must appear
849 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000850 if (CanonicalVD->isStaticLocal() && CurScope &&
851 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000852 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000853 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
854 bool IsDecl =
855 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
856 Diag(VD->getLocation(),
857 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
858 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000859 return ExprError();
860 }
861
862 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
863 // A threadprivate directive must lexically precede all references to any
864 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000865 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000866 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000867 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000868 return ExprError();
869 }
870
871 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +0000872 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000873 return DE;
874}
875
Alexey Bataeved09d242014-05-28 05:53:51 +0000876Sema::DeclGroupPtrTy
877Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
878 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000879 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000880 CurContext->addDecl(D);
881 return DeclGroupPtrTy::make(DeclGroupRef(D));
882 }
883 return DeclGroupPtrTy();
884}
885
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000886namespace {
887class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
888 Sema &SemaRef;
889
890public:
891 bool VisitDeclRefExpr(const DeclRefExpr *E) {
892 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
893 if (VD->hasLocalStorage()) {
894 SemaRef.Diag(E->getLocStart(),
895 diag::err_omp_local_var_in_threadprivate_init)
896 << E->getSourceRange();
897 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
898 << VD << VD->getSourceRange();
899 return true;
900 }
901 }
902 return false;
903 }
904 bool VisitStmt(const Stmt *S) {
905 for (auto Child : S->children()) {
906 if (Child && Visit(Child))
907 return true;
908 }
909 return false;
910 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000911 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000912};
913} // namespace
914
Alexey Bataeved09d242014-05-28 05:53:51 +0000915OMPThreadPrivateDecl *
916Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000917 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000918 for (auto &RefExpr : VarList) {
919 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000920 VarDecl *VD = cast<VarDecl>(DE->getDecl());
921 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000922
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000923 QualType QType = VD->getType();
924 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
925 // It will be analyzed later.
926 Vars.push_back(DE);
927 continue;
928 }
929
Alexey Bataeva769e072013-03-22 06:34:35 +0000930 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
931 // A threadprivate variable must not have an incomplete type.
932 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000933 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000934 continue;
935 }
936
937 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
938 // A threadprivate variable must not have a reference type.
939 if (VD->getType()->isReferenceType()) {
940 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000941 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
942 bool IsDecl =
943 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
944 Diag(VD->getLocation(),
945 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
946 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000947 continue;
948 }
949
Richard Smithfd3834f2013-04-13 02:43:54 +0000950 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000951 if (VD->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000952 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
953 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +0000954 Diag(ILoc, diag::err_omp_var_thread_local)
955 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000956 bool IsDecl =
957 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
958 Diag(VD->getLocation(),
959 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
960 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000961 continue;
962 }
963
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000964 // Check if initial value of threadprivate variable reference variable with
965 // local storage (it is not supported by runtime).
966 if (auto Init = VD->getAnyInitializer()) {
967 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000968 if (Checker.Visit(Init))
969 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000970 }
971
Alexey Bataeved09d242014-05-28 05:53:51 +0000972 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000973 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000974 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
975 Context, SourceRange(Loc, Loc)));
976 if (auto *ML = Context.getASTMutationListener())
977 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000978 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000979 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000980 if (!Vars.empty()) {
981 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
982 Vars);
983 D->setAccess(AS_public);
984 }
985 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000986}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000987
Alexey Bataev7ff55242014-06-19 09:13:45 +0000988static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
989 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
990 bool IsLoopIterVar = false) {
991 if (DVar.RefExpr) {
992 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
993 << getOpenMPClauseName(DVar.CKind);
994 return;
995 }
996 enum {
997 PDSA_StaticMemberShared,
998 PDSA_StaticLocalVarShared,
999 PDSA_LoopIterVarPrivate,
1000 PDSA_LoopIterVarLinear,
1001 PDSA_LoopIterVarLastprivate,
1002 PDSA_ConstVarShared,
1003 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001004 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001005 PDSA_LocalVarPrivate,
1006 PDSA_Implicit
1007 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001008 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001009 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +00001010 if (IsLoopIterVar) {
1011 if (DVar.CKind == OMPC_private)
1012 Reason = PDSA_LoopIterVarPrivate;
1013 else if (DVar.CKind == OMPC_lastprivate)
1014 Reason = PDSA_LoopIterVarLastprivate;
1015 else
1016 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001017 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1018 Reason = PDSA_TaskVarFirstprivate;
1019 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001020 } else if (VD->isStaticLocal())
1021 Reason = PDSA_StaticLocalVarShared;
1022 else if (VD->isStaticDataMember())
1023 Reason = PDSA_StaticMemberShared;
1024 else if (VD->isFileVarDecl())
1025 Reason = PDSA_GlobalVarShared;
1026 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1027 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001028 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001029 ReportHint = true;
1030 Reason = PDSA_LocalVarPrivate;
1031 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001032 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001033 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001034 << Reason << ReportHint
1035 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1036 } else if (DVar.ImplicitDSALoc.isValid()) {
1037 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1038 << getOpenMPClauseName(DVar.CKind);
1039 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001040}
1041
Alexey Bataev758e55e2013-09-06 18:03:48 +00001042namespace {
1043class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1044 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001045 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001046 bool ErrorFound;
1047 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001048 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001049 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001050
Alexey Bataev758e55e2013-09-06 18:03:48 +00001051public:
1052 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001053 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001055 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1056 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001057
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001058 auto DVar = Stack->getTopDSA(VD, false);
1059 // Check if the variable has explicit DSA set and stop analysis if it so.
1060 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001061
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001062 auto ELoc = E->getExprLoc();
1063 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064 // The default(none) clause requires that each variable that is referenced
1065 // in the construct, and does not have a predetermined data-sharing
1066 // attribute, must have its data-sharing attribute explicitly determined
1067 // by being listed in a data-sharing attribute clause.
1068 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001069 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001070 VarsWithInheritedDSA.count(VD) == 0) {
1071 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001072 return;
1073 }
1074
1075 // OpenMP [2.9.3.6, Restrictions, p.2]
1076 // A list item that appears in a reduction clause of the innermost
1077 // enclosing worksharing or parallel construct may not be accessed in an
1078 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001079 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001080 [](OpenMPDirectiveKind K) -> bool {
1081 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001082 isOpenMPWorksharingDirective(K) ||
1083 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001084 },
1085 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001086 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1087 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001088 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1089 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001090 return;
1091 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001092
1093 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001094 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001095 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001096 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001097 }
1098 }
1099 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001100 for (auto *C : S->clauses()) {
1101 // Skip analysis of arguments of implicitly defined firstprivate clause
1102 // for task directives.
1103 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1104 for (auto *CC : C->children()) {
1105 if (CC)
1106 Visit(CC);
1107 }
1108 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001109 }
1110 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001111 for (auto *C : S->children()) {
1112 if (C && !isa<OMPExecutableDirective>(C))
1113 Visit(C);
1114 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001115 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001116
1117 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001118 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001119 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1120 return VarsWithInheritedDSA;
1121 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001122
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1124 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001125};
Alexey Bataeved09d242014-05-28 05:53:51 +00001126} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001127
Alexey Bataevbae9a792014-06-27 10:37:06 +00001128void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001129 switch (DKind) {
1130 case OMPD_parallel: {
1131 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1132 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001133 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001134 std::make_pair(".global_tid.", KmpInt32PtrTy),
1135 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1136 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001137 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001138 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1139 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001140 break;
1141 }
1142 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001143 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001144 std::make_pair(StringRef(), QualType()) // __context with shared vars
1145 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001146 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1147 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001148 break;
1149 }
1150 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001151 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001152 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001153 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001154 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1155 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001156 break;
1157 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001158 case OMPD_for_simd: {
1159 Sema::CapturedParamNameType Params[] = {
1160 std::make_pair(StringRef(), QualType()) // __context with shared vars
1161 };
1162 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1163 Params);
1164 break;
1165 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001166 case OMPD_sections: {
1167 Sema::CapturedParamNameType Params[] = {
1168 std::make_pair(StringRef(), QualType()) // __context with shared vars
1169 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001170 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1171 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001172 break;
1173 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001174 case OMPD_section: {
1175 Sema::CapturedParamNameType Params[] = {
1176 std::make_pair(StringRef(), QualType()) // __context with shared vars
1177 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001178 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1179 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001180 break;
1181 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001182 case OMPD_single: {
1183 Sema::CapturedParamNameType Params[] = {
1184 std::make_pair(StringRef(), QualType()) // __context with shared vars
1185 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001186 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1187 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001188 break;
1189 }
Alexander Musman80c22892014-07-17 08:54:58 +00001190 case OMPD_master: {
1191 Sema::CapturedParamNameType Params[] = {
1192 std::make_pair(StringRef(), QualType()) // __context with shared vars
1193 };
1194 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1195 Params);
1196 break;
1197 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001198 case OMPD_critical: {
1199 Sema::CapturedParamNameType Params[] = {
1200 std::make_pair(StringRef(), QualType()) // __context with shared vars
1201 };
1202 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1203 Params);
1204 break;
1205 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001206 case OMPD_parallel_for: {
1207 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1208 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1209 Sema::CapturedParamNameType Params[] = {
1210 std::make_pair(".global_tid.", KmpInt32PtrTy),
1211 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1212 std::make_pair(StringRef(), QualType()) // __context with shared vars
1213 };
1214 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1215 Params);
1216 break;
1217 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001218 case OMPD_parallel_for_simd: {
1219 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1220 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1221 Sema::CapturedParamNameType Params[] = {
1222 std::make_pair(".global_tid.", KmpInt32PtrTy),
1223 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1224 std::make_pair(StringRef(), QualType()) // __context with shared vars
1225 };
1226 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1227 Params);
1228 break;
1229 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001230 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001231 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1232 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001233 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001234 std::make_pair(".global_tid.", KmpInt32PtrTy),
1235 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001236 std::make_pair(StringRef(), QualType()) // __context with shared vars
1237 };
1238 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1239 Params);
1240 break;
1241 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001242 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001243 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001244 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1245 FunctionProtoType::ExtProtoInfo EPI;
1246 EPI.Variadic = true;
1247 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001248 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001249 std::make_pair(".global_tid.", KmpInt32Ty),
1250 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001251 std::make_pair(".privates.",
1252 Context.VoidPtrTy.withConst().withRestrict()),
1253 std::make_pair(
1254 ".copy_fn.",
1255 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001256 std::make_pair(StringRef(), QualType()) // __context with shared vars
1257 };
1258 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1259 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001260 // Mark this captured region as inlined, because we don't use outlined
1261 // function directly.
1262 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1263 AlwaysInlineAttr::CreateImplicit(
1264 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001265 break;
1266 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001267 case OMPD_ordered: {
1268 Sema::CapturedParamNameType Params[] = {
1269 std::make_pair(StringRef(), QualType()) // __context with shared vars
1270 };
1271 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1272 Params);
1273 break;
1274 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001275 case OMPD_atomic: {
1276 Sema::CapturedParamNameType Params[] = {
1277 std::make_pair(StringRef(), QualType()) // __context with shared vars
1278 };
1279 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1280 Params);
1281 break;
1282 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001283 case OMPD_target: {
1284 Sema::CapturedParamNameType Params[] = {
1285 std::make_pair(StringRef(), QualType()) // __context with shared vars
1286 };
1287 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1288 Params);
1289 break;
1290 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001291 case OMPD_teams: {
1292 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1293 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1294 Sema::CapturedParamNameType Params[] = {
1295 std::make_pair(".global_tid.", KmpInt32PtrTy),
1296 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1297 std::make_pair(StringRef(), QualType()) // __context with shared vars
1298 };
1299 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1300 Params);
1301 break;
1302 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001303 case OMPD_taskgroup: {
1304 Sema::CapturedParamNameType Params[] = {
1305 std::make_pair(StringRef(), QualType()) // __context with shared vars
1306 };
1307 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1308 Params);
1309 break;
1310 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001311 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001312 case OMPD_taskyield:
1313 case OMPD_barrier:
1314 case OMPD_taskwait:
1315 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001316 llvm_unreachable("OpenMP Directive is not allowed");
1317 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001318 llvm_unreachable("Unknown OpenMP directive");
1319 }
1320}
1321
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001322StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1323 ArrayRef<OMPClause *> Clauses) {
1324 if (!S.isUsable()) {
1325 ActOnCapturedRegionError();
1326 return StmtError();
1327 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001328 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001329 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001330 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1331 Clause->getClauseKind() == OMPC_copyprivate) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001332 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001333 for (auto *VarRef : Clause->children()) {
1334 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001335 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001336 }
1337 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001338 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1339 Clause->getClauseKind() == OMPC_schedule) {
1340 // Mark all variables in private list clauses as used in inner region.
1341 // Required for proper codegen of combined directives.
1342 // TODO: add processing for other clauses.
1343 if (auto *E = cast_or_null<Expr>(
1344 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1345 MarkDeclarationsReferencedInExpr(E);
1346 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001347 }
1348 }
1349 return ActOnCapturedRegionEnd(S.get());
1350}
1351
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001352static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1353 OpenMPDirectiveKind CurrentRegion,
1354 const DeclarationNameInfo &CurrentName,
1355 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001356 // Allowed nesting of constructs
1357 // +------------------+-----------------+------------------------------------+
1358 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1359 // +------------------+-----------------+------------------------------------+
1360 // | parallel | parallel | * |
1361 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001362 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001363 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001364 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001365 // | parallel | simd | * |
1366 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001367 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001368 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001369 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001370 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001371 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001372 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001373 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001374 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001375 // | parallel | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001376 // | parallel | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001377 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001378 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001379 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001380 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001381 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001382 // +------------------+-----------------+------------------------------------+
1383 // | for | parallel | * |
1384 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001385 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001386 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001387 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001388 // | for | simd | * |
1389 // | for | sections | + |
1390 // | for | section | + |
1391 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001392 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001393 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001394 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001395 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001396 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001397 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001398 // | for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001399 // | for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001400 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001401 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001402 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001403 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001404 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001405 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001406 // | master | parallel | * |
1407 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001408 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001409 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001410 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001411 // | master | simd | * |
1412 // | master | sections | + |
1413 // | master | section | + |
1414 // | master | single | + |
1415 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001416 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001417 // | master |parallel sections| * |
1418 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001419 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001420 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001421 // | master | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001422 // | master | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001423 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001424 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001425 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001426 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001427 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001428 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001429 // | critical | parallel | * |
1430 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001431 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001432 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001433 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001434 // | critical | simd | * |
1435 // | critical | sections | + |
1436 // | critical | section | + |
1437 // | critical | single | + |
1438 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001439 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001440 // | critical |parallel sections| * |
1441 // | critical | task | * |
1442 // | critical | taskyield | * |
1443 // | critical | barrier | + |
1444 // | critical | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001445 // | critical | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001446 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001447 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001448 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001449 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001450 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001451 // | simd | parallel | |
1452 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001453 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001454 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001455 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001456 // | simd | simd | |
1457 // | simd | sections | |
1458 // | simd | section | |
1459 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001460 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001461 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001462 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001463 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001464 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001465 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001466 // | simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001467 // | simd | taskgroup | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001468 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001469 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001470 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001471 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001472 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001473 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001474 // | for simd | parallel | |
1475 // | for simd | for | |
1476 // | for simd | for simd | |
1477 // | for simd | master | |
1478 // | for simd | critical | |
1479 // | for simd | simd | |
1480 // | for simd | sections | |
1481 // | for simd | section | |
1482 // | for simd | single | |
1483 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001484 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001485 // | for simd |parallel sections| |
1486 // | for simd | task | |
1487 // | for simd | taskyield | |
1488 // | for simd | barrier | |
1489 // | for simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001490 // | for simd | taskgroup | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001491 // | for simd | flush | |
1492 // | for simd | ordered | |
1493 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001494 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001495 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001496 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001497 // | parallel for simd| parallel | |
1498 // | parallel for simd| for | |
1499 // | parallel for simd| for simd | |
1500 // | parallel for simd| master | |
1501 // | parallel for simd| critical | |
1502 // | parallel for simd| simd | |
1503 // | parallel for simd| sections | |
1504 // | parallel for simd| section | |
1505 // | parallel for simd| single | |
1506 // | parallel for simd| parallel for | |
1507 // | parallel for simd|parallel for simd| |
1508 // | parallel for simd|parallel sections| |
1509 // | parallel for simd| task | |
1510 // | parallel for simd| taskyield | |
1511 // | parallel for simd| barrier | |
1512 // | parallel for simd| taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001513 // | parallel for simd| taskgroup | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001514 // | parallel for simd| flush | |
1515 // | parallel for simd| ordered | |
1516 // | parallel for simd| atomic | |
1517 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001518 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001519 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001520 // | sections | parallel | * |
1521 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001522 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001523 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001524 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001525 // | sections | simd | * |
1526 // | sections | sections | + |
1527 // | sections | section | * |
1528 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001529 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001530 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001531 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001532 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001533 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001534 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001535 // | sections | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001536 // | sections | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001537 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001538 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001539 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001540 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001541 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001542 // +------------------+-----------------+------------------------------------+
1543 // | section | parallel | * |
1544 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001545 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001546 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001547 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001548 // | section | simd | * |
1549 // | section | sections | + |
1550 // | section | section | + |
1551 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001552 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001553 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001554 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001555 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001556 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001557 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001558 // | section | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001559 // | section | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001560 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001561 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001562 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001563 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001564 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001565 // +------------------+-----------------+------------------------------------+
1566 // | single | parallel | * |
1567 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001568 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001569 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001570 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001571 // | single | simd | * |
1572 // | single | sections | + |
1573 // | single | section | + |
1574 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001575 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001576 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001577 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001578 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001579 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001580 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001581 // | single | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001582 // | single | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001583 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001584 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001585 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001586 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001587 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001588 // +------------------+-----------------+------------------------------------+
1589 // | parallel for | parallel | * |
1590 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001591 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001592 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001593 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001594 // | parallel for | simd | * |
1595 // | parallel for | sections | + |
1596 // | parallel for | section | + |
1597 // | parallel for | single | + |
1598 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001599 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001600 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001601 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001602 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001603 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001604 // | parallel for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001605 // | parallel for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001606 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001607 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001608 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001609 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001610 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001611 // +------------------+-----------------+------------------------------------+
1612 // | parallel sections| parallel | * |
1613 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001614 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001615 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001616 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001617 // | parallel sections| simd | * |
1618 // | parallel sections| sections | + |
1619 // | parallel sections| section | * |
1620 // | parallel sections| single | + |
1621 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001622 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001623 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001624 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001625 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001626 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001627 // | parallel sections| taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001628 // | parallel sections| taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001629 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001630 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001631 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001632 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001633 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001634 // +------------------+-----------------+------------------------------------+
1635 // | task | parallel | * |
1636 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001637 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001638 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001639 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001640 // | task | simd | * |
1641 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001642 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001643 // | task | single | + |
1644 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001645 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001646 // | task |parallel sections| * |
1647 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001648 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001649 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001650 // | task | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001651 // | task | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001652 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001653 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001654 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001655 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001656 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001657 // +------------------+-----------------+------------------------------------+
1658 // | ordered | parallel | * |
1659 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001660 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001661 // | ordered | master | * |
1662 // | ordered | critical | * |
1663 // | ordered | simd | * |
1664 // | ordered | sections | + |
1665 // | ordered | section | + |
1666 // | ordered | single | + |
1667 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001668 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001669 // | ordered |parallel sections| * |
1670 // | ordered | task | * |
1671 // | ordered | taskyield | * |
1672 // | ordered | barrier | + |
1673 // | ordered | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001674 // | ordered | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001675 // | ordered | flush | * |
1676 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001677 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001678 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001679 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001680 // +------------------+-----------------+------------------------------------+
1681 // | atomic | parallel | |
1682 // | atomic | for | |
1683 // | atomic | for simd | |
1684 // | atomic | master | |
1685 // | atomic | critical | |
1686 // | atomic | simd | |
1687 // | atomic | sections | |
1688 // | atomic | section | |
1689 // | atomic | single | |
1690 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001691 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001692 // | atomic |parallel sections| |
1693 // | atomic | task | |
1694 // | atomic | taskyield | |
1695 // | atomic | barrier | |
1696 // | atomic | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001697 // | atomic | taskgroup | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001698 // | atomic | flush | |
1699 // | atomic | ordered | |
1700 // | atomic | atomic | |
1701 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001702 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001703 // +------------------+-----------------+------------------------------------+
1704 // | target | parallel | * |
1705 // | target | for | * |
1706 // | target | for simd | * |
1707 // | target | master | * |
1708 // | target | critical | * |
1709 // | target | simd | * |
1710 // | target | sections | * |
1711 // | target | section | * |
1712 // | target | single | * |
1713 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001714 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001715 // | target |parallel sections| * |
1716 // | target | task | * |
1717 // | target | taskyield | * |
1718 // | target | barrier | * |
1719 // | target | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001720 // | target | taskgroup | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001721 // | target | flush | * |
1722 // | target | ordered | * |
1723 // | target | atomic | * |
1724 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001725 // | target | teams | * |
1726 // +------------------+-----------------+------------------------------------+
1727 // | teams | parallel | * |
1728 // | teams | for | + |
1729 // | teams | for simd | + |
1730 // | teams | master | + |
1731 // | teams | critical | + |
1732 // | teams | simd | + |
1733 // | teams | sections | + |
1734 // | teams | section | + |
1735 // | teams | single | + |
1736 // | teams | parallel for | * |
1737 // | teams |parallel for simd| * |
1738 // | teams |parallel sections| * |
1739 // | teams | task | + |
1740 // | teams | taskyield | + |
1741 // | teams | barrier | + |
1742 // | teams | taskwait | + |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001743 // | teams | taskgroup | + |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001744 // | teams | flush | + |
1745 // | teams | ordered | + |
1746 // | teams | atomic | + |
1747 // | teams | target | + |
1748 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001749 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001750 if (Stack->getCurScope()) {
1751 auto ParentRegion = Stack->getParentDirective();
1752 bool NestingProhibited = false;
1753 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001754 enum {
1755 NoRecommend,
1756 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001757 ShouldBeInOrderedRegion,
1758 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001759 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001760 if (isOpenMPSimdDirective(ParentRegion)) {
1761 // OpenMP [2.16, Nesting of Regions]
1762 // OpenMP constructs may not be nested inside a simd region.
1763 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1764 return true;
1765 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001766 if (ParentRegion == OMPD_atomic) {
1767 // OpenMP [2.16, Nesting of Regions]
1768 // OpenMP constructs may not be nested inside an atomic region.
1769 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1770 return true;
1771 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001772 if (CurrentRegion == OMPD_section) {
1773 // OpenMP [2.7.2, sections Construct, Restrictions]
1774 // Orphaned section directives are prohibited. That is, the section
1775 // directives must appear within the sections construct and must not be
1776 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001777 if (ParentRegion != OMPD_sections &&
1778 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001779 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1780 << (ParentRegion != OMPD_unknown)
1781 << getOpenMPDirectiveName(ParentRegion);
1782 return true;
1783 }
1784 return false;
1785 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001786 // Allow some constructs to be orphaned (they could be used in functions,
1787 // called from OpenMP regions with the required preconditions).
1788 if (ParentRegion == OMPD_unknown)
1789 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001790 if (CurrentRegion == OMPD_master) {
1791 // OpenMP [2.16, Nesting of Regions]
1792 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001793 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001794 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1795 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001796 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1797 // OpenMP [2.16, Nesting of Regions]
1798 // A critical region may not be nested (closely or otherwise) inside a
1799 // critical region with the same name. Note that this restriction is not
1800 // sufficient to prevent deadlock.
1801 SourceLocation PreviousCriticalLoc;
1802 bool DeadLock =
1803 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1804 OpenMPDirectiveKind K,
1805 const DeclarationNameInfo &DNI,
1806 SourceLocation Loc)
1807 ->bool {
1808 if (K == OMPD_critical &&
1809 DNI.getName() == CurrentName.getName()) {
1810 PreviousCriticalLoc = Loc;
1811 return true;
1812 } else
1813 return false;
1814 },
1815 false /* skip top directive */);
1816 if (DeadLock) {
1817 SemaRef.Diag(StartLoc,
1818 diag::err_omp_prohibited_region_critical_same_name)
1819 << CurrentName.getName();
1820 if (PreviousCriticalLoc.isValid())
1821 SemaRef.Diag(PreviousCriticalLoc,
1822 diag::note_omp_previous_critical_region);
1823 return true;
1824 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001825 } else if (CurrentRegion == OMPD_barrier) {
1826 // OpenMP [2.16, Nesting of Regions]
1827 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001828 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001829 NestingProhibited =
1830 isOpenMPWorksharingDirective(ParentRegion) ||
1831 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1832 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001833 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001834 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001835 // OpenMP [2.16, Nesting of Regions]
1836 // A worksharing region may not be closely nested inside a worksharing,
1837 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001838 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001839 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001840 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1841 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1842 Recommend = ShouldBeInParallelRegion;
1843 } else if (CurrentRegion == OMPD_ordered) {
1844 // OpenMP [2.16, Nesting of Regions]
1845 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001846 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001847 // An ordered region must be closely nested inside a loop region (or
1848 // parallel loop region) with an ordered clause.
1849 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001850 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001851 !Stack->isParentOrderedRegion();
1852 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001853 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1854 // OpenMP [2.16, Nesting of Regions]
1855 // If specified, a teams construct must be contained within a target
1856 // construct.
1857 NestingProhibited = ParentRegion != OMPD_target;
1858 Recommend = ShouldBeInTargetRegion;
1859 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1860 }
1861 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1862 // OpenMP [2.16, Nesting of Regions]
1863 // distribute, parallel, parallel sections, parallel workshare, and the
1864 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1865 // constructs that can be closely nested in the teams region.
1866 // TODO: add distribute directive.
1867 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1868 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001869 }
1870 if (NestingProhibited) {
1871 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001872 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1873 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001874 return true;
1875 }
1876 }
1877 return false;
1878}
1879
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001880StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001881 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001882 ArrayRef<OMPClause *> Clauses,
1883 Stmt *AStmt,
1884 SourceLocation StartLoc,
1885 SourceLocation EndLoc) {
1886 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001887 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001888 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001889
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001890 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001891 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001892 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001893 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001894 if (AStmt) {
1895 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1896
1897 // Check default data sharing attributes for referenced variables.
1898 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1899 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1900 if (DSAChecker.isErrorFound())
1901 return StmtError();
1902 // Generate list of implicitly defined firstprivate variables.
1903 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001904
1905 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1906 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1907 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1908 SourceLocation(), SourceLocation())) {
1909 ClausesWithImplicit.push_back(Implicit);
1910 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1911 DSAChecker.getImplicitFirstprivate().size();
1912 } else
1913 ErrorFound = true;
1914 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001915 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001916
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001917 switch (Kind) {
1918 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001919 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1920 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001921 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001922 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001923 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1924 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001925 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001926 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001927 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1928 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001929 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001930 case OMPD_for_simd:
1931 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1932 EndLoc, VarsWithInheritedDSA);
1933 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001934 case OMPD_sections:
1935 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1936 EndLoc);
1937 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001938 case OMPD_section:
1939 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001940 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001941 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1942 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001943 case OMPD_single:
1944 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1945 EndLoc);
1946 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001947 case OMPD_master:
1948 assert(ClausesWithImplicit.empty() &&
1949 "No clauses are allowed for 'omp master' directive");
1950 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1951 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001952 case OMPD_critical:
1953 assert(ClausesWithImplicit.empty() &&
1954 "No clauses are allowed for 'omp critical' directive");
1955 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1956 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001957 case OMPD_parallel_for:
1958 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1959 EndLoc, VarsWithInheritedDSA);
1960 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001961 case OMPD_parallel_for_simd:
1962 Res = ActOnOpenMPParallelForSimdDirective(
1963 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1964 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001965 case OMPD_parallel_sections:
1966 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1967 StartLoc, EndLoc);
1968 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001969 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001970 Res =
1971 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1972 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001973 case OMPD_taskyield:
1974 assert(ClausesWithImplicit.empty() &&
1975 "No clauses are allowed for 'omp taskyield' directive");
1976 assert(AStmt == nullptr &&
1977 "No associated statement allowed for 'omp taskyield' directive");
1978 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1979 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001980 case OMPD_barrier:
1981 assert(ClausesWithImplicit.empty() &&
1982 "No clauses are allowed for 'omp barrier' directive");
1983 assert(AStmt == nullptr &&
1984 "No associated statement allowed for 'omp barrier' directive");
1985 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1986 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001987 case OMPD_taskwait:
1988 assert(ClausesWithImplicit.empty() &&
1989 "No clauses are allowed for 'omp taskwait' directive");
1990 assert(AStmt == nullptr &&
1991 "No associated statement allowed for 'omp taskwait' directive");
1992 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1993 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001994 case OMPD_taskgroup:
1995 assert(ClausesWithImplicit.empty() &&
1996 "No clauses are allowed for 'omp taskgroup' directive");
1997 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
1998 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001999 case OMPD_flush:
2000 assert(AStmt == nullptr &&
2001 "No associated statement allowed for 'omp flush' directive");
2002 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2003 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002004 case OMPD_ordered:
2005 assert(ClausesWithImplicit.empty() &&
2006 "No clauses are allowed for 'omp ordered' directive");
2007 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
2008 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002009 case OMPD_atomic:
2010 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2011 EndLoc);
2012 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002013 case OMPD_teams:
2014 Res =
2015 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2016 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002017 case OMPD_target:
2018 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2019 EndLoc);
2020 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002021 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002022 llvm_unreachable("OpenMP Directive is not allowed");
2023 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002024 llvm_unreachable("Unknown OpenMP directive");
2025 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002026
Alexey Bataev4acb8592014-07-07 13:01:15 +00002027 for (auto P : VarsWithInheritedDSA) {
2028 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2029 << P.first << P.second->getSourceRange();
2030 }
2031 if (!VarsWithInheritedDSA.empty())
2032 return StmtError();
2033
Alexey Bataeved09d242014-05-28 05:53:51 +00002034 if (ErrorFound)
2035 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002036 return Res;
2037}
2038
2039StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2040 Stmt *AStmt,
2041 SourceLocation StartLoc,
2042 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002043 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2044 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2045 // 1.2.2 OpenMP Language Terminology
2046 // Structured block - An executable statement with a single entry at the
2047 // top and a single exit at the bottom.
2048 // The point of exit cannot be a branch out of the structured block.
2049 // longjmp() and throw() must not violate the entry/exit criteria.
2050 CS->getCapturedDecl()->setNothrow();
2051
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002052 getCurFunction()->setHasBranchProtectedScope();
2053
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002054 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
2055 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002056}
2057
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002058namespace {
2059/// \brief Helper class for checking canonical form of the OpenMP loops and
2060/// extracting iteration space of each loop in the loop nest, that will be used
2061/// for IR generation.
2062class OpenMPIterationSpaceChecker {
2063 /// \brief Reference to Sema.
2064 Sema &SemaRef;
2065 /// \brief A location for diagnostics (when there is no some better location).
2066 SourceLocation DefaultLoc;
2067 /// \brief A location for diagnostics (when increment is not compatible).
2068 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002069 /// \brief A source location for referring to loop init later.
2070 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002071 /// \brief A source location for referring to condition later.
2072 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002073 /// \brief A source location for referring to increment later.
2074 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002075 /// \brief Loop variable.
2076 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002077 /// \brief Reference to loop variable.
2078 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002079 /// \brief Lower bound (initializer for the var).
2080 Expr *LB;
2081 /// \brief Upper bound.
2082 Expr *UB;
2083 /// \brief Loop step (increment).
2084 Expr *Step;
2085 /// \brief This flag is true when condition is one of:
2086 /// Var < UB
2087 /// Var <= UB
2088 /// UB > Var
2089 /// UB >= Var
2090 bool TestIsLessOp;
2091 /// \brief This flag is true when condition is strict ( < or > ).
2092 bool TestIsStrictOp;
2093 /// \brief This flag is true when step is subtracted on each iteration.
2094 bool SubtractStep;
2095
2096public:
2097 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2098 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002099 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2100 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002101 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2102 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002103 /// \brief Check init-expr for canonical loop form and save loop counter
2104 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002105 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002106 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2107 /// for less/greater and for strict/non-strict comparison.
2108 bool CheckCond(Expr *S);
2109 /// \brief Check incr-expr for canonical loop form and return true if it
2110 /// does not conform, otherwise save loop step (#Step).
2111 bool CheckInc(Expr *S);
2112 /// \brief Return the loop counter variable.
2113 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002114 /// \brief Return the reference expression to loop counter variable.
2115 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002116 /// \brief Source range of the loop init.
2117 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2118 /// \brief Source range of the loop condition.
2119 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2120 /// \brief Source range of the loop increment.
2121 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2122 /// \brief True if the step should be subtracted.
2123 bool ShouldSubtractStep() const { return SubtractStep; }
2124 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002125 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002126 /// \brief Build the precondition expression for the loops.
2127 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002128 /// \brief Build reference expression to the counter be used for codegen.
2129 Expr *BuildCounterVar() const;
2130 /// \brief Build initization of the counter be used for codegen.
2131 Expr *BuildCounterInit() const;
2132 /// \brief Build step of the counter be used for codegen.
2133 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002134 /// \brief Return true if any expression is dependent.
2135 bool Dependent() const;
2136
2137private:
2138 /// \brief Check the right-hand side of an assignment in the increment
2139 /// expression.
2140 bool CheckIncRHS(Expr *RHS);
2141 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002142 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002143 /// \brief Helper to set upper bound.
2144 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2145 const SourceLocation &SL);
2146 /// \brief Helper to set loop increment.
2147 bool SetStep(Expr *NewStep, bool Subtract);
2148};
2149
2150bool OpenMPIterationSpaceChecker::Dependent() const {
2151 if (!Var) {
2152 assert(!LB && !UB && !Step);
2153 return false;
2154 }
2155 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2156 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2157}
2158
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002159bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2160 DeclRefExpr *NewVarRefExpr,
2161 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002162 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002163 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2164 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002165 if (!NewVar || !NewLB)
2166 return true;
2167 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002168 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002169 LB = NewLB;
2170 return false;
2171}
2172
2173bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2174 const SourceRange &SR,
2175 const SourceLocation &SL) {
2176 // State consistency checking to ensure correct usage.
2177 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2178 !TestIsLessOp && !TestIsStrictOp);
2179 if (!NewUB)
2180 return true;
2181 UB = NewUB;
2182 TestIsLessOp = LessOp;
2183 TestIsStrictOp = StrictOp;
2184 ConditionSrcRange = SR;
2185 ConditionLoc = SL;
2186 return false;
2187}
2188
2189bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2190 // State consistency checking to ensure correct usage.
2191 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2192 if (!NewStep)
2193 return true;
2194 if (!NewStep->isValueDependent()) {
2195 // Check that the step is integer expression.
2196 SourceLocation StepLoc = NewStep->getLocStart();
2197 ExprResult Val =
2198 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2199 if (Val.isInvalid())
2200 return true;
2201 NewStep = Val.get();
2202
2203 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2204 // If test-expr is of form var relational-op b and relational-op is < or
2205 // <= then incr-expr must cause var to increase on each iteration of the
2206 // loop. If test-expr is of form var relational-op b and relational-op is
2207 // > or >= then incr-expr must cause var to decrease on each iteration of
2208 // the loop.
2209 // If test-expr is of form b relational-op var and relational-op is < or
2210 // <= then incr-expr must cause var to decrease on each iteration of the
2211 // loop. If test-expr is of form b relational-op var and relational-op is
2212 // > or >= then incr-expr must cause var to increase on each iteration of
2213 // the loop.
2214 llvm::APSInt Result;
2215 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2216 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2217 bool IsConstNeg =
2218 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002219 bool IsConstPos =
2220 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002221 bool IsConstZero = IsConstant && !Result.getBoolValue();
2222 if (UB && (IsConstZero ||
2223 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002224 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002225 SemaRef.Diag(NewStep->getExprLoc(),
2226 diag::err_omp_loop_incr_not_compatible)
2227 << Var << TestIsLessOp << NewStep->getSourceRange();
2228 SemaRef.Diag(ConditionLoc,
2229 diag::note_omp_loop_cond_requres_compatible_incr)
2230 << TestIsLessOp << ConditionSrcRange;
2231 return true;
2232 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002233 if (TestIsLessOp == Subtract) {
2234 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2235 NewStep).get();
2236 Subtract = !Subtract;
2237 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002238 }
2239
2240 Step = NewStep;
2241 SubtractStep = Subtract;
2242 return false;
2243}
2244
Alexey Bataev9c821032015-04-30 04:23:23 +00002245bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002246 // Check init-expr for canonical loop form and save loop counter
2247 // variable - #Var and its initialization value - #LB.
2248 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2249 // var = lb
2250 // integer-type var = lb
2251 // random-access-iterator-type var = lb
2252 // pointer-type var = lb
2253 //
2254 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002255 if (EmitDiags) {
2256 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2257 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002258 return true;
2259 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002260 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002261 if (Expr *E = dyn_cast<Expr>(S))
2262 S = E->IgnoreParens();
2263 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2264 if (BO->getOpcode() == BO_Assign)
2265 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002266 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002267 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002268 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2269 if (DS->isSingleDecl()) {
2270 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2271 if (Var->hasInit()) {
2272 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002273 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002274 SemaRef.Diag(S->getLocStart(),
2275 diag::ext_omp_loop_not_canonical_init)
2276 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002277 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002278 }
2279 }
2280 }
2281 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2282 if (CE->getOperator() == OO_Equal)
2283 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002284 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2285 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002286
Alexey Bataev9c821032015-04-30 04:23:23 +00002287 if (EmitDiags) {
2288 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2289 << S->getSourceRange();
2290 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002291 return true;
2292}
2293
Alexey Bataev23b69422014-06-18 07:08:49 +00002294/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002295/// variable (which may be the loop variable) if possible.
2296static const VarDecl *GetInitVarDecl(const Expr *E) {
2297 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002298 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002299 E = E->IgnoreParenImpCasts();
2300 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2301 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2302 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2303 CE->getArg(0) != nullptr)
2304 E = CE->getArg(0)->IgnoreParenImpCasts();
2305 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2306 if (!DRE)
2307 return nullptr;
2308 return dyn_cast<VarDecl>(DRE->getDecl());
2309}
2310
2311bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2312 // Check test-expr for canonical form, save upper-bound UB, flags for
2313 // less/greater and for strict/non-strict comparison.
2314 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2315 // var relational-op b
2316 // b relational-op var
2317 //
2318 if (!S) {
2319 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2320 return true;
2321 }
2322 S = S->IgnoreParenImpCasts();
2323 SourceLocation CondLoc = S->getLocStart();
2324 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2325 if (BO->isRelationalOp()) {
2326 if (GetInitVarDecl(BO->getLHS()) == Var)
2327 return SetUB(BO->getRHS(),
2328 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2329 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2330 BO->getSourceRange(), BO->getOperatorLoc());
2331 if (GetInitVarDecl(BO->getRHS()) == Var)
2332 return SetUB(BO->getLHS(),
2333 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2334 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2335 BO->getSourceRange(), BO->getOperatorLoc());
2336 }
2337 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2338 if (CE->getNumArgs() == 2) {
2339 auto Op = CE->getOperator();
2340 switch (Op) {
2341 case OO_Greater:
2342 case OO_GreaterEqual:
2343 case OO_Less:
2344 case OO_LessEqual:
2345 if (GetInitVarDecl(CE->getArg(0)) == Var)
2346 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2347 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2348 CE->getOperatorLoc());
2349 if (GetInitVarDecl(CE->getArg(1)) == Var)
2350 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2351 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2352 CE->getOperatorLoc());
2353 break;
2354 default:
2355 break;
2356 }
2357 }
2358 }
2359 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2360 << S->getSourceRange() << Var;
2361 return true;
2362}
2363
2364bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2365 // RHS of canonical loop form increment can be:
2366 // var + incr
2367 // incr + var
2368 // var - incr
2369 //
2370 RHS = RHS->IgnoreParenImpCasts();
2371 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2372 if (BO->isAdditiveOp()) {
2373 bool IsAdd = BO->getOpcode() == BO_Add;
2374 if (GetInitVarDecl(BO->getLHS()) == Var)
2375 return SetStep(BO->getRHS(), !IsAdd);
2376 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2377 return SetStep(BO->getLHS(), false);
2378 }
2379 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2380 bool IsAdd = CE->getOperator() == OO_Plus;
2381 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2382 if (GetInitVarDecl(CE->getArg(0)) == Var)
2383 return SetStep(CE->getArg(1), !IsAdd);
2384 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2385 return SetStep(CE->getArg(0), false);
2386 }
2387 }
2388 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2389 << RHS->getSourceRange() << Var;
2390 return true;
2391}
2392
2393bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2394 // Check incr-expr for canonical loop form and return true if it
2395 // does not conform.
2396 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2397 // ++var
2398 // var++
2399 // --var
2400 // var--
2401 // var += incr
2402 // var -= incr
2403 // var = var + incr
2404 // var = incr + var
2405 // var = var - incr
2406 //
2407 if (!S) {
2408 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2409 return true;
2410 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002411 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002412 S = S->IgnoreParens();
2413 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2414 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2415 return SetStep(
2416 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2417 (UO->isDecrementOp() ? -1 : 1)).get(),
2418 false);
2419 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2420 switch (BO->getOpcode()) {
2421 case BO_AddAssign:
2422 case BO_SubAssign:
2423 if (GetInitVarDecl(BO->getLHS()) == Var)
2424 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2425 break;
2426 case BO_Assign:
2427 if (GetInitVarDecl(BO->getLHS()) == Var)
2428 return CheckIncRHS(BO->getRHS());
2429 break;
2430 default:
2431 break;
2432 }
2433 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2434 switch (CE->getOperator()) {
2435 case OO_PlusPlus:
2436 case OO_MinusMinus:
2437 if (GetInitVarDecl(CE->getArg(0)) == Var)
2438 return SetStep(
2439 SemaRef.ActOnIntegerConstant(
2440 CE->getLocStart(),
2441 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2442 false);
2443 break;
2444 case OO_PlusEqual:
2445 case OO_MinusEqual:
2446 if (GetInitVarDecl(CE->getArg(0)) == Var)
2447 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2448 break;
2449 case OO_Equal:
2450 if (GetInitVarDecl(CE->getArg(0)) == Var)
2451 return CheckIncRHS(CE->getArg(1));
2452 break;
2453 default:
2454 break;
2455 }
2456 }
2457 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2458 << S->getSourceRange() << Var;
2459 return true;
2460}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002461
2462/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002463Expr *
2464OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2465 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002466 ExprResult Diff;
2467 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2468 SemaRef.getLangOpts().CPlusPlus) {
2469 // Upper - Lower
2470 Expr *Upper = TestIsLessOp ? UB : LB;
2471 Expr *Lower = TestIsLessOp ? LB : UB;
2472
2473 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2474
2475 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2476 // BuildBinOp already emitted error, this one is to point user to upper
2477 // and lower bound, and to tell what is passed to 'operator-'.
2478 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2479 << Upper->getSourceRange() << Lower->getSourceRange();
2480 return nullptr;
2481 }
2482 }
2483
2484 if (!Diff.isUsable())
2485 return nullptr;
2486
2487 // Upper - Lower [- 1]
2488 if (TestIsStrictOp)
2489 Diff = SemaRef.BuildBinOp(
2490 S, DefaultLoc, BO_Sub, Diff.get(),
2491 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2492 if (!Diff.isUsable())
2493 return nullptr;
2494
2495 // Upper - Lower [- 1] + Step
2496 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2497 Step->IgnoreImplicit());
2498 if (!Diff.isUsable())
2499 return nullptr;
2500
2501 // Parentheses (for dumping/debugging purposes only).
2502 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2503 if (!Diff.isUsable())
2504 return nullptr;
2505
2506 // (Upper - Lower [- 1] + Step) / Step
2507 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2508 Step->IgnoreImplicit());
2509 if (!Diff.isUsable())
2510 return nullptr;
2511
Alexander Musman174b3ca2014-10-06 11:16:29 +00002512 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2513 if (LimitedType) {
2514 auto &C = SemaRef.Context;
2515 QualType Type = Diff.get()->getType();
2516 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2517 if (NewSize != C.getTypeSize(Type)) {
2518 if (NewSize < C.getTypeSize(Type)) {
2519 assert(NewSize == 64 && "incorrect loop var size");
2520 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2521 << InitSrcRange << ConditionSrcRange;
2522 }
2523 QualType NewType = C.getIntTypeForBitwidth(
2524 NewSize, Type->hasSignedIntegerRepresentation());
2525 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2526 Sema::AA_Converting, true);
2527 if (!Diff.isUsable())
2528 return nullptr;
2529 }
2530 }
2531
Alexander Musmana5f070a2014-10-01 06:03:56 +00002532 return Diff.get();
2533}
2534
Alexey Bataev62dbb972015-04-22 11:59:37 +00002535Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2536 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2537 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2538 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2539 auto CondExpr = SemaRef.BuildBinOp(
2540 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2541 : (TestIsStrictOp ? BO_GT : BO_GE),
2542 LB, UB);
2543 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2544 // Otherwise use original loop conditon and evaluate it in runtime.
2545 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2546}
2547
Alexander Musmana5f070a2014-10-01 06:03:56 +00002548/// \brief Build reference expression to the counter be used for codegen.
2549Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002550 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002551}
2552
2553/// \brief Build initization of the counter be used for codegen.
2554Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2555
2556/// \brief Build step of the counter be used for codegen.
2557Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2558
2559/// \brief Iteration space of a single for loop.
2560struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002561 /// \brief Condition of the loop.
2562 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002563 /// \brief This expression calculates the number of iterations in the loop.
2564 /// It is always possible to calculate it before starting the loop.
2565 Expr *NumIterations;
2566 /// \brief The loop counter variable.
2567 Expr *CounterVar;
2568 /// \brief This is initializer for the initial value of #CounterVar.
2569 Expr *CounterInit;
2570 /// \brief This is step for the #CounterVar used to generate its update:
2571 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2572 Expr *CounterStep;
2573 /// \brief Should step be subtracted?
2574 bool Subtract;
2575 /// \brief Source range of the loop init.
2576 SourceRange InitSrcRange;
2577 /// \brief Source range of the loop condition.
2578 SourceRange CondSrcRange;
2579 /// \brief Source range of the loop increment.
2580 SourceRange IncSrcRange;
2581};
2582
Alexey Bataev23b69422014-06-18 07:08:49 +00002583} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002584
Alexey Bataev9c821032015-04-30 04:23:23 +00002585void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2586 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2587 assert(Init && "Expected loop in canonical form.");
2588 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2589 if (CollapseIteration > 0 &&
2590 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2591 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2592 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2593 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2594 }
2595 DSAStack->setCollapseNumber(CollapseIteration - 1);
2596 }
2597}
2598
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002599/// \brief Called on a for stmt to check and extract its iteration space
2600/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002601static bool CheckOpenMPIterationSpace(
2602 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2603 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2604 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002605 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2606 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002607 // OpenMP [2.6, Canonical Loop Form]
2608 // for (init-expr; test-expr; incr-expr) structured-block
2609 auto For = dyn_cast_or_null<ForStmt>(S);
2610 if (!For) {
2611 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002612 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2613 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2614 << CurrentNestedLoopCount;
2615 if (NestedLoopCount > 1)
2616 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2617 diag::note_omp_collapse_expr)
2618 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002619 return true;
2620 }
2621 assert(For->getBody());
2622
2623 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2624
2625 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002626 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002627 if (ISC.CheckInit(Init)) {
2628 return true;
2629 }
2630
2631 bool HasErrors = false;
2632
2633 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002634 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002635
2636 // OpenMP [2.6, Canonical Loop Form]
2637 // Var is one of the following:
2638 // A variable of signed or unsigned integer type.
2639 // For C++, a variable of a random access iterator type.
2640 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002641 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002642 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2643 !VarType->isPointerType() &&
2644 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2645 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2646 << SemaRef.getLangOpts().CPlusPlus;
2647 HasErrors = true;
2648 }
2649
Alexey Bataev4acb8592014-07-07 13:01:15 +00002650 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2651 // Construct
2652 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2653 // parallel for construct is (are) private.
2654 // The loop iteration variable in the associated for-loop of a simd construct
2655 // with just one associated for-loop is linear with a constant-linear-step
2656 // that is the increment of the associated for-loop.
2657 // Exclude loop var from the list of variables with implicitly defined data
2658 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002659 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002660
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002661 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2662 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002663 // The loop iteration variable in the associated for-loop of a simd construct
2664 // with just one associated for-loop may be listed in a linear clause with a
2665 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002666 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2667 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002668 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002669 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2670 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2671 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002672 auto PredeterminedCKind =
2673 isOpenMPSimdDirective(DKind)
2674 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2675 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002676 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002677 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002678 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2679 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002680 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2681 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2682 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002683 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002684 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2685 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00002686 if (DVar.RefExpr == nullptr)
2687 DVar.CKind = PredeterminedCKind;
2688 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002689 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002690 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002691 // Make the loop iteration variable private (for worksharing constructs),
2692 // linear (for simd directives with the only one associated loop) or
2693 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002694 if (DVar.CKind == OMPC_unknown)
2695 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2696 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00002697 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002698 }
2699
Alexey Bataev7ff55242014-06-19 09:13:45 +00002700 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002701
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002702 // Check test-expr.
2703 HasErrors |= ISC.CheckCond(For->getCond());
2704
2705 // Check incr-expr.
2706 HasErrors |= ISC.CheckInc(For->getInc());
2707
Alexander Musmana5f070a2014-10-01 06:03:56 +00002708 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002709 return HasErrors;
2710
Alexander Musmana5f070a2014-10-01 06:03:56 +00002711 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002712 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00002713 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2714 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002715 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2716 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2717 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2718 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2719 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2720 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2721 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2722
Alexey Bataev62dbb972015-04-22 11:59:37 +00002723 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2724 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002725 ResultIterSpace.CounterVar == nullptr ||
2726 ResultIterSpace.CounterInit == nullptr ||
2727 ResultIterSpace.CounterStep == nullptr);
2728
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002729 return HasErrors;
2730}
2731
Alexander Musmana5f070a2014-10-01 06:03:56 +00002732/// \brief Build 'VarRef = Start + Iter * Step'.
2733static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2734 SourceLocation Loc, ExprResult VarRef,
2735 ExprResult Start, ExprResult Iter,
2736 ExprResult Step, bool Subtract) {
2737 // Add parentheses (for debugging purposes only).
2738 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2739 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2740 !Step.isUsable())
2741 return ExprError();
2742
2743 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2744 Step.get()->IgnoreImplicit());
2745 if (!Update.isUsable())
2746 return ExprError();
2747
2748 // Build 'VarRef = Start + Iter * Step'.
2749 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2750 Start.get()->IgnoreImplicit(), Update.get());
2751 if (!Update.isUsable())
2752 return ExprError();
2753
2754 Update = SemaRef.PerformImplicitConversion(
2755 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2756 if (!Update.isUsable())
2757 return ExprError();
2758
2759 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2760 return Update;
2761}
2762
2763/// \brief Convert integer expression \a E to make it have at least \a Bits
2764/// bits.
2765static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2766 Sema &SemaRef) {
2767 if (E == nullptr)
2768 return ExprError();
2769 auto &C = SemaRef.Context;
2770 QualType OldType = E->getType();
2771 unsigned HasBits = C.getTypeSize(OldType);
2772 if (HasBits >= Bits)
2773 return ExprResult(E);
2774 // OK to convert to signed, because new type has more bits than old.
2775 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2776 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2777 true);
2778}
2779
2780/// \brief Check if the given expression \a E is a constant integer that fits
2781/// into \a Bits bits.
2782static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2783 if (E == nullptr)
2784 return false;
2785 llvm::APSInt Result;
2786 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2787 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2788 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002789}
2790
2791/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002792/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2793/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002794static unsigned
2795CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2796 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002797 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002798 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002799 unsigned NestedLoopCount = 1;
2800 if (NestedLoopCountExpr) {
2801 // Found 'collapse' clause - calculate collapse number.
2802 llvm::APSInt Result;
2803 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2804 NestedLoopCount = Result.getLimitedValue();
2805 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002806 // This is helper routine for loop directives (e.g., 'for', 'simd',
2807 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002808 SmallVector<LoopIterationSpace, 4> IterSpaces;
2809 IterSpaces.resize(NestedLoopCount);
2810 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002811 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002812 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002813 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002814 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002815 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002816 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002817 // OpenMP [2.8.1, simd construct, Restrictions]
2818 // All loops associated with the construct must be perfectly nested; that
2819 // is, there must be no intervening code nor any OpenMP directive between
2820 // any two loops.
2821 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002822 }
2823
Alexander Musmana5f070a2014-10-01 06:03:56 +00002824 Built.clear(/* size */ NestedLoopCount);
2825
2826 if (SemaRef.CurContext->isDependentContext())
2827 return NestedLoopCount;
2828
2829 // An example of what is generated for the following code:
2830 //
2831 // #pragma omp simd collapse(2)
2832 // for (i = 0; i < NI; ++i)
2833 // for (j = J0; j < NJ; j+=2) {
2834 // <loop body>
2835 // }
2836 //
2837 // We generate the code below.
2838 // Note: the loop body may be outlined in CodeGen.
2839 // Note: some counters may be C++ classes, operator- is used to find number of
2840 // iterations and operator+= to calculate counter value.
2841 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2842 // or i64 is currently supported).
2843 //
2844 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2845 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2846 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2847 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2848 // // similar updates for vars in clauses (e.g. 'linear')
2849 // <loop body (using local i and j)>
2850 // }
2851 // i = NI; // assign final values of counters
2852 // j = NJ;
2853 //
2854
2855 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2856 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002857 // Precondition tests if there is at least one iteration (all conditions are
2858 // true).
2859 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002860 auto N0 = IterSpaces[0].NumIterations;
2861 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2862 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2863
2864 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2865 return NestedLoopCount;
2866
2867 auto &C = SemaRef.Context;
2868 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2869
2870 Scope *CurScope = DSA.getCurScope();
2871 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002872 if (PreCond.isUsable()) {
2873 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2874 PreCond.get(), IterSpaces[Cnt].PreCond);
2875 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002876 auto N = IterSpaces[Cnt].NumIterations;
2877 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2878 if (LastIteration32.isUsable())
2879 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2880 LastIteration32.get(), N);
2881 if (LastIteration64.isUsable())
2882 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2883 LastIteration64.get(), N);
2884 }
2885
2886 // Choose either the 32-bit or 64-bit version.
2887 ExprResult LastIteration = LastIteration64;
2888 if (LastIteration32.isUsable() &&
2889 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2890 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2891 FitsInto(
2892 32 /* Bits */,
2893 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2894 LastIteration64.get(), SemaRef)))
2895 LastIteration = LastIteration32;
2896
2897 if (!LastIteration.isUsable())
2898 return 0;
2899
2900 // Save the number of iterations.
2901 ExprResult NumIterations = LastIteration;
2902 {
2903 LastIteration = SemaRef.BuildBinOp(
2904 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2905 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2906 if (!LastIteration.isUsable())
2907 return 0;
2908 }
2909
2910 // Calculate the last iteration number beforehand instead of doing this on
2911 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2912 llvm::APSInt Result;
2913 bool IsConstant =
2914 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2915 ExprResult CalcLastIteration;
2916 if (!IsConstant) {
2917 SourceLocation SaveLoc;
2918 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00002919 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002920 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00002921 ExprResult SaveRef = buildDeclRefExpr(
2922 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002923 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2924 SaveRef.get(), LastIteration.get());
2925 LastIteration = SaveRef;
2926
2927 // Prepare SaveRef + 1.
2928 NumIterations = SemaRef.BuildBinOp(
2929 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2930 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2931 if (!NumIterations.isUsable())
2932 return 0;
2933 }
2934
2935 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2936
Alexander Musmanc6388682014-12-15 07:07:06 +00002937 QualType VType = LastIteration.get()->getType();
2938 // Build variables passed into runtime, nesessary for worksharing directives.
2939 ExprResult LB, UB, IL, ST, EUB;
2940 if (isOpenMPWorksharingDirective(DKind)) {
2941 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002942 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2943 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002944 SemaRef.AddInitializerToDecl(
2945 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2946 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2947
2948 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002949 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2950 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002951 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2952 /*DirectInit*/ false,
2953 /*TypeMayContainAuto*/ false);
2954
2955 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2956 // This will be used to implement clause 'lastprivate'.
2957 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002958 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2959 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002960 SemaRef.AddInitializerToDecl(
2961 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2962 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2963
2964 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00002965 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2966 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002967 SemaRef.AddInitializerToDecl(
2968 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2969 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2970
2971 // Build expression: UB = min(UB, LastIteration)
2972 // It is nesessary for CodeGen of directives with static scheduling.
2973 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2974 UB.get(), LastIteration.get());
2975 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2976 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2977 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2978 CondOp.get());
2979 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2980 }
2981
2982 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002983 ExprResult IV;
2984 ExprResult Init;
2985 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002986 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2987 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002988 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2989 ? LB.get()
2990 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2991 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2992 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002993 }
2994
Alexander Musmanc6388682014-12-15 07:07:06 +00002995 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002996 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002997 ExprResult Cond =
2998 isOpenMPWorksharingDirective(DKind)
2999 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3000 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3001 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003002
3003 // Loop increment (IV = IV + 1)
3004 SourceLocation IncLoc;
3005 ExprResult Inc =
3006 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3007 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3008 if (!Inc.isUsable())
3009 return 0;
3010 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00003011 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3012 if (!Inc.isUsable())
3013 return 0;
3014
3015 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3016 // Used for directives with static scheduling.
3017 ExprResult NextLB, NextUB;
3018 if (isOpenMPWorksharingDirective(DKind)) {
3019 // LB + ST
3020 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3021 if (!NextLB.isUsable())
3022 return 0;
3023 // LB = LB + ST
3024 NextLB =
3025 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3026 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3027 if (!NextLB.isUsable())
3028 return 0;
3029 // UB + ST
3030 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3031 if (!NextUB.isUsable())
3032 return 0;
3033 // UB = UB + ST
3034 NextUB =
3035 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3036 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3037 if (!NextUB.isUsable())
3038 return 0;
3039 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003040
3041 // Build updates and final values of the loop counters.
3042 bool HasErrors = false;
3043 Built.Counters.resize(NestedLoopCount);
3044 Built.Updates.resize(NestedLoopCount);
3045 Built.Finals.resize(NestedLoopCount);
3046 {
3047 ExprResult Div;
3048 // Go from inner nested loop to outer.
3049 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3050 LoopIterationSpace &IS = IterSpaces[Cnt];
3051 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3052 // Build: Iter = (IV / Div) % IS.NumIters
3053 // where Div is product of previous iterations' IS.NumIters.
3054 ExprResult Iter;
3055 if (Div.isUsable()) {
3056 Iter =
3057 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3058 } else {
3059 Iter = IV;
3060 assert((Cnt == (int)NestedLoopCount - 1) &&
3061 "unusable div expected on first iteration only");
3062 }
3063
3064 if (Cnt != 0 && Iter.isUsable())
3065 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3066 IS.NumIterations);
3067 if (!Iter.isUsable()) {
3068 HasErrors = true;
3069 break;
3070 }
3071
Alexey Bataev39f915b82015-05-08 10:41:21 +00003072 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3073 auto *CounterVar = buildDeclRefExpr(
3074 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3075 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3076 /*RefersToCapture=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003077 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003078 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003079 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3080 if (!Update.isUsable()) {
3081 HasErrors = true;
3082 break;
3083 }
3084
3085 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3086 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003087 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003088 IS.NumIterations, IS.CounterStep, IS.Subtract);
3089 if (!Final.isUsable()) {
3090 HasErrors = true;
3091 break;
3092 }
3093
3094 // Build Div for the next iteration: Div <- Div * IS.NumIters
3095 if (Cnt != 0) {
3096 if (Div.isUnset())
3097 Div = IS.NumIterations;
3098 else
3099 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3100 IS.NumIterations);
3101
3102 // Add parentheses (for debugging purposes only).
3103 if (Div.isUsable())
3104 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3105 if (!Div.isUsable()) {
3106 HasErrors = true;
3107 break;
3108 }
3109 }
3110 if (!Update.isUsable() || !Final.isUsable()) {
3111 HasErrors = true;
3112 break;
3113 }
3114 // Save results
3115 Built.Counters[Cnt] = IS.CounterVar;
3116 Built.Updates[Cnt] = Update.get();
3117 Built.Finals[Cnt] = Final.get();
3118 }
3119 }
3120
3121 if (HasErrors)
3122 return 0;
3123
3124 // Save results
3125 Built.IterationVarRef = IV.get();
3126 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003127 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003128 Built.CalcLastIteration = CalcLastIteration.get();
3129 Built.PreCond = PreCond.get();
3130 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003131 Built.Init = Init.get();
3132 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003133 Built.LB = LB.get();
3134 Built.UB = UB.get();
3135 Built.IL = IL.get();
3136 Built.ST = ST.get();
3137 Built.EUB = EUB.get();
3138 Built.NLB = NextLB.get();
3139 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003140
Alexey Bataevabfc0692014-06-25 06:52:00 +00003141 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003142}
3143
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003144static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevc925aa32015-04-27 08:00:32 +00003145 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003146 return C->getClauseKind() == OMPC_collapse;
3147 };
3148 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
Alexey Bataevc925aa32015-04-27 08:00:32 +00003149 Clauses, std::move(CollapseFilter));
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003150 if (I)
3151 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3152 return nullptr;
3153}
3154
Alexey Bataev4acb8592014-07-07 13:01:15 +00003155StmtResult Sema::ActOnOpenMPSimdDirective(
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;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +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_simd, 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 Bataev1b59ab52014-02-27 08:29:12 +00003165 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003166
Alexander Musmana5f070a2014-10-01 06:03:56 +00003167 assert((CurContext->isDependentContext() || B.builtAll()) &&
3168 "omp simd loop exprs were not built");
3169
Alexander Musman3276a272015-03-21 10:12:56 +00003170 if (!CurContext->isDependentContext()) {
3171 // Finalize the clauses that need pre-built expressions for CodeGen.
3172 for (auto C : Clauses) {
3173 if (auto LC = dyn_cast<OMPLinearClause>(C))
3174 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3175 B.NumIterations, *this, CurScope))
3176 return StmtError();
3177 }
3178 }
3179
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003180 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003181 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3182 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003183}
3184
Alexey Bataev4acb8592014-07-07 13:01:15 +00003185StmtResult Sema::ActOnOpenMPForDirective(
3186 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3187 SourceLocation EndLoc,
3188 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003189 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003190 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003191 unsigned NestedLoopCount =
3192 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003193 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003194 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003195 return StmtError();
3196
Alexander Musmana5f070a2014-10-01 06:03:56 +00003197 assert((CurContext->isDependentContext() || B.builtAll()) &&
3198 "omp for loop exprs were not built");
3199
Alexey Bataevf29276e2014-06-18 04:14:57 +00003200 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003201 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3202 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003203}
3204
Alexander Musmanf82886e2014-09-18 05:12:34 +00003205StmtResult Sema::ActOnOpenMPForSimdDirective(
3206 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3207 SourceLocation EndLoc,
3208 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003209 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003210 // In presence of clause 'collapse', it will define the nested loops number.
3211 unsigned NestedLoopCount =
3212 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003213 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003214 if (NestedLoopCount == 0)
3215 return StmtError();
3216
Alexander Musmanc6388682014-12-15 07:07:06 +00003217 assert((CurContext->isDependentContext() || B.builtAll()) &&
3218 "omp for simd loop exprs were not built");
3219
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00003220 if (!CurContext->isDependentContext()) {
3221 // Finalize the clauses that need pre-built expressions for CodeGen.
3222 for (auto C : Clauses) {
3223 if (auto LC = dyn_cast<OMPLinearClause>(C))
3224 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3225 B.NumIterations, *this, CurScope))
3226 return StmtError();
3227 }
3228 }
3229
Alexander Musmanf82886e2014-09-18 05:12:34 +00003230 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003231 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3232 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003233}
3234
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003235StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3236 Stmt *AStmt,
3237 SourceLocation StartLoc,
3238 SourceLocation EndLoc) {
3239 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3240 auto BaseStmt = AStmt;
3241 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3242 BaseStmt = CS->getCapturedStmt();
3243 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3244 auto S = C->children();
3245 if (!S)
3246 return StmtError();
3247 // All associated statements must be '#pragma omp section' except for
3248 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003249 for (++S; S; ++S) {
3250 auto SectionStmt = *S;
3251 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3252 if (SectionStmt)
3253 Diag(SectionStmt->getLocStart(),
3254 diag::err_omp_sections_substmt_not_section);
3255 return StmtError();
3256 }
3257 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003258 } else {
3259 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3260 return StmtError();
3261 }
3262
3263 getCurFunction()->setHasBranchProtectedScope();
3264
3265 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3266 AStmt);
3267}
3268
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003269StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3270 SourceLocation StartLoc,
3271 SourceLocation EndLoc) {
3272 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3273
3274 getCurFunction()->setHasBranchProtectedScope();
3275
3276 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3277}
3278
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003279StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3280 Stmt *AStmt,
3281 SourceLocation StartLoc,
3282 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003283 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3284
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003285 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003286
Alexey Bataev3255bf32015-01-19 05:20:46 +00003287 // OpenMP [2.7.3, single Construct, Restrictions]
3288 // The copyprivate clause must not be used with the nowait clause.
3289 OMPClause *Nowait = nullptr;
3290 OMPClause *Copyprivate = nullptr;
3291 for (auto *Clause : Clauses) {
3292 if (Clause->getClauseKind() == OMPC_nowait)
3293 Nowait = Clause;
3294 else if (Clause->getClauseKind() == OMPC_copyprivate)
3295 Copyprivate = Clause;
3296 if (Copyprivate && Nowait) {
3297 Diag(Copyprivate->getLocStart(),
3298 diag::err_omp_single_copyprivate_with_nowait);
3299 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3300 return StmtError();
3301 }
3302 }
3303
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003304 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3305}
3306
Alexander Musman80c22892014-07-17 08:54:58 +00003307StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3308 SourceLocation StartLoc,
3309 SourceLocation EndLoc) {
3310 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3311
3312 getCurFunction()->setHasBranchProtectedScope();
3313
3314 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3315}
3316
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003317StmtResult
3318Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3319 Stmt *AStmt, SourceLocation StartLoc,
3320 SourceLocation EndLoc) {
3321 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3322
3323 getCurFunction()->setHasBranchProtectedScope();
3324
3325 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3326 AStmt);
3327}
3328
Alexey Bataev4acb8592014-07-07 13:01:15 +00003329StmtResult Sema::ActOnOpenMPParallelForDirective(
3330 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3331 SourceLocation EndLoc,
3332 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3333 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3334 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3335 // 1.2.2 OpenMP Language Terminology
3336 // Structured block - An executable statement with a single entry at the
3337 // top and a single exit at the bottom.
3338 // The point of exit cannot be a branch out of the structured block.
3339 // longjmp() and throw() must not violate the entry/exit criteria.
3340 CS->getCapturedDecl()->setNothrow();
3341
Alexander Musmanc6388682014-12-15 07:07:06 +00003342 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003343 // In presence of clause 'collapse', it will define the nested loops number.
3344 unsigned NestedLoopCount =
3345 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003346 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003347 if (NestedLoopCount == 0)
3348 return StmtError();
3349
Alexander Musmana5f070a2014-10-01 06:03:56 +00003350 assert((CurContext->isDependentContext() || B.builtAll()) &&
3351 "omp parallel for loop exprs were not built");
3352
Alexey Bataev4acb8592014-07-07 13:01:15 +00003353 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003354 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3355 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003356}
3357
Alexander Musmane4e893b2014-09-23 09:33:00 +00003358StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3359 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3360 SourceLocation EndLoc,
3361 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3362 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3363 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3364 // 1.2.2 OpenMP Language Terminology
3365 // Structured block - An executable statement with a single entry at the
3366 // top and a single exit at the bottom.
3367 // The point of exit cannot be a branch out of the structured block.
3368 // longjmp() and throw() must not violate the entry/exit criteria.
3369 CS->getCapturedDecl()->setNothrow();
3370
Alexander Musmanc6388682014-12-15 07:07:06 +00003371 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003372 // In presence of clause 'collapse', it will define the nested loops number.
3373 unsigned NestedLoopCount =
3374 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003375 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003376 if (NestedLoopCount == 0)
3377 return StmtError();
3378
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00003379 if (!CurContext->isDependentContext()) {
3380 // Finalize the clauses that need pre-built expressions for CodeGen.
3381 for (auto C : Clauses) {
3382 if (auto LC = dyn_cast<OMPLinearClause>(C))
3383 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3384 B.NumIterations, *this, CurScope))
3385 return StmtError();
3386 }
3387 }
3388
Alexander Musmane4e893b2014-09-23 09:33:00 +00003389 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003390 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003391 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003392}
3393
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003394StmtResult
3395Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3396 Stmt *AStmt, SourceLocation StartLoc,
3397 SourceLocation EndLoc) {
3398 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3399 auto BaseStmt = AStmt;
3400 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3401 BaseStmt = CS->getCapturedStmt();
3402 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3403 auto S = C->children();
3404 if (!S)
3405 return StmtError();
3406 // All associated statements must be '#pragma omp section' except for
3407 // the first one.
3408 for (++S; S; ++S) {
3409 auto SectionStmt = *S;
3410 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3411 if (SectionStmt)
3412 Diag(SectionStmt->getLocStart(),
3413 diag::err_omp_parallel_sections_substmt_not_section);
3414 return StmtError();
3415 }
3416 }
3417 } else {
3418 Diag(AStmt->getLocStart(),
3419 diag::err_omp_parallel_sections_not_compound_stmt);
3420 return StmtError();
3421 }
3422
3423 getCurFunction()->setHasBranchProtectedScope();
3424
3425 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3426 Clauses, AStmt);
3427}
3428
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003429StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3430 Stmt *AStmt, SourceLocation StartLoc,
3431 SourceLocation EndLoc) {
3432 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3433 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3434 // 1.2.2 OpenMP Language Terminology
3435 // Structured block - An executable statement with a single entry at the
3436 // top and a single exit at the bottom.
3437 // The point of exit cannot be a branch out of the structured block.
3438 // longjmp() and throw() must not violate the entry/exit criteria.
3439 CS->getCapturedDecl()->setNothrow();
3440
3441 getCurFunction()->setHasBranchProtectedScope();
3442
3443 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3444}
3445
Alexey Bataev68446b72014-07-18 07:47:19 +00003446StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3447 SourceLocation EndLoc) {
3448 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3449}
3450
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003451StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3452 SourceLocation EndLoc) {
3453 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3454}
3455
Alexey Bataev2df347a2014-07-18 10:17:07 +00003456StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3457 SourceLocation EndLoc) {
3458 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3459}
3460
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003461StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
3462 SourceLocation StartLoc,
3463 SourceLocation EndLoc) {
3464 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3465
3466 getCurFunction()->setHasBranchProtectedScope();
3467
3468 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
3469}
3470
Alexey Bataev6125da92014-07-21 11:26:11 +00003471StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3472 SourceLocation StartLoc,
3473 SourceLocation EndLoc) {
3474 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3475 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3476}
3477
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003478StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3479 SourceLocation StartLoc,
3480 SourceLocation EndLoc) {
3481 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3482
3483 getCurFunction()->setHasBranchProtectedScope();
3484
3485 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3486}
3487
Alexey Bataev1d160b12015-03-13 12:27:31 +00003488namespace {
3489/// \brief Helper class for checking expression in 'omp atomic [update]'
3490/// construct.
3491class OpenMPAtomicUpdateChecker {
3492 /// \brief Error results for atomic update expressions.
3493 enum ExprAnalysisErrorCode {
3494 /// \brief A statement is not an expression statement.
3495 NotAnExpression,
3496 /// \brief Expression is not builtin binary or unary operation.
3497 NotABinaryOrUnaryExpression,
3498 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3499 NotAnUnaryIncDecExpression,
3500 /// \brief An expression is not of scalar type.
3501 NotAScalarType,
3502 /// \brief A binary operation is not an assignment operation.
3503 NotAnAssignmentOp,
3504 /// \brief RHS part of the binary operation is not a binary expression.
3505 NotABinaryExpression,
3506 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3507 /// expression.
3508 NotABinaryOperator,
3509 /// \brief RHS binary operation does not have reference to the updated LHS
3510 /// part.
3511 NotAnUpdateExpression,
3512 /// \brief No errors is found.
3513 NoError
3514 };
3515 /// \brief Reference to Sema.
3516 Sema &SemaRef;
3517 /// \brief A location for note diagnostics (when error is found).
3518 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003519 /// \brief 'x' lvalue part of the source atomic expression.
3520 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003521 /// \brief 'expr' rvalue part of the source atomic expression.
3522 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003523 /// \brief Helper expression of the form
3524 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3525 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3526 Expr *UpdateExpr;
3527 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3528 /// important for non-associative operations.
3529 bool IsXLHSInRHSPart;
3530 BinaryOperatorKind Op;
3531 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003532 /// \brief true if the source expression is a postfix unary operation, false
3533 /// if it is a prefix unary operation.
3534 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003535
3536public:
3537 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003538 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003539 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003540 /// \brief Check specified statement that it is suitable for 'atomic update'
3541 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003542 /// expression. If DiagId and NoteId == 0, then only check is performed
3543 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003544 /// \param DiagId Diagnostic which should be emitted if error is found.
3545 /// \param NoteId Diagnostic note for the main error message.
3546 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003547 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003548 /// \brief Return the 'x' lvalue part of the source atomic expression.
3549 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003550 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3551 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003552 /// \brief Return the update expression used in calculation of the updated
3553 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3554 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3555 Expr *getUpdateExpr() const { return UpdateExpr; }
3556 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3557 /// false otherwise.
3558 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3559
Alexey Bataevb78ca832015-04-01 03:33:17 +00003560 /// \brief true if the source expression is a postfix unary operation, false
3561 /// if it is a prefix unary operation.
3562 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3563
Alexey Bataev1d160b12015-03-13 12:27:31 +00003564private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003565 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3566 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003567};
3568} // namespace
3569
3570bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3571 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3572 ExprAnalysisErrorCode ErrorFound = NoError;
3573 SourceLocation ErrorLoc, NoteLoc;
3574 SourceRange ErrorRange, NoteRange;
3575 // Allowed constructs are:
3576 // x = x binop expr;
3577 // x = expr binop x;
3578 if (AtomicBinOp->getOpcode() == BO_Assign) {
3579 X = AtomicBinOp->getLHS();
3580 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3581 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3582 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3583 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3584 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003585 Op = AtomicInnerBinOp->getOpcode();
3586 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003587 auto *LHS = AtomicInnerBinOp->getLHS();
3588 auto *RHS = AtomicInnerBinOp->getRHS();
3589 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3590 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3591 /*Canonical=*/true);
3592 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3593 /*Canonical=*/true);
3594 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3595 /*Canonical=*/true);
3596 if (XId == LHSId) {
3597 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003598 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003599 } else if (XId == RHSId) {
3600 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003601 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003602 } else {
3603 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3604 ErrorRange = AtomicInnerBinOp->getSourceRange();
3605 NoteLoc = X->getExprLoc();
3606 NoteRange = X->getSourceRange();
3607 ErrorFound = NotAnUpdateExpression;
3608 }
3609 } else {
3610 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3611 ErrorRange = AtomicInnerBinOp->getSourceRange();
3612 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3613 NoteRange = SourceRange(NoteLoc, NoteLoc);
3614 ErrorFound = NotABinaryOperator;
3615 }
3616 } else {
3617 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3618 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3619 ErrorFound = NotABinaryExpression;
3620 }
3621 } else {
3622 ErrorLoc = AtomicBinOp->getExprLoc();
3623 ErrorRange = AtomicBinOp->getSourceRange();
3624 NoteLoc = AtomicBinOp->getOperatorLoc();
3625 NoteRange = SourceRange(NoteLoc, NoteLoc);
3626 ErrorFound = NotAnAssignmentOp;
3627 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003628 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003629 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3630 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3631 return true;
3632 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003633 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003634 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003635}
3636
3637bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3638 unsigned NoteId) {
3639 ExprAnalysisErrorCode ErrorFound = NoError;
3640 SourceLocation ErrorLoc, NoteLoc;
3641 SourceRange ErrorRange, NoteRange;
3642 // Allowed constructs are:
3643 // x++;
3644 // x--;
3645 // ++x;
3646 // --x;
3647 // x binop= expr;
3648 // x = x binop expr;
3649 // x = expr binop x;
3650 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3651 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3652 if (AtomicBody->getType()->isScalarType() ||
3653 AtomicBody->isInstantiationDependent()) {
3654 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3655 AtomicBody->IgnoreParenImpCasts())) {
3656 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003657 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003658 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003659 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003660 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003661 X = AtomicCompAssignOp->getLHS();
3662 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003663 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3664 AtomicBody->IgnoreParenImpCasts())) {
3665 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003666 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3667 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003668 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003669 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3670 // Check for Unary Operation
3671 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003672 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003673 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3674 OpLoc = AtomicUnaryOp->getOperatorLoc();
3675 X = AtomicUnaryOp->getSubExpr();
3676 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3677 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003678 } else {
3679 ErrorFound = NotAnUnaryIncDecExpression;
3680 ErrorLoc = AtomicUnaryOp->getExprLoc();
3681 ErrorRange = AtomicUnaryOp->getSourceRange();
3682 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3683 NoteRange = SourceRange(NoteLoc, NoteLoc);
3684 }
3685 } else {
3686 ErrorFound = NotABinaryOrUnaryExpression;
3687 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3688 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3689 }
3690 } else {
3691 ErrorFound = NotAScalarType;
3692 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3693 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3694 }
3695 } else {
3696 ErrorFound = NotAnExpression;
3697 NoteLoc = ErrorLoc = S->getLocStart();
3698 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3699 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003700 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003701 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3702 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3703 return true;
3704 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003705 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003706 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003707 // Build an update expression of form 'OpaqueValueExpr(x) binop
3708 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3709 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3710 auto *OVEX = new (SemaRef.getASTContext())
3711 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3712 auto *OVEExpr = new (SemaRef.getASTContext())
3713 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3714 auto Update =
3715 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3716 IsXLHSInRHSPart ? OVEExpr : OVEX);
3717 if (Update.isInvalid())
3718 return true;
3719 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3720 Sema::AA_Casting);
3721 if (Update.isInvalid())
3722 return true;
3723 UpdateExpr = Update.get();
3724 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003725 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003726}
3727
Alexey Bataev0162e452014-07-22 10:10:35 +00003728StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3729 Stmt *AStmt,
3730 SourceLocation StartLoc,
3731 SourceLocation EndLoc) {
3732 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003733 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003734 // 1.2.2 OpenMP Language Terminology
3735 // Structured block - An executable statement with a single entry at the
3736 // top and a single exit at the bottom.
3737 // The point of exit cannot be a branch out of the structured block.
3738 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003739 OpenMPClauseKind AtomicKind = OMPC_unknown;
3740 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003741 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003742 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003743 C->getClauseKind() == OMPC_update ||
3744 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003745 if (AtomicKind != OMPC_unknown) {
3746 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3747 << SourceRange(C->getLocStart(), C->getLocEnd());
3748 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3749 << getOpenMPClauseName(AtomicKind);
3750 } else {
3751 AtomicKind = C->getClauseKind();
3752 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003753 }
3754 }
3755 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003756
Alexey Bataev459dec02014-07-24 06:46:57 +00003757 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003758 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3759 Body = EWC->getSubExpr();
3760
Alexey Bataev62cec442014-11-18 10:14:22 +00003761 Expr *X = nullptr;
3762 Expr *V = nullptr;
3763 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003764 Expr *UE = nullptr;
3765 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003766 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003767 // OpenMP [2.12.6, atomic Construct]
3768 // In the next expressions:
3769 // * x and v (as applicable) are both l-value expressions with scalar type.
3770 // * During the execution of an atomic region, multiple syntactic
3771 // occurrences of x must designate the same storage location.
3772 // * Neither of v and expr (as applicable) may access the storage location
3773 // designated by x.
3774 // * Neither of x and expr (as applicable) may access the storage location
3775 // designated by v.
3776 // * expr is an expression with scalar type.
3777 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3778 // * binop, binop=, ++, and -- are not overloaded operators.
3779 // * The expression x binop expr must be numerically equivalent to x binop
3780 // (expr). This requirement is satisfied if the operators in expr have
3781 // precedence greater than binop, or by using parentheses around expr or
3782 // subexpressions of expr.
3783 // * The expression expr binop x must be numerically equivalent to (expr)
3784 // binop x. This requirement is satisfied if the operators in expr have
3785 // precedence equal to or greater than binop, or by using parentheses around
3786 // expr or subexpressions of expr.
3787 // * For forms that allow multiple occurrences of x, the number of times
3788 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003789 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003790 enum {
3791 NotAnExpression,
3792 NotAnAssignmentOp,
3793 NotAScalarType,
3794 NotAnLValue,
3795 NoError
3796 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003797 SourceLocation ErrorLoc, NoteLoc;
3798 SourceRange ErrorRange, NoteRange;
3799 // If clause is read:
3800 // v = x;
3801 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3802 auto AtomicBinOp =
3803 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3804 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3805 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3806 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3807 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3808 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3809 if (!X->isLValue() || !V->isLValue()) {
3810 auto NotLValueExpr = X->isLValue() ? V : X;
3811 ErrorFound = NotAnLValue;
3812 ErrorLoc = AtomicBinOp->getExprLoc();
3813 ErrorRange = AtomicBinOp->getSourceRange();
3814 NoteLoc = NotLValueExpr->getExprLoc();
3815 NoteRange = NotLValueExpr->getSourceRange();
3816 }
3817 } else if (!X->isInstantiationDependent() ||
3818 !V->isInstantiationDependent()) {
3819 auto NotScalarExpr =
3820 (X->isInstantiationDependent() || X->getType()->isScalarType())
3821 ? V
3822 : X;
3823 ErrorFound = NotAScalarType;
3824 ErrorLoc = AtomicBinOp->getExprLoc();
3825 ErrorRange = AtomicBinOp->getSourceRange();
3826 NoteLoc = NotScalarExpr->getExprLoc();
3827 NoteRange = NotScalarExpr->getSourceRange();
3828 }
3829 } else {
3830 ErrorFound = NotAnAssignmentOp;
3831 ErrorLoc = AtomicBody->getExprLoc();
3832 ErrorRange = AtomicBody->getSourceRange();
3833 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3834 : AtomicBody->getExprLoc();
3835 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3836 : AtomicBody->getSourceRange();
3837 }
3838 } else {
3839 ErrorFound = NotAnExpression;
3840 NoteLoc = ErrorLoc = Body->getLocStart();
3841 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003842 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003843 if (ErrorFound != NoError) {
3844 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3845 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003846 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3847 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003848 return StmtError();
3849 } else if (CurContext->isDependentContext())
3850 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003851 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003852 enum {
3853 NotAnExpression,
3854 NotAnAssignmentOp,
3855 NotAScalarType,
3856 NotAnLValue,
3857 NoError
3858 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003859 SourceLocation ErrorLoc, NoteLoc;
3860 SourceRange ErrorRange, NoteRange;
3861 // If clause is write:
3862 // x = expr;
3863 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3864 auto AtomicBinOp =
3865 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3866 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003867 X = AtomicBinOp->getLHS();
3868 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003869 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3870 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3871 if (!X->isLValue()) {
3872 ErrorFound = NotAnLValue;
3873 ErrorLoc = AtomicBinOp->getExprLoc();
3874 ErrorRange = AtomicBinOp->getSourceRange();
3875 NoteLoc = X->getExprLoc();
3876 NoteRange = X->getSourceRange();
3877 }
3878 } else if (!X->isInstantiationDependent() ||
3879 !E->isInstantiationDependent()) {
3880 auto NotScalarExpr =
3881 (X->isInstantiationDependent() || X->getType()->isScalarType())
3882 ? E
3883 : X;
3884 ErrorFound = NotAScalarType;
3885 ErrorLoc = AtomicBinOp->getExprLoc();
3886 ErrorRange = AtomicBinOp->getSourceRange();
3887 NoteLoc = NotScalarExpr->getExprLoc();
3888 NoteRange = NotScalarExpr->getSourceRange();
3889 }
3890 } else {
3891 ErrorFound = NotAnAssignmentOp;
3892 ErrorLoc = AtomicBody->getExprLoc();
3893 ErrorRange = AtomicBody->getSourceRange();
3894 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3895 : AtomicBody->getExprLoc();
3896 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3897 : AtomicBody->getSourceRange();
3898 }
3899 } else {
3900 ErrorFound = NotAnExpression;
3901 NoteLoc = ErrorLoc = Body->getLocStart();
3902 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003903 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003904 if (ErrorFound != NoError) {
3905 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3906 << ErrorRange;
3907 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3908 << NoteRange;
3909 return StmtError();
3910 } else if (CurContext->isDependentContext())
3911 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003912 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003913 // If clause is update:
3914 // x++;
3915 // x--;
3916 // ++x;
3917 // --x;
3918 // x binop= expr;
3919 // x = x binop expr;
3920 // x = expr binop x;
3921 OpenMPAtomicUpdateChecker Checker(*this);
3922 if (Checker.checkStatement(
3923 Body, (AtomicKind == OMPC_update)
3924 ? diag::err_omp_atomic_update_not_expression_statement
3925 : diag::err_omp_atomic_not_expression_statement,
3926 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003927 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003928 if (!CurContext->isDependentContext()) {
3929 E = Checker.getExpr();
3930 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003931 UE = Checker.getUpdateExpr();
3932 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003933 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003934 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003935 enum {
3936 NotAnAssignmentOp,
3937 NotACompoundStatement,
3938 NotTwoSubstatements,
3939 NotASpecificExpression,
3940 NoError
3941 } ErrorFound = NoError;
3942 SourceLocation ErrorLoc, NoteLoc;
3943 SourceRange ErrorRange, NoteRange;
3944 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3945 // If clause is a capture:
3946 // v = x++;
3947 // v = x--;
3948 // v = ++x;
3949 // v = --x;
3950 // v = x binop= expr;
3951 // v = x = x binop expr;
3952 // v = x = expr binop x;
3953 auto *AtomicBinOp =
3954 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3955 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3956 V = AtomicBinOp->getLHS();
3957 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3958 OpenMPAtomicUpdateChecker Checker(*this);
3959 if (Checker.checkStatement(
3960 Body, diag::err_omp_atomic_capture_not_expression_statement,
3961 diag::note_omp_atomic_update))
3962 return StmtError();
3963 E = Checker.getExpr();
3964 X = Checker.getX();
3965 UE = Checker.getUpdateExpr();
3966 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3967 IsPostfixUpdate = Checker.isPostfixUpdate();
3968 } else {
3969 ErrorLoc = AtomicBody->getExprLoc();
3970 ErrorRange = AtomicBody->getSourceRange();
3971 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3972 : AtomicBody->getExprLoc();
3973 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3974 : AtomicBody->getSourceRange();
3975 ErrorFound = NotAnAssignmentOp;
3976 }
3977 if (ErrorFound != NoError) {
3978 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3979 << ErrorRange;
3980 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3981 return StmtError();
3982 } else if (CurContext->isDependentContext()) {
3983 UE = V = E = X = nullptr;
3984 }
3985 } else {
3986 // If clause is a capture:
3987 // { v = x; x = expr; }
3988 // { v = x; x++; }
3989 // { v = x; x--; }
3990 // { v = x; ++x; }
3991 // { v = x; --x; }
3992 // { v = x; x binop= expr; }
3993 // { v = x; x = x binop expr; }
3994 // { v = x; x = expr binop x; }
3995 // { x++; v = x; }
3996 // { x--; v = x; }
3997 // { ++x; v = x; }
3998 // { --x; v = x; }
3999 // { x binop= expr; v = x; }
4000 // { x = x binop expr; v = x; }
4001 // { x = expr binop x; v = x; }
4002 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4003 // Check that this is { expr1; expr2; }
4004 if (CS->size() == 2) {
4005 auto *First = CS->body_front();
4006 auto *Second = CS->body_back();
4007 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4008 First = EWC->getSubExpr()->IgnoreParenImpCasts();
4009 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4010 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4011 // Need to find what subexpression is 'v' and what is 'x'.
4012 OpenMPAtomicUpdateChecker Checker(*this);
4013 bool IsUpdateExprFound = !Checker.checkStatement(Second);
4014 BinaryOperator *BinOp = nullptr;
4015 if (IsUpdateExprFound) {
4016 BinOp = dyn_cast<BinaryOperator>(First);
4017 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4018 }
4019 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4020 // { v = x; x++; }
4021 // { v = x; x--; }
4022 // { v = x; ++x; }
4023 // { v = x; --x; }
4024 // { v = x; x binop= expr; }
4025 // { v = x; x = x binop expr; }
4026 // { v = x; x = expr binop x; }
4027 // Check that the first 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 = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004040 }
4041 }
4042 if (!IsUpdateExprFound) {
4043 IsUpdateExprFound = !Checker.checkStatement(First);
4044 BinOp = nullptr;
4045 if (IsUpdateExprFound) {
4046 BinOp = dyn_cast<BinaryOperator>(Second);
4047 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4048 }
4049 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4050 // { x++; v = x; }
4051 // { x--; v = x; }
4052 // { ++x; v = x; }
4053 // { --x; v = x; }
4054 // { x binop= expr; v = x; }
4055 // { x = x binop expr; v = x; }
4056 // { x = expr binop x; v = x; }
4057 // Check that the second expression has form v = x.
4058 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4059 llvm::FoldingSetNodeID XId, PossibleXId;
4060 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4061 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4062 IsUpdateExprFound = XId == PossibleXId;
4063 if (IsUpdateExprFound) {
4064 V = BinOp->getLHS();
4065 X = Checker.getX();
4066 E = Checker.getExpr();
4067 UE = Checker.getUpdateExpr();
4068 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004069 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004070 }
4071 }
4072 }
4073 if (!IsUpdateExprFound) {
4074 // { v = x; x = expr; }
4075 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4076 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
4077 ErrorFound = NotAnAssignmentOp;
4078 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4079 : First->getLocStart();
4080 NoteRange = ErrorRange = FirstBinOp
4081 ? FirstBinOp->getSourceRange()
4082 : SourceRange(ErrorLoc, ErrorLoc);
4083 } else {
4084 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4085 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4086 ErrorFound = NotAnAssignmentOp;
4087 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
4088 : Second->getLocStart();
4089 NoteRange = ErrorRange = SecondBinOp
4090 ? SecondBinOp->getSourceRange()
4091 : SourceRange(ErrorLoc, ErrorLoc);
4092 } else {
4093 auto *PossibleXRHSInFirst =
4094 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4095 auto *PossibleXLHSInSecond =
4096 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4097 llvm::FoldingSetNodeID X1Id, X2Id;
4098 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4099 PossibleXLHSInSecond->Profile(X2Id, Context,
4100 /*Canonical=*/true);
4101 IsUpdateExprFound = X1Id == X2Id;
4102 if (IsUpdateExprFound) {
4103 V = FirstBinOp->getLHS();
4104 X = SecondBinOp->getLHS();
4105 E = SecondBinOp->getRHS();
4106 UE = nullptr;
4107 IsXLHSInRHSPart = false;
4108 IsPostfixUpdate = true;
4109 } else {
4110 ErrorFound = NotASpecificExpression;
4111 ErrorLoc = FirstBinOp->getExprLoc();
4112 ErrorRange = FirstBinOp->getSourceRange();
4113 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4114 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4115 }
4116 }
4117 }
4118 }
4119 } else {
4120 NoteLoc = ErrorLoc = Body->getLocStart();
4121 NoteRange = ErrorRange =
4122 SourceRange(Body->getLocStart(), Body->getLocStart());
4123 ErrorFound = NotTwoSubstatements;
4124 }
4125 } else {
4126 NoteLoc = ErrorLoc = Body->getLocStart();
4127 NoteRange = ErrorRange =
4128 SourceRange(Body->getLocStart(), Body->getLocStart());
4129 ErrorFound = NotACompoundStatement;
4130 }
4131 if (ErrorFound != NoError) {
4132 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4133 << ErrorRange;
4134 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4135 return StmtError();
4136 } else if (CurContext->isDependentContext()) {
4137 UE = V = E = X = nullptr;
4138 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004139 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004140 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004141
4142 getCurFunction()->setHasBranchProtectedScope();
4143
Alexey Bataev62cec442014-11-18 10:14:22 +00004144 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004145 X, V, E, UE, IsXLHSInRHSPart,
4146 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004147}
4148
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004149StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4150 Stmt *AStmt,
4151 SourceLocation StartLoc,
4152 SourceLocation EndLoc) {
4153 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4154
Alexey Bataev13314bf2014-10-09 04:18:56 +00004155 // OpenMP [2.16, Nesting of Regions]
4156 // If specified, a teams construct must be contained within a target
4157 // construct. That target construct must contain no statements or directives
4158 // outside of the teams construct.
4159 if (DSAStack->hasInnerTeamsRegion()) {
4160 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4161 bool OMPTeamsFound = true;
4162 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4163 auto I = CS->body_begin();
4164 while (I != CS->body_end()) {
4165 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4166 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4167 OMPTeamsFound = false;
4168 break;
4169 }
4170 ++I;
4171 }
4172 assert(I != CS->body_end() && "Not found statement");
4173 S = *I;
4174 }
4175 if (!OMPTeamsFound) {
4176 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4177 Diag(DSAStack->getInnerTeamsRegionLoc(),
4178 diag::note_omp_nested_teams_construct_here);
4179 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4180 << isa<OMPExecutableDirective>(S);
4181 return StmtError();
4182 }
4183 }
4184
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004185 getCurFunction()->setHasBranchProtectedScope();
4186
4187 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4188}
4189
Alexey Bataev13314bf2014-10-09 04:18:56 +00004190StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4191 Stmt *AStmt, SourceLocation StartLoc,
4192 SourceLocation EndLoc) {
4193 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4194 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4195 // 1.2.2 OpenMP Language Terminology
4196 // Structured block - An executable statement with a single entry at the
4197 // top and a single exit at the bottom.
4198 // The point of exit cannot be a branch out of the structured block.
4199 // longjmp() and throw() must not violate the entry/exit criteria.
4200 CS->getCapturedDecl()->setNothrow();
4201
4202 getCurFunction()->setHasBranchProtectedScope();
4203
4204 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4205}
4206
Alexey Bataeved09d242014-05-28 05:53:51 +00004207OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004208 SourceLocation StartLoc,
4209 SourceLocation LParenLoc,
4210 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004211 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004212 switch (Kind) {
4213 case OMPC_if:
4214 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4215 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004216 case OMPC_final:
4217 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4218 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004219 case OMPC_num_threads:
4220 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4221 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004222 case OMPC_safelen:
4223 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4224 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004225 case OMPC_collapse:
4226 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4227 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004228 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004229 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004230 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004231 case OMPC_private:
4232 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004233 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004234 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004235 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004236 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004237 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004238 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004239 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004240 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004241 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004242 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004243 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004244 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004245 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004246 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004247 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004248 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004249 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004250 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004251 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004252 llvm_unreachable("Clause is not allowed.");
4253 }
4254 return Res;
4255}
4256
Alexey Bataeved09d242014-05-28 05:53:51 +00004257OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004258 SourceLocation LParenLoc,
4259 SourceLocation EndLoc) {
4260 Expr *ValExpr = Condition;
4261 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4262 !Condition->isInstantiationDependent() &&
4263 !Condition->containsUnexpandedParameterPack()) {
4264 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004265 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004266 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004267 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004268
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004269 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004270 }
4271
4272 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4273}
4274
Alexey Bataev3778b602014-07-17 07:32:53 +00004275OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4276 SourceLocation StartLoc,
4277 SourceLocation LParenLoc,
4278 SourceLocation EndLoc) {
4279 Expr *ValExpr = Condition;
4280 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4281 !Condition->isInstantiationDependent() &&
4282 !Condition->containsUnexpandedParameterPack()) {
4283 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4284 Condition->getExprLoc(), Condition);
4285 if (Val.isInvalid())
4286 return nullptr;
4287
4288 ValExpr = Val.get();
4289 }
4290
4291 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4292}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004293ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4294 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004295 if (!Op)
4296 return ExprError();
4297
4298 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4299 public:
4300 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004301 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004302 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4303 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004304 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4305 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004306 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4307 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004308 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4309 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004310 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4311 QualType T,
4312 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004313 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4314 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004315 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4316 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004317 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004318 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004319 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004320 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4321 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004322 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4323 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004324 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4325 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004326 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004327 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004328 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004329 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4330 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004331 llvm_unreachable("conversion functions are permitted");
4332 }
4333 } ConvertDiagnoser;
4334 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4335}
4336
4337OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4338 SourceLocation StartLoc,
4339 SourceLocation LParenLoc,
4340 SourceLocation EndLoc) {
4341 Expr *ValExpr = NumThreads;
4342 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004343 !NumThreads->containsUnexpandedParameterPack()) {
4344 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4345 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004346 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004347 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004348 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004349
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004350 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004351
4352 // OpenMP [2.5, Restrictions]
4353 // The num_threads expression must evaluate to a positive integer value.
4354 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004355 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4356 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004357 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4358 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004359 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004360 }
4361 }
4362
Alexey Bataeved09d242014-05-28 05:53:51 +00004363 return new (Context)
4364 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004365}
4366
Alexey Bataev62c87d22014-03-21 04:51:18 +00004367ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4368 OpenMPClauseKind CKind) {
4369 if (!E)
4370 return ExprError();
4371 if (E->isValueDependent() || E->isTypeDependent() ||
4372 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004373 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004374 llvm::APSInt Result;
4375 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4376 if (ICE.isInvalid())
4377 return ExprError();
4378 if (!Result.isStrictlyPositive()) {
4379 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4380 << getOpenMPClauseName(CKind) << E->getSourceRange();
4381 return ExprError();
4382 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004383 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4384 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4385 << E->getSourceRange();
4386 return ExprError();
4387 }
Alexey Bataev9c821032015-04-30 04:23:23 +00004388 if (CKind == OMPC_collapse) {
4389 DSAStack->setCollapseNumber(Result.getExtValue());
4390 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004391 return ICE;
4392}
4393
4394OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4395 SourceLocation LParenLoc,
4396 SourceLocation EndLoc) {
4397 // OpenMP [2.8.1, simd construct, Description]
4398 // The parameter of the safelen clause must be a constant
4399 // positive integer expression.
4400 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4401 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004402 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004403 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004404 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004405}
4406
Alexander Musman64d33f12014-06-04 07:53:32 +00004407OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4408 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004409 SourceLocation LParenLoc,
4410 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004411 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004412 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004413 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004414 // The parameter of the collapse clause must be a constant
4415 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004416 ExprResult NumForLoopsResult =
4417 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4418 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004419 return nullptr;
4420 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004421 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004422}
4423
Alexey Bataeved09d242014-05-28 05:53:51 +00004424OMPClause *Sema::ActOnOpenMPSimpleClause(
4425 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4426 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004427 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004428 switch (Kind) {
4429 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004430 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004431 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4432 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004433 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004434 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004435 Res = ActOnOpenMPProcBindClause(
4436 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4437 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004438 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004439 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004440 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004441 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004442 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004443 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004444 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004445 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004446 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004447 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004448 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004449 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004450 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004451 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004452 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004453 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004454 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004455 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004456 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004457 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004458 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004459 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004460 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004461 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004462 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004463 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004464 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004465 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004466 llvm_unreachable("Clause is not allowed.");
4467 }
4468 return Res;
4469}
4470
4471OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4472 SourceLocation KindKwLoc,
4473 SourceLocation StartLoc,
4474 SourceLocation LParenLoc,
4475 SourceLocation EndLoc) {
4476 if (Kind == OMPC_DEFAULT_unknown) {
4477 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004478 static_assert(OMPC_DEFAULT_unknown > 0,
4479 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004480 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004481 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004482 Values += "'";
4483 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4484 Values += "'";
4485 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004486 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004487 Values += " or ";
4488 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004489 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004490 break;
4491 default:
4492 Values += Sep;
4493 break;
4494 }
4495 }
4496 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004497 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004498 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004499 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004500 switch (Kind) {
4501 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004502 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004503 break;
4504 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004505 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004506 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004507 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004508 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004509 break;
4510 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004511 return new (Context)
4512 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004513}
4514
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004515OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4516 SourceLocation KindKwLoc,
4517 SourceLocation StartLoc,
4518 SourceLocation LParenLoc,
4519 SourceLocation EndLoc) {
4520 if (Kind == OMPC_PROC_BIND_unknown) {
4521 std::string Values;
4522 std::string Sep(", ");
4523 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4524 Values += "'";
4525 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4526 Values += "'";
4527 switch (i) {
4528 case OMPC_PROC_BIND_unknown - 2:
4529 Values += " or ";
4530 break;
4531 case OMPC_PROC_BIND_unknown - 1:
4532 break;
4533 default:
4534 Values += Sep;
4535 break;
4536 }
4537 }
4538 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004539 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004540 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004541 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004542 return new (Context)
4543 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004544}
4545
Alexey Bataev56dafe82014-06-20 07:16:17 +00004546OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4547 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4548 SourceLocation StartLoc, SourceLocation LParenLoc,
4549 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4550 SourceLocation EndLoc) {
4551 OMPClause *Res = nullptr;
4552 switch (Kind) {
4553 case OMPC_schedule:
4554 Res = ActOnOpenMPScheduleClause(
4555 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4556 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4557 break;
4558 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004559 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004560 case OMPC_num_threads:
4561 case OMPC_safelen:
4562 case OMPC_collapse:
4563 case OMPC_default:
4564 case OMPC_proc_bind:
4565 case OMPC_private:
4566 case OMPC_firstprivate:
4567 case OMPC_lastprivate:
4568 case OMPC_shared:
4569 case OMPC_reduction:
4570 case OMPC_linear:
4571 case OMPC_aligned:
4572 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004573 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004574 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004575 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004576 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004577 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004578 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004579 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004580 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004581 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004582 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004583 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004584 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004585 case OMPC_unknown:
4586 llvm_unreachable("Clause is not allowed.");
4587 }
4588 return Res;
4589}
4590
4591OMPClause *Sema::ActOnOpenMPScheduleClause(
4592 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4593 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4594 SourceLocation EndLoc) {
4595 if (Kind == OMPC_SCHEDULE_unknown) {
4596 std::string Values;
4597 std::string Sep(", ");
4598 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4599 Values += "'";
4600 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4601 Values += "'";
4602 switch (i) {
4603 case OMPC_SCHEDULE_unknown - 2:
4604 Values += " or ";
4605 break;
4606 case OMPC_SCHEDULE_unknown - 1:
4607 break;
4608 default:
4609 Values += Sep;
4610 break;
4611 }
4612 }
4613 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4614 << Values << getOpenMPClauseName(OMPC_schedule);
4615 return nullptr;
4616 }
4617 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00004618 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004619 if (ChunkSize) {
4620 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4621 !ChunkSize->isInstantiationDependent() &&
4622 !ChunkSize->containsUnexpandedParameterPack()) {
4623 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4624 ExprResult Val =
4625 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4626 if (Val.isInvalid())
4627 return nullptr;
4628
4629 ValExpr = Val.get();
4630
4631 // OpenMP [2.7.1, Restrictions]
4632 // chunk_size must be a loop invariant integer expression with a positive
4633 // value.
4634 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00004635 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4636 if (Result.isSigned() && !Result.isStrictlyPositive()) {
4637 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4638 << "schedule" << ChunkSize->getSourceRange();
4639 return nullptr;
4640 }
4641 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4642 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4643 ChunkSize->getType(), ".chunk.");
4644 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4645 ChunkSize->getExprLoc(),
4646 /*RefersToCapture=*/true);
4647 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004648 }
4649 }
4650 }
4651
4652 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00004653 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00004654}
4655
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004656OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4657 SourceLocation StartLoc,
4658 SourceLocation EndLoc) {
4659 OMPClause *Res = nullptr;
4660 switch (Kind) {
4661 case OMPC_ordered:
4662 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4663 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004664 case OMPC_nowait:
4665 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4666 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004667 case OMPC_untied:
4668 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4669 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004670 case OMPC_mergeable:
4671 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4672 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004673 case OMPC_read:
4674 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4675 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004676 case OMPC_write:
4677 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4678 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004679 case OMPC_update:
4680 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4681 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004682 case OMPC_capture:
4683 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4684 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004685 case OMPC_seq_cst:
4686 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4687 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004688 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004689 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004690 case OMPC_num_threads:
4691 case OMPC_safelen:
4692 case OMPC_collapse:
4693 case OMPC_schedule:
4694 case OMPC_private:
4695 case OMPC_firstprivate:
4696 case OMPC_lastprivate:
4697 case OMPC_shared:
4698 case OMPC_reduction:
4699 case OMPC_linear:
4700 case OMPC_aligned:
4701 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004702 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004703 case OMPC_default:
4704 case OMPC_proc_bind:
4705 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004706 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004707 case OMPC_unknown:
4708 llvm_unreachable("Clause is not allowed.");
4709 }
4710 return Res;
4711}
4712
4713OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4714 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004715 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004716 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4717}
4718
Alexey Bataev236070f2014-06-20 11:19:47 +00004719OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4720 SourceLocation EndLoc) {
4721 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4722}
4723
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004724OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4725 SourceLocation EndLoc) {
4726 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4727}
4728
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004729OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4730 SourceLocation EndLoc) {
4731 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4732}
4733
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004734OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4735 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004736 return new (Context) OMPReadClause(StartLoc, EndLoc);
4737}
4738
Alexey Bataevdea47612014-07-23 07:46:59 +00004739OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4740 SourceLocation EndLoc) {
4741 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4742}
4743
Alexey Bataev67a4f222014-07-23 10:25:33 +00004744OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4745 SourceLocation EndLoc) {
4746 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4747}
4748
Alexey Bataev459dec02014-07-24 06:46:57 +00004749OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4750 SourceLocation EndLoc) {
4751 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4752}
4753
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004754OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4755 SourceLocation EndLoc) {
4756 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4757}
4758
Alexey Bataevc5e02582014-06-16 07:08:35 +00004759OMPClause *Sema::ActOnOpenMPVarListClause(
4760 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4761 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4762 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4763 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004764 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004765 switch (Kind) {
4766 case OMPC_private:
4767 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4768 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004769 case OMPC_firstprivate:
4770 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4771 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004772 case OMPC_lastprivate:
4773 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4774 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004775 case OMPC_shared:
4776 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4777 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004778 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004779 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4780 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004781 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004782 case OMPC_linear:
4783 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4784 ColonLoc, EndLoc);
4785 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004786 case OMPC_aligned:
4787 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4788 ColonLoc, EndLoc);
4789 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004790 case OMPC_copyin:
4791 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4792 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004793 case OMPC_copyprivate:
4794 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4795 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004796 case OMPC_flush:
4797 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4798 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004799 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004800 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004801 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004802 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004803 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004804 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004805 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004806 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004807 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004808 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004809 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004810 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004811 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004812 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004813 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004814 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004815 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004816 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004817 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004818 llvm_unreachable("Clause is not allowed.");
4819 }
4820 return Res;
4821}
4822
4823OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4824 SourceLocation StartLoc,
4825 SourceLocation LParenLoc,
4826 SourceLocation EndLoc) {
4827 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004828 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004829 for (auto &RefExpr : VarList) {
4830 assert(RefExpr && "NULL expr in OpenMP private clause.");
4831 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004832 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004833 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004834 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004835 continue;
4836 }
4837
Alexey Bataeved09d242014-05-28 05:53:51 +00004838 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004839 // OpenMP [2.1, C/C++]
4840 // A list item is a variable name.
4841 // OpenMP [2.9.3.3, Restrictions, p.1]
4842 // A variable that is part of another variable (as an array or
4843 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004844 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004845 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004846 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004847 continue;
4848 }
4849 Decl *D = DE->getDecl();
4850 VarDecl *VD = cast<VarDecl>(D);
4851
4852 QualType Type = VD->getType();
4853 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4854 // It will be analyzed later.
4855 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004856 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004857 continue;
4858 }
4859
4860 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4861 // A variable that appears in a private clause must not have an incomplete
4862 // type or a reference type.
4863 if (RequireCompleteType(ELoc, Type,
4864 diag::err_omp_private_incomplete_type)) {
4865 continue;
4866 }
4867 if (Type->isReferenceType()) {
4868 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004869 << getOpenMPClauseName(OMPC_private) << Type;
4870 bool IsDecl =
4871 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4872 Diag(VD->getLocation(),
4873 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4874 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004875 continue;
4876 }
4877
Alexey Bataev758e55e2013-09-06 18:03:48 +00004878 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4879 // in a Construct]
4880 // Variables with the predetermined data-sharing attributes may not be
4881 // listed in data-sharing attributes clauses, except for the cases
4882 // listed below. For these exceptions only, listing a predetermined
4883 // variable in a data-sharing attribute clause is allowed and overrides
4884 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004885 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004886 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004887 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4888 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004889 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004890 continue;
4891 }
4892
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004893 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00004894 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004895 DSAStack->getCurrentDirective() == OMPD_task) {
4896 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
4897 << getOpenMPClauseName(OMPC_private) << Type
4898 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4899 bool IsDecl =
4900 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4901 Diag(VD->getLocation(),
4902 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4903 << VD;
4904 continue;
4905 }
4906
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004907 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4908 // A variable of class type (or array thereof) that appears in a private
4909 // clause requires an accessible, unambiguous default constructor for the
4910 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004911 // Generate helper private variable and initialize it with the default
4912 // value. The address of the original variable is replaced by the address of
4913 // the new private variable in CodeGen. This new variable is not added to
4914 // IdResolver, so the code in the OpenMP region uses original variable for
4915 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004916 Type = Type.getUnqualifiedType();
4917 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
Alexey Bataev39f915b82015-05-08 10:41:21 +00004918 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004919 if (VDPrivate->isInvalidDecl())
4920 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004921 auto VDPrivateRefExpr = buildDeclRefExpr(
4922 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00004923
Alexey Bataev758e55e2013-09-06 18:03:48 +00004924 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004925 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004926 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004927 }
4928
Alexey Bataeved09d242014-05-28 05:53:51 +00004929 if (Vars.empty())
4930 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004931
Alexey Bataev03b340a2014-10-21 03:16:40 +00004932 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4933 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004934}
4935
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004936namespace {
4937class DiagsUninitializedSeveretyRAII {
4938private:
4939 DiagnosticsEngine &Diags;
4940 SourceLocation SavedLoc;
4941 bool IsIgnored;
4942
4943public:
4944 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4945 bool IsIgnored)
4946 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4947 if (!IsIgnored) {
4948 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4949 /*Map*/ diag::Severity::Ignored, Loc);
4950 }
4951 }
4952 ~DiagsUninitializedSeveretyRAII() {
4953 if (!IsIgnored)
4954 Diags.popMappings(SavedLoc);
4955 }
4956};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004957}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004958
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004959OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4960 SourceLocation StartLoc,
4961 SourceLocation LParenLoc,
4962 SourceLocation EndLoc) {
4963 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004964 SmallVector<Expr *, 8> PrivateCopies;
4965 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004966 bool IsImplicitClause =
4967 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4968 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4969
Alexey Bataeved09d242014-05-28 05:53:51 +00004970 for (auto &RefExpr : VarList) {
4971 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4972 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004973 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004974 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004975 PrivateCopies.push_back(nullptr);
4976 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004977 continue;
4978 }
4979
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004980 SourceLocation ELoc =
4981 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004982 // OpenMP [2.1, C/C++]
4983 // A list item is a variable name.
4984 // OpenMP [2.9.3.3, Restrictions, p.1]
4985 // A variable that is part of another variable (as an array or
4986 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004987 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004988 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004989 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004990 continue;
4991 }
4992 Decl *D = DE->getDecl();
4993 VarDecl *VD = cast<VarDecl>(D);
4994
4995 QualType Type = VD->getType();
4996 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4997 // It will be analyzed later.
4998 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004999 PrivateCopies.push_back(nullptr);
5000 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005001 continue;
5002 }
5003
5004 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5005 // A variable that appears in a private clause must not have an incomplete
5006 // type or a reference type.
5007 if (RequireCompleteType(ELoc, Type,
5008 diag::err_omp_firstprivate_incomplete_type)) {
5009 continue;
5010 }
5011 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005012 if (IsImplicitClause) {
5013 Diag(ImplicitClauseLoc,
5014 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
5015 << Type;
5016 Diag(RefExpr->getExprLoc(), diag::note_used_here);
5017 } else {
5018 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5019 << getOpenMPClauseName(OMPC_firstprivate) << Type;
5020 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005021 bool IsDecl =
5022 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5023 Diag(VD->getLocation(),
5024 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5025 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005026 continue;
5027 }
5028
5029 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5030 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00005031 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005032 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005033 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005034
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005035 // If an implicit firstprivate variable found it was checked already.
5036 if (!IsImplicitClause) {
5037 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005038 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005039 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5040 // A list item that specifies a given variable may not appear in more
5041 // than one clause on the same directive, except that a variable may be
5042 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005043 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00005044 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005045 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005046 << getOpenMPClauseName(DVar.CKind)
5047 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005048 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005049 continue;
5050 }
5051
5052 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5053 // in a Construct]
5054 // Variables with the predetermined data-sharing attributes may not be
5055 // listed in data-sharing attributes clauses, except for the cases
5056 // listed below. For these exceptions only, listing a predetermined
5057 // variable in a data-sharing attribute clause is allowed and overrides
5058 // the variable's predetermined data-sharing attributes.
5059 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5060 // in a Construct, C/C++, p.2]
5061 // Variables with const-qualified type having no mutable member may be
5062 // listed in a firstprivate clause, even if they are static data members.
5063 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5064 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
5065 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005066 << getOpenMPClauseName(DVar.CKind)
5067 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005068 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005069 continue;
5070 }
5071
Alexey Bataevf29276e2014-06-18 04:14:57 +00005072 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005073 // OpenMP [2.9.3.4, Restrictions, p.2]
5074 // A list item that is private within a parallel region must not appear
5075 // in a firstprivate clause on a worksharing construct if any of the
5076 // worksharing regions arising from the worksharing construct ever bind
5077 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00005078 if (isOpenMPWorksharingDirective(CurrDir) &&
5079 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005080 DVar = DSAStack->getImplicitDSA(VD, true);
5081 if (DVar.CKind != OMPC_shared &&
5082 (isOpenMPParallelDirective(DVar.DKind) ||
5083 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005084 Diag(ELoc, diag::err_omp_required_access)
5085 << getOpenMPClauseName(OMPC_firstprivate)
5086 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005087 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005088 continue;
5089 }
5090 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005091 // OpenMP [2.9.3.4, Restrictions, p.3]
5092 // A list item that appears in a reduction clause of a parallel construct
5093 // must not appear in a firstprivate clause on a worksharing or task
5094 // construct if any of the worksharing or task regions arising from the
5095 // worksharing or task construct ever bind to any of the parallel regions
5096 // arising from the parallel construct.
5097 // OpenMP [2.9.3.4, Restrictions, p.4]
5098 // A list item that appears in a reduction clause in worksharing
5099 // construct must not appear in a firstprivate clause in a task construct
5100 // encountered during execution of any of the worksharing regions arising
5101 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005102 if (CurrDir == OMPD_task) {
5103 DVar =
5104 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5105 [](OpenMPDirectiveKind K) -> bool {
5106 return isOpenMPParallelDirective(K) ||
5107 isOpenMPWorksharingDirective(K);
5108 },
5109 false);
5110 if (DVar.CKind == OMPC_reduction &&
5111 (isOpenMPParallelDirective(DVar.DKind) ||
5112 isOpenMPWorksharingDirective(DVar.DKind))) {
5113 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5114 << getOpenMPDirectiveName(DVar.DKind);
5115 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5116 continue;
5117 }
5118 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005119 }
5120
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005121 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005122 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005123 DSAStack->getCurrentDirective() == OMPD_task) {
5124 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5125 << getOpenMPClauseName(OMPC_firstprivate) << Type
5126 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5127 bool IsDecl =
5128 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5129 Diag(VD->getLocation(),
5130 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5131 << VD;
5132 continue;
5133 }
5134
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005135 Type = Type.getUnqualifiedType();
5136 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005137 // Generate helper private variable and initialize it with the value of the
5138 // original variable. The address of the original variable is replaced by
5139 // the address of the new private variable in the CodeGen. This new variable
5140 // is not added to IdResolver, so the code in the OpenMP region uses
5141 // original variable for proper diagnostics and variable capturing.
5142 Expr *VDInitRefExpr = nullptr;
5143 // For arrays generate initializer for single element and replace it by the
5144 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005145 if (Type->isArrayType()) {
5146 auto VDInit =
5147 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5148 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005149 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005150 ElemType = ElemType.getUnqualifiedType();
5151 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5152 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00005153 InitializedEntity Entity =
5154 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005155 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5156
5157 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5158 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5159 if (Result.isInvalid())
5160 VDPrivate->setInvalidDecl();
5161 else
5162 VDPrivate->setInit(Result.getAs<Expr>());
5163 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00005164 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005165 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005166 VDInitRefExpr =
5167 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00005168 AddInitializerToDecl(VDPrivate,
5169 DefaultLvalueConversion(VDInitRefExpr).get(),
5170 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005171 }
5172 if (VDPrivate->isInvalidDecl()) {
5173 if (IsImplicitClause) {
5174 Diag(DE->getExprLoc(),
5175 diag::note_omp_task_predetermined_firstprivate_here);
5176 }
5177 continue;
5178 }
5179 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005180 auto VDPrivateRefExpr = buildDeclRefExpr(
5181 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005182 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5183 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005184 PrivateCopies.push_back(VDPrivateRefExpr);
5185 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005186 }
5187
Alexey Bataeved09d242014-05-28 05:53:51 +00005188 if (Vars.empty())
5189 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005190
5191 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005192 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005193}
5194
Alexander Musman1bb328c2014-06-04 13:06:39 +00005195OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5196 SourceLocation StartLoc,
5197 SourceLocation LParenLoc,
5198 SourceLocation EndLoc) {
5199 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00005200 SmallVector<Expr *, 8> SrcExprs;
5201 SmallVector<Expr *, 8> DstExprs;
5202 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005203 for (auto &RefExpr : VarList) {
5204 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5205 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5206 // It will be analyzed later.
5207 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00005208 SrcExprs.push_back(nullptr);
5209 DstExprs.push_back(nullptr);
5210 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005211 continue;
5212 }
5213
5214 SourceLocation ELoc = RefExpr->getExprLoc();
5215 // OpenMP [2.1, C/C++]
5216 // A list item is a variable name.
5217 // OpenMP [2.14.3.5, Restrictions, p.1]
5218 // A variable that is part of another variable (as an array or structure
5219 // element) cannot appear in a lastprivate clause.
5220 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5221 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5222 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5223 continue;
5224 }
5225 Decl *D = DE->getDecl();
5226 VarDecl *VD = cast<VarDecl>(D);
5227
5228 QualType Type = VD->getType();
5229 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5230 // It will be analyzed later.
5231 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005232 SrcExprs.push_back(nullptr);
5233 DstExprs.push_back(nullptr);
5234 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005235 continue;
5236 }
5237
5238 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5239 // A variable that appears in a lastprivate clause must not have an
5240 // incomplete type or a reference type.
5241 if (RequireCompleteType(ELoc, Type,
5242 diag::err_omp_lastprivate_incomplete_type)) {
5243 continue;
5244 }
5245 if (Type->isReferenceType()) {
5246 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5247 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5248 bool IsDecl =
5249 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5250 Diag(VD->getLocation(),
5251 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5252 << VD;
5253 continue;
5254 }
5255
5256 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5257 // in a Construct]
5258 // Variables with the predetermined data-sharing attributes may not be
5259 // listed in data-sharing attributes clauses, except for the cases
5260 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005261 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005262 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5263 DVar.CKind != OMPC_firstprivate &&
5264 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5265 Diag(ELoc, diag::err_omp_wrong_dsa)
5266 << getOpenMPClauseName(DVar.CKind)
5267 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005268 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005269 continue;
5270 }
5271
Alexey Bataevf29276e2014-06-18 04:14:57 +00005272 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5273 // OpenMP [2.14.3.5, Restrictions, p.2]
5274 // A list item that is private within a parallel region, or that appears in
5275 // the reduction clause of a parallel construct, must not appear in a
5276 // lastprivate clause on a worksharing construct if any of the corresponding
5277 // worksharing regions ever binds to any of the corresponding parallel
5278 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005279 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00005280 if (isOpenMPWorksharingDirective(CurrDir) &&
5281 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005282 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005283 if (DVar.CKind != OMPC_shared) {
5284 Diag(ELoc, diag::err_omp_required_access)
5285 << getOpenMPClauseName(OMPC_lastprivate)
5286 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005287 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005288 continue;
5289 }
5290 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005291 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005292 // A variable of class type (or array thereof) that appears in a
5293 // lastprivate clause requires an accessible, unambiguous default
5294 // constructor for the class type, unless the list item is also specified
5295 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005296 // A variable of class type (or array thereof) that appears in a
5297 // lastprivate clause requires an accessible, unambiguous copy assignment
5298 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005299 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005300 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev38e89532015-04-16 04:54:05 +00005301 Type.getUnqualifiedType(), ".lastprivate.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00005302 auto *PseudoSrcExpr = buildDeclRefExpr(
5303 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005304 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005305 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
Alexey Bataev38e89532015-04-16 04:54:05 +00005306 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005307 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005308 // For arrays generate assignment operation for single element and replace
5309 // it by the original array element in CodeGen.
5310 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5311 PseudoDstExpr, PseudoSrcExpr);
5312 if (AssignmentOp.isInvalid())
5313 continue;
5314 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5315 /*DiscardedValue=*/true);
5316 if (AssignmentOp.isInvalid())
5317 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005318
Alexey Bataev39f915b82015-05-08 10:41:21 +00005319 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005320 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005321 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005322 SrcExprs.push_back(PseudoSrcExpr);
5323 DstExprs.push_back(PseudoDstExpr);
5324 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005325 }
5326
5327 if (Vars.empty())
5328 return nullptr;
5329
5330 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005331 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005332}
5333
Alexey Bataev758e55e2013-09-06 18:03:48 +00005334OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5335 SourceLocation StartLoc,
5336 SourceLocation LParenLoc,
5337 SourceLocation EndLoc) {
5338 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005339 for (auto &RefExpr : VarList) {
5340 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5341 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005342 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005343 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005344 continue;
5345 }
5346
Alexey Bataeved09d242014-05-28 05:53:51 +00005347 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005348 // OpenMP [2.1, C/C++]
5349 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005350 // OpenMP [2.14.3.2, Restrictions, p.1]
5351 // A variable that is part of another variable (as an array or structure
5352 // element) cannot appear in a shared unless it is a static data member
5353 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005354 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005355 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005356 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005357 continue;
5358 }
5359 Decl *D = DE->getDecl();
5360 VarDecl *VD = cast<VarDecl>(D);
5361
5362 QualType Type = VD->getType();
5363 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5364 // It will be analyzed later.
5365 Vars.push_back(DE);
5366 continue;
5367 }
5368
5369 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5370 // in a Construct]
5371 // Variables with the predetermined data-sharing attributes may not be
5372 // listed in data-sharing attributes clauses, except for the cases
5373 // listed below. For these exceptions only, listing a predetermined
5374 // variable in a data-sharing attribute clause is allowed and overrides
5375 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005376 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005377 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5378 DVar.RefExpr) {
5379 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5380 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005381 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005382 continue;
5383 }
5384
5385 DSAStack->addDSA(VD, DE, OMPC_shared);
5386 Vars.push_back(DE);
5387 }
5388
Alexey Bataeved09d242014-05-28 05:53:51 +00005389 if (Vars.empty())
5390 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005391
5392 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5393}
5394
Alexey Bataevc5e02582014-06-16 07:08:35 +00005395namespace {
5396class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5397 DSAStackTy *Stack;
5398
5399public:
5400 bool VisitDeclRefExpr(DeclRefExpr *E) {
5401 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005402 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005403 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5404 return false;
5405 if (DVar.CKind != OMPC_unknown)
5406 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005407 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005408 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005409 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005410 return true;
5411 return false;
5412 }
5413 return false;
5414 }
5415 bool VisitStmt(Stmt *S) {
5416 for (auto Child : S->children()) {
5417 if (Child && Visit(Child))
5418 return true;
5419 }
5420 return false;
5421 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005422 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005423};
Alexey Bataev23b69422014-06-18 07:08:49 +00005424} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005425
5426OMPClause *Sema::ActOnOpenMPReductionClause(
5427 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5428 SourceLocation ColonLoc, SourceLocation EndLoc,
5429 CXXScopeSpec &ReductionIdScopeSpec,
5430 const DeclarationNameInfo &ReductionId) {
5431 // TODO: Allow scope specification search when 'declare reduction' is
5432 // supported.
5433 assert(ReductionIdScopeSpec.isEmpty() &&
5434 "No support for scoped reduction identifiers yet.");
5435
5436 auto DN = ReductionId.getName();
5437 auto OOK = DN.getCXXOverloadedOperator();
5438 BinaryOperatorKind BOK = BO_Comma;
5439
5440 // OpenMP [2.14.3.6, reduction clause]
5441 // C
5442 // reduction-identifier is either an identifier or one of the following
5443 // operators: +, -, *, &, |, ^, && and ||
5444 // C++
5445 // reduction-identifier is either an id-expression or one of the following
5446 // operators: +, -, *, &, |, ^, && and ||
5447 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5448 switch (OOK) {
5449 case OO_Plus:
5450 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005451 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005452 break;
5453 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005454 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005455 break;
5456 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005457 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005458 break;
5459 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005460 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005461 break;
5462 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005463 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005464 break;
5465 case OO_AmpAmp:
5466 BOK = BO_LAnd;
5467 break;
5468 case OO_PipePipe:
5469 BOK = BO_LOr;
5470 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005471 case OO_New:
5472 case OO_Delete:
5473 case OO_Array_New:
5474 case OO_Array_Delete:
5475 case OO_Slash:
5476 case OO_Percent:
5477 case OO_Tilde:
5478 case OO_Exclaim:
5479 case OO_Equal:
5480 case OO_Less:
5481 case OO_Greater:
5482 case OO_LessEqual:
5483 case OO_GreaterEqual:
5484 case OO_PlusEqual:
5485 case OO_MinusEqual:
5486 case OO_StarEqual:
5487 case OO_SlashEqual:
5488 case OO_PercentEqual:
5489 case OO_CaretEqual:
5490 case OO_AmpEqual:
5491 case OO_PipeEqual:
5492 case OO_LessLess:
5493 case OO_GreaterGreater:
5494 case OO_LessLessEqual:
5495 case OO_GreaterGreaterEqual:
5496 case OO_EqualEqual:
5497 case OO_ExclaimEqual:
5498 case OO_PlusPlus:
5499 case OO_MinusMinus:
5500 case OO_Comma:
5501 case OO_ArrowStar:
5502 case OO_Arrow:
5503 case OO_Call:
5504 case OO_Subscript:
5505 case OO_Conditional:
5506 case NUM_OVERLOADED_OPERATORS:
5507 llvm_unreachable("Unexpected reduction identifier");
5508 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005509 if (auto II = DN.getAsIdentifierInfo()) {
5510 if (II->isStr("max"))
5511 BOK = BO_GT;
5512 else if (II->isStr("min"))
5513 BOK = BO_LT;
5514 }
5515 break;
5516 }
5517 SourceRange ReductionIdRange;
5518 if (ReductionIdScopeSpec.isValid()) {
5519 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5520 }
5521 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5522 if (BOK == BO_Comma) {
5523 // Not allowed reduction identifier is found.
5524 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5525 << ReductionIdRange;
5526 return nullptr;
5527 }
5528
5529 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005530 SmallVector<Expr *, 8> LHSs;
5531 SmallVector<Expr *, 8> RHSs;
5532 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005533 for (auto RefExpr : VarList) {
5534 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5535 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5536 // It will be analyzed later.
5537 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005538 LHSs.push_back(nullptr);
5539 RHSs.push_back(nullptr);
5540 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005541 continue;
5542 }
5543
5544 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5545 RefExpr->isInstantiationDependent() ||
5546 RefExpr->containsUnexpandedParameterPack()) {
5547 // It will be analyzed later.
5548 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005549 LHSs.push_back(nullptr);
5550 RHSs.push_back(nullptr);
5551 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005552 continue;
5553 }
5554
5555 auto ELoc = RefExpr->getExprLoc();
5556 auto ERange = RefExpr->getSourceRange();
5557 // OpenMP [2.1, C/C++]
5558 // A list item is a variable or array section, subject to the restrictions
5559 // specified in Section 2.4 on page 42 and in each of the sections
5560 // describing clauses and directives for which a list appears.
5561 // OpenMP [2.14.3.3, Restrictions, p.1]
5562 // A variable that is part of another variable (as an array or
5563 // structure element) cannot appear in a private clause.
5564 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5565 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5566 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5567 continue;
5568 }
5569 auto D = DE->getDecl();
5570 auto VD = cast<VarDecl>(D);
5571 auto Type = VD->getType();
5572 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5573 // A variable that appears in a private clause must not have an incomplete
5574 // type or a reference type.
5575 if (RequireCompleteType(ELoc, Type,
5576 diag::err_omp_reduction_incomplete_type))
5577 continue;
5578 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5579 // Arrays may not appear in a reduction clause.
5580 if (Type.getNonReferenceType()->isArrayType()) {
5581 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5582 bool IsDecl =
5583 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5584 Diag(VD->getLocation(),
5585 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5586 << VD;
5587 continue;
5588 }
5589 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5590 // A list item that appears in a reduction clause must not be
5591 // const-qualified.
5592 if (Type.getNonReferenceType().isConstant(Context)) {
5593 Diag(ELoc, diag::err_omp_const_variable)
5594 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5595 bool IsDecl =
5596 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5597 Diag(VD->getLocation(),
5598 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5599 << VD;
5600 continue;
5601 }
5602 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5603 // If a list-item is a reference type then it must bind to the same object
5604 // for all threads of the team.
5605 VarDecl *VDDef = VD->getDefinition();
5606 if (Type->isReferenceType() && VDDef) {
5607 DSARefChecker Check(DSAStack);
5608 if (Check.Visit(VDDef->getInit())) {
5609 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5610 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5611 continue;
5612 }
5613 }
5614 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5615 // The type of a list item that appears in a reduction clause must be valid
5616 // for the reduction-identifier. For a max or min reduction in C, the type
5617 // of the list item must be an allowed arithmetic data type: char, int,
5618 // float, double, or _Bool, possibly modified with long, short, signed, or
5619 // unsigned. For a max or min reduction in C++, the type of the list item
5620 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5621 // double, or bool, possibly modified with long, short, signed, or unsigned.
5622 if ((BOK == BO_GT || BOK == BO_LT) &&
5623 !(Type->isScalarType() ||
5624 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5625 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5626 << getLangOpts().CPlusPlus;
5627 bool IsDecl =
5628 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5629 Diag(VD->getLocation(),
5630 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5631 << VD;
5632 continue;
5633 }
5634 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5635 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5636 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5637 bool IsDecl =
5638 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5639 Diag(VD->getLocation(),
5640 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5641 << VD;
5642 continue;
5643 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005644 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5645 // in a Construct]
5646 // Variables with the predetermined data-sharing attributes may not be
5647 // listed in data-sharing attributes clauses, except for the cases
5648 // listed below. For these exceptions only, listing a predetermined
5649 // variable in a data-sharing attribute clause is allowed and overrides
5650 // the variable's predetermined data-sharing attributes.
5651 // OpenMP [2.14.3.6, Restrictions, p.3]
5652 // Any number of reduction clauses can be specified on the directive,
5653 // but a list item can appear only once in the reduction clauses for that
5654 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005655 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005656 if (DVar.CKind == OMPC_reduction) {
5657 Diag(ELoc, diag::err_omp_once_referenced)
5658 << getOpenMPClauseName(OMPC_reduction);
5659 if (DVar.RefExpr) {
5660 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5661 }
5662 } else if (DVar.CKind != OMPC_unknown) {
5663 Diag(ELoc, diag::err_omp_wrong_dsa)
5664 << getOpenMPClauseName(DVar.CKind)
5665 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005666 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005667 continue;
5668 }
5669
5670 // OpenMP [2.14.3.6, Restrictions, p.1]
5671 // A list item that appears in a reduction clause of a worksharing
5672 // construct must be shared in the parallel regions to which any of the
5673 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005674 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005675 if (isOpenMPWorksharingDirective(CurrDir) &&
5676 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005677 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005678 if (DVar.CKind != OMPC_shared) {
5679 Diag(ELoc, diag::err_omp_required_access)
5680 << getOpenMPClauseName(OMPC_reduction)
5681 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005682 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005683 continue;
5684 }
5685 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005686 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005687 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5688 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005689 // Add initializer for private variable.
5690 Expr *Init = nullptr;
5691 switch (BOK) {
5692 case BO_Add:
5693 case BO_Xor:
5694 case BO_Or:
5695 case BO_LOr:
5696 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5697 if (Type->isScalarType() || Type->isAnyComplexType()) {
5698 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005699 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005700 break;
5701 case BO_Mul:
5702 case BO_LAnd:
5703 if (Type->isScalarType() || Type->isAnyComplexType()) {
5704 // '*' and '&&' reduction ops - initializer is '1'.
5705 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5706 }
5707 break;
5708 case BO_And: {
5709 // '&' reduction op - initializer is '~0'.
5710 QualType OrigType = Type;
5711 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5712 Type = ComplexTy->getElementType();
5713 }
5714 if (Type->isRealFloatingType()) {
5715 llvm::APFloat InitValue =
5716 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5717 /*isIEEE=*/true);
5718 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5719 Type, ELoc);
5720 } else if (Type->isScalarType()) {
5721 auto Size = Context.getTypeSize(Type);
5722 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5723 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5724 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5725 }
5726 if (Init && OrigType->isAnyComplexType()) {
5727 // Init = 0xFFFF + 0xFFFFi;
5728 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5729 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5730 }
5731 Type = OrigType;
5732 break;
5733 }
5734 case BO_LT:
5735 case BO_GT: {
5736 // 'min' reduction op - initializer is 'Largest representable number in
5737 // the reduction list item type'.
5738 // 'max' reduction op - initializer is 'Least representable number in
5739 // the reduction list item type'.
5740 if (Type->isIntegerType() || Type->isPointerType()) {
5741 bool IsSigned = Type->hasSignedIntegerRepresentation();
5742 auto Size = Context.getTypeSize(Type);
5743 QualType IntTy =
5744 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5745 llvm::APInt InitValue =
5746 (BOK != BO_LT)
5747 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5748 : llvm::APInt::getMinValue(Size)
5749 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5750 : llvm::APInt::getMaxValue(Size);
5751 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5752 if (Type->isPointerType()) {
5753 // Cast to pointer type.
5754 auto CastExpr = BuildCStyleCastExpr(
5755 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5756 SourceLocation(), Init);
5757 if (CastExpr.isInvalid())
5758 continue;
5759 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005760 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005761 } else if (Type->isRealFloatingType()) {
5762 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5763 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5764 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5765 Type, ELoc);
5766 }
5767 break;
5768 }
5769 case BO_PtrMemD:
5770 case BO_PtrMemI:
5771 case BO_MulAssign:
5772 case BO_Div:
5773 case BO_Rem:
5774 case BO_Sub:
5775 case BO_Shl:
5776 case BO_Shr:
5777 case BO_LE:
5778 case BO_GE:
5779 case BO_EQ:
5780 case BO_NE:
5781 case BO_AndAssign:
5782 case BO_XorAssign:
5783 case BO_OrAssign:
5784 case BO_Assign:
5785 case BO_AddAssign:
5786 case BO_SubAssign:
5787 case BO_DivAssign:
5788 case BO_RemAssign:
5789 case BO_ShlAssign:
5790 case BO_ShrAssign:
5791 case BO_Comma:
5792 llvm_unreachable("Unexpected reduction operation");
5793 }
5794 if (Init) {
5795 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5796 /*TypeMayContainAuto=*/false);
5797 } else {
5798 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5799 }
5800 if (!RHSVD->hasInit()) {
5801 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5802 << ReductionIdRange;
5803 bool IsDecl =
5804 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5805 Diag(VD->getLocation(),
5806 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5807 << VD;
5808 continue;
5809 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00005810 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5811 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005812 ExprResult ReductionOp =
5813 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5814 LHSDRE, RHSDRE);
5815 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00005816 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005817 ReductionOp =
5818 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5819 BO_Assign, LHSDRE, ReductionOp.get());
5820 } else {
5821 auto *ConditionalOp = new (Context) ConditionalOperator(
5822 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5823 RHSDRE, Type, VK_LValue, OK_Ordinary);
5824 ReductionOp =
5825 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5826 BO_Assign, LHSDRE, ConditionalOp);
5827 }
5828 if (ReductionOp.isUsable()) {
5829 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005830 }
5831 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005832 if (ReductionOp.isInvalid())
5833 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005834
5835 DSAStack->addDSA(VD, DE, OMPC_reduction);
5836 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005837 LHSs.push_back(LHSDRE);
5838 RHSs.push_back(RHSDRE);
5839 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005840 }
5841
5842 if (Vars.empty())
5843 return nullptr;
5844
5845 return OMPReductionClause::Create(
5846 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005847 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5848 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005849}
5850
Alexander Musman8dba6642014-04-22 13:09:42 +00005851OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5852 SourceLocation StartLoc,
5853 SourceLocation LParenLoc,
5854 SourceLocation ColonLoc,
5855 SourceLocation EndLoc) {
5856 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005857 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005858 for (auto &RefExpr : VarList) {
5859 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5860 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005861 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005862 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005863 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005864 continue;
5865 }
5866
5867 // OpenMP [2.14.3.7, linear clause]
5868 // A list item that appears in a linear clause is subject to the private
5869 // clause semantics described in Section 2.14.3.3 on page 159 except as
5870 // noted. In addition, the value of the new list item on each iteration
5871 // of the associated loop(s) corresponds to the value of the original
5872 // list item before entering the construct plus the logical number of
5873 // the iteration times linear-step.
5874
Alexey Bataeved09d242014-05-28 05:53:51 +00005875 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005876 // OpenMP [2.1, C/C++]
5877 // A list item is a variable name.
5878 // OpenMP [2.14.3.3, Restrictions, p.1]
5879 // A variable that is part of another variable (as an array or
5880 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005881 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005882 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005883 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005884 continue;
5885 }
5886
5887 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5888
5889 // OpenMP [2.14.3.7, linear clause]
5890 // A list-item cannot appear in more than one linear clause.
5891 // A list-item that appears in a linear clause cannot appear in any
5892 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005893 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005894 if (DVar.RefExpr) {
5895 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5896 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005897 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005898 continue;
5899 }
5900
5901 QualType QType = VD->getType();
5902 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5903 // It will be analyzed later.
5904 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005905 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005906 continue;
5907 }
5908
5909 // A variable must not have an incomplete type or a reference type.
5910 if (RequireCompleteType(ELoc, QType,
5911 diag::err_omp_linear_incomplete_type)) {
5912 continue;
5913 }
5914 if (QType->isReferenceType()) {
5915 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5916 << getOpenMPClauseName(OMPC_linear) << QType;
5917 bool IsDecl =
5918 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5919 Diag(VD->getLocation(),
5920 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5921 << VD;
5922 continue;
5923 }
5924
5925 // A list item must not be const-qualified.
5926 if (QType.isConstant(Context)) {
5927 Diag(ELoc, diag::err_omp_const_variable)
5928 << getOpenMPClauseName(OMPC_linear);
5929 bool IsDecl =
5930 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5931 Diag(VD->getLocation(),
5932 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5933 << VD;
5934 continue;
5935 }
5936
5937 // A list item must be of integral or pointer type.
5938 QType = QType.getUnqualifiedType().getCanonicalType();
5939 const Type *Ty = QType.getTypePtrOrNull();
5940 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5941 !Ty->isPointerType())) {
5942 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5943 bool IsDecl =
5944 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5945 Diag(VD->getLocation(),
5946 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5947 << VD;
5948 continue;
5949 }
5950
Alexander Musman3276a272015-03-21 10:12:56 +00005951 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005952 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexander Musman3276a272015-03-21 10:12:56 +00005953 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5954 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005955 auto InitRef = buildDeclRefExpr(
5956 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00005957 DSAStack->addDSA(VD, DE, OMPC_linear);
5958 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005959 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005960 }
5961
5962 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005963 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005964
5965 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005966 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005967 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5968 !Step->isInstantiationDependent() &&
5969 !Step->containsUnexpandedParameterPack()) {
5970 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005971 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005972 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005973 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005974 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005975
Alexander Musman3276a272015-03-21 10:12:56 +00005976 // Build var to save the step value.
5977 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005978 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00005979 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005980 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00005981 ExprResult CalcStep =
5982 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5983
Alexander Musman8dba6642014-04-22 13:09:42 +00005984 // Warn about zero linear step (it would be probably better specified as
5985 // making corresponding variables 'const').
5986 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005987 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5988 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005989 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5990 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005991 if (!IsConstant && CalcStep.isUsable()) {
5992 // Calculate the step beforehand instead of doing this on each iteration.
5993 // (This is not used if the number of iterations may be kfold-ed).
5994 CalcStepExpr = CalcStep.get();
5995 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005996 }
5997
5998 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005999 Vars, Inits, StepExpr, CalcStepExpr);
6000}
6001
6002static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
6003 Expr *NumIterations, Sema &SemaRef,
6004 Scope *S) {
6005 // Walk the vars and build update/final expressions for the CodeGen.
6006 SmallVector<Expr *, 8> Updates;
6007 SmallVector<Expr *, 8> Finals;
6008 Expr *Step = Clause.getStep();
6009 Expr *CalcStep = Clause.getCalcStep();
6010 // OpenMP [2.14.3.7, linear clause]
6011 // If linear-step is not specified it is assumed to be 1.
6012 if (Step == nullptr)
6013 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6014 else if (CalcStep)
6015 Step = cast<BinaryOperator>(CalcStep)->getLHS();
6016 bool HasErrors = false;
6017 auto CurInit = Clause.inits().begin();
6018 for (auto &RefExpr : Clause.varlists()) {
6019 Expr *InitExpr = *CurInit;
6020
6021 // Build privatized reference to the current linear var.
6022 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006023 auto PrivateRef =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006024 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
6025 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
6026 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00006027
6028 // Build update: Var = InitExpr + IV * Step
6029 ExprResult Update =
6030 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6031 InitExpr, IV, Step, /* Subtract */ false);
6032 Update = SemaRef.ActOnFinishFullExpr(Update.get());
6033
6034 // Build final: Var = InitExpr + NumIterations * Step
6035 ExprResult Final =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006036 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6037 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexander Musman3276a272015-03-21 10:12:56 +00006038 Final = SemaRef.ActOnFinishFullExpr(Final.get());
6039 if (!Update.isUsable() || !Final.isUsable()) {
6040 Updates.push_back(nullptr);
6041 Finals.push_back(nullptr);
6042 HasErrors = true;
6043 } else {
6044 Updates.push_back(Update.get());
6045 Finals.push_back(Final.get());
6046 }
6047 ++CurInit;
6048 }
6049 Clause.setUpdates(Updates);
6050 Clause.setFinals(Finals);
6051 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00006052}
6053
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006054OMPClause *Sema::ActOnOpenMPAlignedClause(
6055 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
6056 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
6057
6058 SmallVector<Expr *, 8> Vars;
6059 for (auto &RefExpr : VarList) {
6060 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
6061 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6062 // It will be analyzed later.
6063 Vars.push_back(RefExpr);
6064 continue;
6065 }
6066
6067 SourceLocation ELoc = RefExpr->getExprLoc();
6068 // OpenMP [2.1, C/C++]
6069 // A list item is a variable name.
6070 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6071 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6072 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6073 continue;
6074 }
6075
6076 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6077
6078 // OpenMP [2.8.1, simd construct, Restrictions]
6079 // The type of list items appearing in the aligned clause must be
6080 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006081 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006082 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006083 const Type *Ty = QType.getTypePtrOrNull();
6084 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6085 !Ty->isPointerType())) {
6086 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6087 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6088 bool IsDecl =
6089 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6090 Diag(VD->getLocation(),
6091 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6092 << VD;
6093 continue;
6094 }
6095
6096 // OpenMP [2.8.1, simd construct, Restrictions]
6097 // A list-item cannot appear in more than one aligned clause.
6098 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6099 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6100 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6101 << getOpenMPClauseName(OMPC_aligned);
6102 continue;
6103 }
6104
6105 Vars.push_back(DE);
6106 }
6107
6108 // OpenMP [2.8.1, simd construct, Description]
6109 // The parameter of the aligned clause, alignment, must be a constant
6110 // positive integer expression.
6111 // If no optional parameter is specified, implementation-defined default
6112 // alignments for SIMD instructions on the target platforms are assumed.
6113 if (Alignment != nullptr) {
6114 ExprResult AlignResult =
6115 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6116 if (AlignResult.isInvalid())
6117 return nullptr;
6118 Alignment = AlignResult.get();
6119 }
6120 if (Vars.empty())
6121 return nullptr;
6122
6123 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6124 EndLoc, Vars, Alignment);
6125}
6126
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006127OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6128 SourceLocation StartLoc,
6129 SourceLocation LParenLoc,
6130 SourceLocation EndLoc) {
6131 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006132 SmallVector<Expr *, 8> SrcExprs;
6133 SmallVector<Expr *, 8> DstExprs;
6134 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00006135 for (auto &RefExpr : VarList) {
6136 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6137 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006138 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006139 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006140 SrcExprs.push_back(nullptr);
6141 DstExprs.push_back(nullptr);
6142 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006143 continue;
6144 }
6145
Alexey Bataeved09d242014-05-28 05:53:51 +00006146 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006147 // OpenMP [2.1, C/C++]
6148 // A list item is a variable name.
6149 // OpenMP [2.14.4.1, Restrictions, p.1]
6150 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00006151 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006152 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006153 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006154 continue;
6155 }
6156
6157 Decl *D = DE->getDecl();
6158 VarDecl *VD = cast<VarDecl>(D);
6159
6160 QualType Type = VD->getType();
6161 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6162 // It will be analyzed later.
6163 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006164 SrcExprs.push_back(nullptr);
6165 DstExprs.push_back(nullptr);
6166 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006167 continue;
6168 }
6169
6170 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6171 // A list item that appears in a copyin clause must be threadprivate.
6172 if (!DSAStack->isThreadPrivate(VD)) {
6173 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00006174 << getOpenMPClauseName(OMPC_copyin)
6175 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006176 continue;
6177 }
6178
6179 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6180 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00006181 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006182 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006183 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006184 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006185 ElemType.getUnqualifiedType(), ".copyin.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00006186 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006187 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6188 auto *DstVD =
6189 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006190 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006191 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006192 // For arrays generate assignment operation for single element and replace
6193 // it by the original array element in CodeGen.
6194 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6195 PseudoDstExpr, PseudoSrcExpr);
6196 if (AssignmentOp.isInvalid())
6197 continue;
6198 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6199 /*DiscardedValue=*/true);
6200 if (AssignmentOp.isInvalid())
6201 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006202
6203 DSAStack->addDSA(VD, DE, OMPC_copyin);
6204 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006205 SrcExprs.push_back(PseudoSrcExpr);
6206 DstExprs.push_back(PseudoDstExpr);
6207 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006208 }
6209
Alexey Bataeved09d242014-05-28 05:53:51 +00006210 if (Vars.empty())
6211 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006212
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006213 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6214 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006215}
6216
Alexey Bataevbae9a792014-06-27 10:37:06 +00006217OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6218 SourceLocation StartLoc,
6219 SourceLocation LParenLoc,
6220 SourceLocation EndLoc) {
6221 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006222 SmallVector<Expr *, 8> SrcExprs;
6223 SmallVector<Expr *, 8> DstExprs;
6224 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006225 for (auto &RefExpr : VarList) {
6226 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6227 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6228 // It will be analyzed later.
6229 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006230 SrcExprs.push_back(nullptr);
6231 DstExprs.push_back(nullptr);
6232 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006233 continue;
6234 }
6235
6236 SourceLocation ELoc = RefExpr->getExprLoc();
6237 // OpenMP [2.1, C/C++]
6238 // A list item is a variable name.
6239 // OpenMP [2.14.4.1, Restrictions, p.1]
6240 // A list item that appears in a copyin clause must be threadprivate.
6241 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6242 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6243 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6244 continue;
6245 }
6246
6247 Decl *D = DE->getDecl();
6248 VarDecl *VD = cast<VarDecl>(D);
6249
6250 QualType Type = VD->getType();
6251 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6252 // It will be analyzed later.
6253 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006254 SrcExprs.push_back(nullptr);
6255 DstExprs.push_back(nullptr);
6256 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006257 continue;
6258 }
6259
6260 // OpenMP [2.14.4.2, Restrictions, p.2]
6261 // A list item that appears in a copyprivate clause may not appear in a
6262 // private or firstprivate clause on the single construct.
6263 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006264 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006265 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6266 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006267 Diag(ELoc, diag::err_omp_wrong_dsa)
6268 << getOpenMPClauseName(DVar.CKind)
6269 << getOpenMPClauseName(OMPC_copyprivate);
6270 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6271 continue;
6272 }
6273
6274 // OpenMP [2.11.4.2, Restrictions, p.1]
6275 // All list items that appear in a copyprivate clause must be either
6276 // threadprivate or private in the enclosing context.
6277 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006278 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006279 if (DVar.CKind == OMPC_shared) {
6280 Diag(ELoc, diag::err_omp_required_access)
6281 << getOpenMPClauseName(OMPC_copyprivate)
6282 << "threadprivate or private in the enclosing context";
6283 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6284 continue;
6285 }
6286 }
6287 }
6288
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006289 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00006290 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006291 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006292 << getOpenMPClauseName(OMPC_copyprivate) << Type
6293 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006294 bool IsDecl =
6295 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6296 Diag(VD->getLocation(),
6297 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6298 << VD;
6299 continue;
6300 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006301
Alexey Bataevbae9a792014-06-27 10:37:06 +00006302 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6303 // A variable of class type (or array thereof) that appears in a
6304 // copyin clause requires an accessible, unambiguous copy assignment
6305 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006306 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6307 auto *SrcVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006308 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006309 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006310 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00006311 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006312 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006313 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006314 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00006315 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6316 PseudoDstExpr, PseudoSrcExpr);
6317 if (AssignmentOp.isInvalid())
6318 continue;
6319 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6320 /*DiscardedValue=*/true);
6321 if (AssignmentOp.isInvalid())
6322 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006323
6324 // No need to mark vars as copyprivate, they are already threadprivate or
6325 // implicitly private.
6326 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006327 SrcExprs.push_back(PseudoSrcExpr);
6328 DstExprs.push_back(PseudoDstExpr);
6329 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006330 }
6331
6332 if (Vars.empty())
6333 return nullptr;
6334
Alexey Bataeva63048e2015-03-23 06:18:07 +00006335 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6336 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006337}
6338
Alexey Bataev6125da92014-07-21 11:26:11 +00006339OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6340 SourceLocation StartLoc,
6341 SourceLocation LParenLoc,
6342 SourceLocation EndLoc) {
6343 if (VarList.empty())
6344 return nullptr;
6345
6346 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6347}
Alexey Bataevdea47612014-07-23 07:46:59 +00006348