blob: ee6bdb21e55270cb0ce19a71f607dde7d3ef6426 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000017#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000018#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/StmtCXX.h"
21#include "clang/AST/StmtOpenMP.h"
22#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "clang/Basic/OpenMPKinds.h"
24#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000025#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000026#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000027#include "clang/Sema/Scope.h"
28#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000029#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030using namespace clang;
31
Alexey Bataev758e55e2013-09-06 18:03:48 +000032//===----------------------------------------------------------------------===//
33// Stack of data-sharing attributes for variables
34//===----------------------------------------------------------------------===//
35
36namespace {
37/// \brief Default data sharing attributes, which can be applied to directive.
38enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000039 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
40 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
41 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000042};
Alexey Bataev7ff55242014-06-19 09:13:45 +000043
Alexey Bataevf29276e2014-06-18 04:14:57 +000044template <class T> struct MatchesAny {
Alexey Bataev23b69422014-06-18 07:08:49 +000045 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
Alexey Bataevf29276e2014-06-18 04:14:57 +000046 bool operator()(T Kind) {
47 for (auto KindEl : Arr)
48 if (KindEl == Kind)
49 return true;
50 return false;
51 }
52
53private:
54 ArrayRef<T> Arr;
55};
Alexey Bataev23b69422014-06-18 07:08:49 +000056struct MatchesAlways {
Alexey Bataevf29276e2014-06-18 04:14:57 +000057 MatchesAlways() {}
Alexey Bataev7ff55242014-06-19 09:13:45 +000058 template <class T> bool operator()(T) { return true; }
Alexey Bataevf29276e2014-06-18 04:14:57 +000059};
60
61typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
62typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
Alexey Bataev758e55e2013-09-06 18:03:48 +000063
64/// \brief Stack for tracking declarations used in OpenMP directives and
65/// clauses and their data-sharing attributes.
66class DSAStackTy {
67public:
68 struct DSAVarData {
69 OpenMPDirectiveKind DKind;
70 OpenMPClauseKind CKind;
71 DeclRefExpr *RefExpr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000072 SourceLocation ImplicitDSALoc;
73 DSAVarData()
74 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
75 ImplicitDSALoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000076 };
Alexey Bataeved09d242014-05-28 05:53:51 +000077
Alexey Bataev758e55e2013-09-06 18:03:48 +000078private:
79 struct DSAInfo {
80 OpenMPClauseKind Attributes;
81 DeclRefExpr *RefExpr;
82 };
83 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000084 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
Alexey Bataev9c821032015-04-30 04:23:23 +000085 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086
87 struct SharingMapTy {
88 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000089 AlignedMapTy AlignedMap;
Alexey Bataev9c821032015-04-30 04:23:23 +000090 LoopControlVariablesSetTy LCVSet;
Alexey Bataev758e55e2013-09-06 18:03:48 +000091 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000092 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +000093 OpenMPDirectiveKind Directive;
94 DeclarationNameInfo DirectiveName;
95 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +000096 SourceLocation ConstructLoc;
Alexey Bataev9fb6e642014-07-22 06:45:04 +000097 bool OrderedRegion;
Alexey Bataev9c821032015-04-30 04:23:23 +000098 unsigned CollapseNumber;
Alexey Bataev13314bf2014-10-09 04:18:56 +000099 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000100 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000101 Scope *CurScope, SourceLocation Loc)
Alexey Bataev9c821032015-04-30 04:23:23 +0000102 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000103 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev9c821032015-04-30 04:23:23 +0000104 ConstructLoc(Loc), OrderedRegion(false), CollapseNumber(1),
105 InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000106 SharingMapTy()
Alexey Bataev9c821032015-04-30 04:23:23 +0000107 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000108 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev9c821032015-04-30 04:23:23 +0000109 ConstructLoc(), OrderedRegion(false), CollapseNumber(1),
110 InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000111 };
112
113 typedef SmallVector<SharingMapTy, 64> StackTy;
114
115 /// \brief Stack of used declaration and their data-sharing attributes.
116 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000117 /// \brief true, if check for DSA must be from parent directive, false, if
118 /// from current directive.
119 bool FromParent;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000120 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000121
122 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
123
124 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000125
126 /// \brief Checks if the variable is a local for OpenMP region.
127 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000128
Alexey Bataev758e55e2013-09-06 18:03:48 +0000129public:
Alexey Bataev39f915b82015-05-08 10:41:21 +0000130 explicit DSAStackTy(Sema &S) : Stack(1), FromParent(false), SemaRef(S) {}
131
132 bool isFromParent() const { return FromParent; }
133 void setFromParent(bool Flag) { FromParent = Flag; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000134
135 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000136 Scope *CurScope, SourceLocation Loc) {
137 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
138 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000139 }
140
141 void pop() {
142 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
143 Stack.pop_back();
144 }
145
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000146 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000147 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000148 /// for diagnostics.
149 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
150
Alexey Bataev9c821032015-04-30 04:23:23 +0000151 /// \brief Register specified variable as loop control variable.
152 void addLoopControlVariable(VarDecl *D);
153 /// \brief Check if the specified variable is a loop control variable for
154 /// current region.
155 bool isLoopControlVariable(VarDecl *D);
156
Alexey Bataev758e55e2013-09-06 18:03:48 +0000157 /// \brief Adds explicit data sharing attribute to the specified declaration.
158 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
159
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 /// \brief Returns data sharing attributes from top of the stack for the
161 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000162 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000164 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000165 /// \brief Checks if the specified variables has data-sharing attributes which
166 /// match specified \a CPred predicate in any directive which matches \a DPred
167 /// predicate.
168 template <class ClausesPredicate, class DirectivesPredicate>
169 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000170 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000171 /// \brief Checks if the specified variables has data-sharing attributes which
172 /// match specified \a CPred predicate in any innermost directive which
173 /// matches \a DPred predicate.
174 template <class ClausesPredicate, class DirectivesPredicate>
175 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000176 DirectivesPredicate DPred,
177 bool FromParent);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000178 /// \brief Finds a directive which matches specified \a DPred predicate.
179 template <class NamedDirectivesPredicate>
180 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000181
Alexey Bataev758e55e2013-09-06 18:03:48 +0000182 /// \brief Returns currently analyzed directive.
183 OpenMPDirectiveKind getCurrentDirective() const {
184 return Stack.back().Directive;
185 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000186 /// \brief Returns parent directive.
187 OpenMPDirectiveKind getParentDirective() const {
188 if (Stack.size() > 2)
189 return Stack[Stack.size() - 2].Directive;
190 return OMPD_unknown;
191 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000192
193 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000194 void setDefaultDSANone(SourceLocation Loc) {
195 Stack.back().DefaultAttr = DSA_none;
196 Stack.back().DefaultAttrLoc = Loc;
197 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000199 void setDefaultDSAShared(SourceLocation Loc) {
200 Stack.back().DefaultAttr = DSA_shared;
201 Stack.back().DefaultAttrLoc = Loc;
202 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000203
204 DefaultDataSharingAttributes getDefaultDSA() const {
205 return Stack.back().DefaultAttr;
206 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000207 SourceLocation getDefaultDSALocation() const {
208 return Stack.back().DefaultAttrLoc;
209 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000210
Alexey Bataevf29276e2014-06-18 04:14:57 +0000211 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000212 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000213 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000214 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000215 }
216
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000217 /// \brief Marks current region as ordered (it has an 'ordered' clause).
218 void setOrderedRegion(bool IsOrdered = true) {
219 Stack.back().OrderedRegion = IsOrdered;
220 }
221 /// \brief Returns true, if parent region is ordered (has associated
222 /// 'ordered' clause), false - otherwise.
223 bool isParentOrderedRegion() const {
224 if (Stack.size() > 2)
225 return Stack[Stack.size() - 2].OrderedRegion;
226 return false;
227 }
228
Alexey Bataev9c821032015-04-30 04:23:23 +0000229 /// \brief Set collapse value for the region.
230 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
231 /// \brief Return collapse value for region.
232 unsigned getCollapseNumber() const {
233 return Stack.back().CollapseNumber;
234 }
235
Alexey Bataev13314bf2014-10-09 04:18:56 +0000236 /// \brief Marks current target region as one with closely nested teams
237 /// region.
238 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
239 if (Stack.size() > 2)
240 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
241 }
242 /// \brief Returns true, if current region has closely nested teams region.
243 bool hasInnerTeamsRegion() const {
244 return getInnerTeamsRegionLoc().isValid();
245 }
246 /// \brief Returns location of the nested teams region (if any).
247 SourceLocation getInnerTeamsRegionLoc() const {
248 if (Stack.size() > 1)
249 return Stack.back().InnerTeamsRegionLoc;
250 return SourceLocation();
251 }
252
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000253 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000254 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000257bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
258 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000259 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000260}
Alexey Bataeved09d242014-05-28 05:53:51 +0000261} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000262
263DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
264 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000265 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000267 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000268 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
269 // in a region but not in construct]
270 // File-scope or namespace-scope variables referenced in called routines
271 // in the region are shared unless they appear in a threadprivate
272 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000273 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000274 DVar.CKind = OMPC_shared;
275
276 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
277 // in a region but not in construct]
278 // Variables with static storage duration that are declared in called
279 // routines in the region are shared.
280 if (D->hasGlobalStorage())
281 DVar.CKind = OMPC_shared;
282
Alexey Bataev758e55e2013-09-06 18:03:48 +0000283 return DVar;
284 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000285
Alexey Bataev758e55e2013-09-06 18:03:48 +0000286 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000287 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
288 // in a Construct, C/C++, predetermined, p.1]
289 // Variables with automatic storage duration that are declared in a scope
290 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000291 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
292 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
293 DVar.CKind = OMPC_private;
294 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000295 }
296
Alexey Bataev758e55e2013-09-06 18:03:48 +0000297 // Explicitly specified attributes and local variables with predetermined
298 // attributes.
299 if (Iter->SharingMap.count(D)) {
300 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
301 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000302 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000303 return DVar;
304 }
305
306 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
307 // in a Construct, C/C++, implicitly determined, p.1]
308 // In a parallel or task construct, the data-sharing attributes of these
309 // variables are determined by the default clause, if present.
310 switch (Iter->DefaultAttr) {
311 case DSA_shared:
312 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000313 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000314 return DVar;
315 case DSA_none:
316 return DVar;
317 case DSA_unspecified:
318 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
319 // in a Construct, implicitly determined, p.2]
320 // In a parallel construct, if no default clause is present, these
321 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000322 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000323 if (isOpenMPParallelDirective(DVar.DKind) ||
324 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000325 DVar.CKind = OMPC_shared;
326 return DVar;
327 }
328
329 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
330 // in a Construct, implicitly determined, p.4]
331 // In a task construct, if no default clause is present, a variable that in
332 // the enclosing context is determined to be shared by all implicit tasks
333 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000334 if (DVar.DKind == OMPD_task) {
335 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000336 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000337 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000338 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
339 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000340 // in a Construct, implicitly determined, p.6]
341 // In a task construct, if no default clause is present, a variable
342 // whose data-sharing attribute is not determined by the rules above is
343 // firstprivate.
344 DVarTemp = getDSA(I, D);
345 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000346 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000347 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000348 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000349 return DVar;
350 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000351 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000352 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000353 }
354 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000355 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000356 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000357 return DVar;
358 }
359 }
360 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
361 // in a Construct, implicitly determined, p.3]
362 // For constructs other than task, if no default clause is present, these
363 // variables inherit their data-sharing attributes from the enclosing
364 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000365 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000366}
367
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000368DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
369 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000370 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000371 auto It = Stack.back().AlignedMap.find(D);
372 if (It == Stack.back().AlignedMap.end()) {
373 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
374 Stack.back().AlignedMap[D] = NewDE;
375 return nullptr;
376 } else {
377 assert(It->second && "Unexpected nullptr expr in the aligned map");
378 return It->second;
379 }
380 return nullptr;
381}
382
Alexey Bataev9c821032015-04-30 04:23:23 +0000383void DSAStackTy::addLoopControlVariable(VarDecl *D) {
384 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
385 D = D->getCanonicalDecl();
386 Stack.back().LCVSet.insert(D);
387}
388
389bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
390 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
391 D = D->getCanonicalDecl();
392 return Stack.back().LCVSet.count(D) > 0;
393}
394
Alexey Bataev758e55e2013-09-06 18:03:48 +0000395void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000396 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000397 if (A == OMPC_threadprivate) {
398 Stack[0].SharingMap[D].Attributes = A;
399 Stack[0].SharingMap[D].RefExpr = E;
400 } else {
401 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
402 Stack.back().SharingMap[D].Attributes = A;
403 Stack.back().SharingMap[D].RefExpr = E;
404 }
405}
406
Alexey Bataeved09d242014-05-28 05:53:51 +0000407bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000408 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000409 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000410 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000411 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000412 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000413 ++I;
414 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000415 if (I == E)
416 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000417 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000418 Scope *CurScope = getCurScope();
419 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000420 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000421 }
422 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000423 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000424 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000425}
426
Alexey Bataev39f915b82015-05-08 10:41:21 +0000427/// \brief Build a variable declaration for OpenMP loop iteration variable.
428static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
429 StringRef Name) {
430 DeclContext *DC = SemaRef.CurContext;
431 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
432 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
433 VarDecl *Decl =
434 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
435 Decl->setImplicit();
436 return Decl;
437}
438
439static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
440 SourceLocation Loc,
441 bool RefersToCapture = false) {
442 D->setReferenced();
443 D->markUsed(S.Context);
444 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
445 SourceLocation(), D, RefersToCapture, Loc, Ty,
446 VK_LValue);
447}
448
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000449DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000450 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000451 DSAVarData DVar;
452
453 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
454 // in a Construct, C/C++, predetermined, p.1]
455 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000456 if (D->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000457 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
458 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000459 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
460 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000461 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000462 }
463 if (Stack[0].SharingMap.count(D)) {
464 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
465 DVar.CKind = OMPC_threadprivate;
466 return DVar;
467 }
468
469 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
470 // in a Construct, C/C++, predetermined, p.1]
471 // Variables with automatic storage duration that are declared in a scope
472 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000473 OpenMPDirectiveKind Kind =
474 FromParent ? getParentDirective() : getCurrentDirective();
475 auto StartI = std::next(Stack.rbegin());
476 auto EndI = std::prev(Stack.rend());
477 if (FromParent && StartI != EndI) {
478 StartI = std::next(StartI);
479 }
480 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000481 if (isOpenMPLocal(D, StartI) &&
482 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
483 D->getStorageClass() == SC_None)) ||
484 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000485 DVar.CKind = OMPC_private;
486 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000487 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000488
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000489 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
490 // in a Construct, C/C++, predetermined, p.4]
491 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000492 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
493 // in a Construct, C/C++, predetermined, p.7]
494 // Variables with static storage duration that are declared in a scope
495 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000496 if (D->isStaticDataMember() || D->isStaticLocal()) {
497 DSAVarData DVarTemp =
498 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
499 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
500 return DVar;
501
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000502 DVar.CKind = OMPC_shared;
503 return DVar;
504 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000505 }
506
507 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000508 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
509 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000510 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
511 // in a Construct, C/C++, predetermined, p.6]
512 // Variables with const qualified type having no mutable member are
513 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000514 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000515 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000516 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000517 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000518 // Variables with const-qualified type having no mutable member may be
519 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000520 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
521 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000522 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
523 return DVar;
524
Alexey Bataev758e55e2013-09-06 18:03:48 +0000525 DVar.CKind = OMPC_shared;
526 return DVar;
527 }
528
Alexey Bataev758e55e2013-09-06 18:03:48 +0000529 // Explicitly specified attributes and local variables with predetermined
530 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000531 auto I = std::prev(StartI);
532 if (I->SharingMap.count(D)) {
533 DVar.RefExpr = I->SharingMap[D].RefExpr;
534 DVar.CKind = I->SharingMap[D].Attributes;
535 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000536 }
537
538 return DVar;
539}
540
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000541DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000542 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000543 auto StartI = Stack.rbegin();
544 auto EndI = std::prev(Stack.rend());
545 if (FromParent && StartI != EndI) {
546 StartI = std::next(StartI);
547 }
548 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000549}
550
Alexey Bataevf29276e2014-06-18 04:14:57 +0000551template <class ClausesPredicate, class DirectivesPredicate>
552DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000553 DirectivesPredicate DPred,
554 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000555 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000556 auto StartI = std::next(Stack.rbegin());
557 auto EndI = std::prev(Stack.rend());
558 if (FromParent && StartI != EndI) {
559 StartI = std::next(StartI);
560 }
561 for (auto I = StartI, EE = EndI; I != EE; ++I) {
562 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000563 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000564 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000565 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000566 return DVar;
567 }
568 return DSAVarData();
569}
570
Alexey Bataevf29276e2014-06-18 04:14:57 +0000571template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000572DSAStackTy::DSAVarData
573DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
574 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000575 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000576 auto StartI = std::next(Stack.rbegin());
577 auto EndI = std::prev(Stack.rend());
578 if (FromParent && StartI != EndI) {
579 StartI = std::next(StartI);
580 }
581 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000582 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000583 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000584 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000585 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000586 return DVar;
587 return DSAVarData();
588 }
589 return DSAVarData();
590}
591
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000592template <class NamedDirectivesPredicate>
593bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
594 auto StartI = std::next(Stack.rbegin());
595 auto EndI = std::prev(Stack.rend());
596 if (FromParent && StartI != EndI) {
597 StartI = std::next(StartI);
598 }
599 for (auto I = StartI, EE = EndI; I != EE; ++I) {
600 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
601 return true;
602 }
603 return false;
604}
605
Alexey Bataev758e55e2013-09-06 18:03:48 +0000606void Sema::InitDataSharingAttributesStack() {
607 VarDataSharingAttributesStack = new DSAStackTy(*this);
608}
609
610#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
611
Alexey Bataevf841bd92014-12-16 07:00:22 +0000612bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
613 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000614 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000615 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000616 if (DSAStack->isLoopControlVariable(VD) ||
617 (VD->hasLocalStorage() &&
618 isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
Alexey Bataev9c821032015-04-30 04:23:23 +0000619 return true;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000620 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000621 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
622 return true;
623 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000624 DSAStack->isFromParent());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000625 return DVarPrivate.CKind != OMPC_unknown;
626 }
627 return false;
628}
629
Alexey Bataeved09d242014-05-28 05:53:51 +0000630void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000631
632void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
633 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000634 Scope *CurScope, SourceLocation Loc) {
635 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000636 PushExpressionEvaluationContext(PotentiallyEvaluated);
637}
638
Alexey Bataev39f915b82015-05-08 10:41:21 +0000639void Sema::StartOpenMPClauses() {
640 DSAStack->setFromParent(/*Flag=*/true);
641}
642
643void Sema::EndOpenMPClauses() {
644 DSAStack->setFromParent(/*Flag=*/false);
645}
646
Alexey Bataev758e55e2013-09-06 18:03:48 +0000647void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000648 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
649 // A variable of class type (or array thereof) that appears in a lastprivate
650 // clause requires an accessible, unambiguous default constructor for the
651 // class type, unless the list item is also specified in a firstprivate
652 // clause.
653 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000654 for (auto *C : D->clauses()) {
655 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
656 SmallVector<Expr *, 8> PrivateCopies;
657 for (auto *DE : Clause->varlists()) {
658 if (DE->isValueDependent() || DE->isTypeDependent()) {
659 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000660 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000661 }
662 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000663 QualType Type = VD->getType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000664 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000665 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000666 // Generate helper private variable and initialize it with the
667 // default value. The address of the original variable is replaced
668 // by the address of the new private variable in CodeGen. This new
669 // variable is not added to IdResolver, so the code in the OpenMP
670 // region uses original variable for proper diagnostics.
Alexey Bataev39f915b82015-05-08 10:41:21 +0000671 auto *VDPrivate =
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000672 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
673 VD->getName());
Alexey Bataev38e89532015-04-16 04:54:05 +0000674 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
675 if (VDPrivate->isInvalidDecl())
676 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000677 PrivateCopies.push_back(buildDeclRefExpr(
678 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000679 } else {
680 // The variable is also a firstprivate, so initialization sequence
681 // for private copy is generated already.
682 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000683 }
684 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000685 // Set initializers to private copies if no errors were found.
686 if (PrivateCopies.size() == Clause->varlist_size()) {
687 Clause->setPrivateCopies(PrivateCopies);
688 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000689 }
690 }
691 }
692
Alexey Bataev758e55e2013-09-06 18:03:48 +0000693 DSAStack->pop();
694 DiscardCleanupsInEvaluationContext();
695 PopExpressionEvaluationContext();
696}
697
Alexander Musman3276a272015-03-21 10:12:56 +0000698static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
699 Expr *NumIterations, Sema &SemaRef,
700 Scope *S);
701
Alexey Bataeva769e072013-03-22 06:34:35 +0000702namespace {
703
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000704class VarDeclFilterCCC : public CorrectionCandidateCallback {
705private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000706 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000707
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000708public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000709 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000710 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000711 NamedDecl *ND = Candidate.getCorrectionDecl();
712 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
713 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000714 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
715 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000716 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000717 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000718 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000719};
Alexey Bataeved09d242014-05-28 05:53:51 +0000720} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000721
722ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
723 CXXScopeSpec &ScopeSpec,
724 const DeclarationNameInfo &Id) {
725 LookupResult Lookup(*this, Id, LookupOrdinaryName);
726 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
727
728 if (Lookup.isAmbiguous())
729 return ExprError();
730
731 VarDecl *VD;
732 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000733 if (TypoCorrection Corrected = CorrectTypo(
734 Id, LookupOrdinaryName, CurScope, nullptr,
735 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000736 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000737 PDiag(Lookup.empty()
738 ? diag::err_undeclared_var_use_suggest
739 : diag::err_omp_expected_var_arg_suggest)
740 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000741 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000742 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000743 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
744 : diag::err_omp_expected_var_arg)
745 << Id.getName();
746 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000747 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000748 } else {
749 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000750 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000751 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
752 return ExprError();
753 }
754 }
755 Lookup.suppressDiagnostics();
756
757 // OpenMP [2.9.2, Syntax, C/C++]
758 // Variables must be file-scope, namespace-scope, or static block-scope.
759 if (!VD->hasGlobalStorage()) {
760 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000761 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
762 bool IsDecl =
763 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000764 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
766 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000767 return ExprError();
768 }
769
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000770 VarDecl *CanonicalVD = VD->getCanonicalDecl();
771 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000772 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
773 // A threadprivate directive for file-scope variables must appear outside
774 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000775 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
776 !getCurLexicalContext()->isTranslationUnit()) {
777 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000778 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
779 bool IsDecl =
780 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
781 Diag(VD->getLocation(),
782 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
783 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000784 return ExprError();
785 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000786 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
787 // A threadprivate directive for static class member variables must appear
788 // in the class definition, in the same scope in which the member
789 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000790 if (CanonicalVD->isStaticDataMember() &&
791 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
792 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000793 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
794 bool IsDecl =
795 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
796 Diag(VD->getLocation(),
797 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
798 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000799 return ExprError();
800 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000801 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
802 // A threadprivate directive for namespace-scope variables must appear
803 // outside any definition or declaration other than the namespace
804 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000805 if (CanonicalVD->getDeclContext()->isNamespace() &&
806 (!getCurLexicalContext()->isFileContext() ||
807 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
808 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000809 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
810 bool IsDecl =
811 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
812 Diag(VD->getLocation(),
813 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
814 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000815 return ExprError();
816 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000817 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
818 // A threadprivate directive for static block-scope variables must appear
819 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000820 if (CanonicalVD->isStaticLocal() && CurScope &&
821 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000822 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000823 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
824 bool IsDecl =
825 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
826 Diag(VD->getLocation(),
827 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
828 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000829 return ExprError();
830 }
831
832 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
833 // A threadprivate directive must lexically precede all references to any
834 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000835 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000836 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000837 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000838 return ExprError();
839 }
840
841 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +0000842 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000843 return DE;
844}
845
Alexey Bataeved09d242014-05-28 05:53:51 +0000846Sema::DeclGroupPtrTy
847Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
848 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000849 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000850 CurContext->addDecl(D);
851 return DeclGroupPtrTy::make(DeclGroupRef(D));
852 }
853 return DeclGroupPtrTy();
854}
855
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000856namespace {
857class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
858 Sema &SemaRef;
859
860public:
861 bool VisitDeclRefExpr(const DeclRefExpr *E) {
862 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
863 if (VD->hasLocalStorage()) {
864 SemaRef.Diag(E->getLocStart(),
865 diag::err_omp_local_var_in_threadprivate_init)
866 << E->getSourceRange();
867 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
868 << VD << VD->getSourceRange();
869 return true;
870 }
871 }
872 return false;
873 }
874 bool VisitStmt(const Stmt *S) {
875 for (auto Child : S->children()) {
876 if (Child && Visit(Child))
877 return true;
878 }
879 return false;
880 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000881 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000882};
883} // namespace
884
Alexey Bataeved09d242014-05-28 05:53:51 +0000885OMPThreadPrivateDecl *
886Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000887 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000888 for (auto &RefExpr : VarList) {
889 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000890 VarDecl *VD = cast<VarDecl>(DE->getDecl());
891 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000892
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000893 QualType QType = VD->getType();
894 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
895 // It will be analyzed later.
896 Vars.push_back(DE);
897 continue;
898 }
899
Alexey Bataeva769e072013-03-22 06:34:35 +0000900 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
901 // A threadprivate variable must not have an incomplete type.
902 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000903 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000904 continue;
905 }
906
907 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
908 // A threadprivate variable must not have a reference type.
909 if (VD->getType()->isReferenceType()) {
910 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000911 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
912 bool IsDecl =
913 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
914 Diag(VD->getLocation(),
915 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
916 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000917 continue;
918 }
919
Richard Smithfd3834f2013-04-13 02:43:54 +0000920 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000921 if (VD->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000922 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
923 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +0000924 Diag(ILoc, diag::err_omp_var_thread_local)
925 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000926 bool IsDecl =
927 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
928 Diag(VD->getLocation(),
929 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
930 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000931 continue;
932 }
933
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000934 // Check if initial value of threadprivate variable reference variable with
935 // local storage (it is not supported by runtime).
936 if (auto Init = VD->getAnyInitializer()) {
937 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000938 if (Checker.Visit(Init))
939 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000940 }
941
Alexey Bataeved09d242014-05-28 05:53:51 +0000942 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000943 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000944 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
945 Context, SourceRange(Loc, Loc)));
946 if (auto *ML = Context.getASTMutationListener())
947 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000948 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000949 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000950 if (!Vars.empty()) {
951 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
952 Vars);
953 D->setAccess(AS_public);
954 }
955 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000956}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000957
Alexey Bataev7ff55242014-06-19 09:13:45 +0000958static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
959 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
960 bool IsLoopIterVar = false) {
961 if (DVar.RefExpr) {
962 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
963 << getOpenMPClauseName(DVar.CKind);
964 return;
965 }
966 enum {
967 PDSA_StaticMemberShared,
968 PDSA_StaticLocalVarShared,
969 PDSA_LoopIterVarPrivate,
970 PDSA_LoopIterVarLinear,
971 PDSA_LoopIterVarLastprivate,
972 PDSA_ConstVarShared,
973 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000974 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000975 PDSA_LocalVarPrivate,
976 PDSA_Implicit
977 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000978 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000979 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000980 if (IsLoopIterVar) {
981 if (DVar.CKind == OMPC_private)
982 Reason = PDSA_LoopIterVarPrivate;
983 else if (DVar.CKind == OMPC_lastprivate)
984 Reason = PDSA_LoopIterVarLastprivate;
985 else
986 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000987 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
988 Reason = PDSA_TaskVarFirstprivate;
989 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000990 } else if (VD->isStaticLocal())
991 Reason = PDSA_StaticLocalVarShared;
992 else if (VD->isStaticDataMember())
993 Reason = PDSA_StaticMemberShared;
994 else if (VD->isFileVarDecl())
995 Reason = PDSA_GlobalVarShared;
996 else if (VD->getType().isConstant(SemaRef.getASTContext()))
997 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000998 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000999 ReportHint = true;
1000 Reason = PDSA_LocalVarPrivate;
1001 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001002 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001003 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001004 << Reason << ReportHint
1005 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1006 } else if (DVar.ImplicitDSALoc.isValid()) {
1007 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1008 << getOpenMPClauseName(DVar.CKind);
1009 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001010}
1011
Alexey Bataev758e55e2013-09-06 18:03:48 +00001012namespace {
1013class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1014 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001015 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001016 bool ErrorFound;
1017 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001018 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001019 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001020
Alexey Bataev758e55e2013-09-06 18:03:48 +00001021public:
1022 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001023 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001024 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001025 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1026 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001027
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001028 auto DVar = Stack->getTopDSA(VD, false);
1029 // Check if the variable has explicit DSA set and stop analysis if it so.
1030 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001031
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001032 auto ELoc = E->getExprLoc();
1033 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034 // The default(none) clause requires that each variable that is referenced
1035 // in the construct, and does not have a predetermined data-sharing
1036 // attribute, must have its data-sharing attribute explicitly determined
1037 // by being listed in a data-sharing attribute clause.
1038 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001039 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001040 VarsWithInheritedDSA.count(VD) == 0) {
1041 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001042 return;
1043 }
1044
1045 // OpenMP [2.9.3.6, Restrictions, p.2]
1046 // A list item that appears in a reduction clause of the innermost
1047 // enclosing worksharing or parallel construct may not be accessed in an
1048 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001049 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001050 [](OpenMPDirectiveKind K) -> bool {
1051 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001052 isOpenMPWorksharingDirective(K) ||
1053 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001054 },
1055 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001056 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1057 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001058 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1059 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001060 return;
1061 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001062
1063 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001064 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001065 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001066 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001067 }
1068 }
1069 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001070 for (auto *C : S->clauses()) {
1071 // Skip analysis of arguments of implicitly defined firstprivate clause
1072 // for task directives.
1073 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1074 for (auto *CC : C->children()) {
1075 if (CC)
1076 Visit(CC);
1077 }
1078 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001079 }
1080 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001081 for (auto *C : S->children()) {
1082 if (C && !isa<OMPExecutableDirective>(C))
1083 Visit(C);
1084 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001085 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001086
1087 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001088 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001089 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1090 return VarsWithInheritedDSA;
1091 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001092
Alexey Bataev7ff55242014-06-19 09:13:45 +00001093 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1094 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001095};
Alexey Bataeved09d242014-05-28 05:53:51 +00001096} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001097
Alexey Bataevbae9a792014-06-27 10:37:06 +00001098void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001099 switch (DKind) {
1100 case OMPD_parallel: {
1101 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1102 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001103 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001104 std::make_pair(".global_tid.", KmpInt32PtrTy),
1105 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1106 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001107 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001108 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1109 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001110 break;
1111 }
1112 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001113 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001114 std::make_pair(StringRef(), QualType()) // __context with shared vars
1115 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001116 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1117 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001118 break;
1119 }
1120 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001121 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001122 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001123 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001124 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1125 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001126 break;
1127 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001128 case OMPD_for_simd: {
1129 Sema::CapturedParamNameType Params[] = {
1130 std::make_pair(StringRef(), QualType()) // __context with shared vars
1131 };
1132 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1133 Params);
1134 break;
1135 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001136 case OMPD_sections: {
1137 Sema::CapturedParamNameType Params[] = {
1138 std::make_pair(StringRef(), QualType()) // __context with shared vars
1139 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001140 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1141 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001142 break;
1143 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001144 case OMPD_section: {
1145 Sema::CapturedParamNameType Params[] = {
1146 std::make_pair(StringRef(), QualType()) // __context with shared vars
1147 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001148 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1149 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001150 break;
1151 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001152 case OMPD_single: {
1153 Sema::CapturedParamNameType Params[] = {
1154 std::make_pair(StringRef(), QualType()) // __context with shared vars
1155 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001156 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1157 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001158 break;
1159 }
Alexander Musman80c22892014-07-17 08:54:58 +00001160 case OMPD_master: {
1161 Sema::CapturedParamNameType Params[] = {
1162 std::make_pair(StringRef(), QualType()) // __context with shared vars
1163 };
1164 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1165 Params);
1166 break;
1167 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001168 case OMPD_critical: {
1169 Sema::CapturedParamNameType Params[] = {
1170 std::make_pair(StringRef(), QualType()) // __context with shared vars
1171 };
1172 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1173 Params);
1174 break;
1175 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001176 case OMPD_parallel_for: {
1177 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1178 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1179 Sema::CapturedParamNameType Params[] = {
1180 std::make_pair(".global_tid.", KmpInt32PtrTy),
1181 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1182 std::make_pair(StringRef(), QualType()) // __context with shared vars
1183 };
1184 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1185 Params);
1186 break;
1187 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001188 case OMPD_parallel_for_simd: {
1189 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1190 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1191 Sema::CapturedParamNameType Params[] = {
1192 std::make_pair(".global_tid.", KmpInt32PtrTy),
1193 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1194 std::make_pair(StringRef(), QualType()) // __context with shared vars
1195 };
1196 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1197 Params);
1198 break;
1199 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001200 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001201 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1202 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001203 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001204 std::make_pair(".global_tid.", KmpInt32PtrTy),
1205 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001206 std::make_pair(StringRef(), QualType()) // __context with shared vars
1207 };
1208 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1209 Params);
1210 break;
1211 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001212 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001213 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001214 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001215 std::make_pair(".global_tid.", KmpInt32Ty),
1216 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001217 std::make_pair(StringRef(), QualType()) // __context with shared vars
1218 };
1219 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1220 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001221 // Mark this captured region as inlined, because we don't use outlined
1222 // function directly.
1223 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1224 AlwaysInlineAttr::CreateImplicit(
1225 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001226 break;
1227 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001228 case OMPD_ordered: {
1229 Sema::CapturedParamNameType Params[] = {
1230 std::make_pair(StringRef(), QualType()) // __context with shared vars
1231 };
1232 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1233 Params);
1234 break;
1235 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001236 case OMPD_atomic: {
1237 Sema::CapturedParamNameType Params[] = {
1238 std::make_pair(StringRef(), QualType()) // __context with shared vars
1239 };
1240 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1241 Params);
1242 break;
1243 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001244 case OMPD_target: {
1245 Sema::CapturedParamNameType Params[] = {
1246 std::make_pair(StringRef(), QualType()) // __context with shared vars
1247 };
1248 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1249 Params);
1250 break;
1251 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001252 case OMPD_teams: {
1253 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1254 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1255 Sema::CapturedParamNameType Params[] = {
1256 std::make_pair(".global_tid.", KmpInt32PtrTy),
1257 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1258 std::make_pair(StringRef(), QualType()) // __context with shared vars
1259 };
1260 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1261 Params);
1262 break;
1263 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001264 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001265 case OMPD_taskyield:
1266 case OMPD_barrier:
1267 case OMPD_taskwait:
1268 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001269 llvm_unreachable("OpenMP Directive is not allowed");
1270 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001271 llvm_unreachable("Unknown OpenMP directive");
1272 }
1273}
1274
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001275StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1276 ArrayRef<OMPClause *> Clauses) {
1277 if (!S.isUsable()) {
1278 ActOnCapturedRegionError();
1279 return StmtError();
1280 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001281 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001282 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001283 if (isOpenMPPrivate(Clause->getClauseKind()) ||
1284 Clause->getClauseKind() == OMPC_copyprivate) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001285 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001286 for (auto *VarRef : Clause->children()) {
1287 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001288 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001289 }
1290 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001291 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1292 Clause->getClauseKind() == OMPC_schedule) {
1293 // Mark all variables in private list clauses as used in inner region.
1294 // Required for proper codegen of combined directives.
1295 // TODO: add processing for other clauses.
1296 if (auto *E = cast_or_null<Expr>(
1297 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1298 MarkDeclarationsReferencedInExpr(E);
1299 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001300 }
1301 }
1302 return ActOnCapturedRegionEnd(S.get());
1303}
1304
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001305static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1306 OpenMPDirectiveKind CurrentRegion,
1307 const DeclarationNameInfo &CurrentName,
1308 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001309 // Allowed nesting of constructs
1310 // +------------------+-----------------+------------------------------------+
1311 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1312 // +------------------+-----------------+------------------------------------+
1313 // | parallel | parallel | * |
1314 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001315 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001316 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001317 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001318 // | parallel | simd | * |
1319 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001320 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001321 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001322 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001323 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001324 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001325 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001326 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001327 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001328 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001329 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001330 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001331 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001332 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001333 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001334 // +------------------+-----------------+------------------------------------+
1335 // | for | parallel | * |
1336 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001337 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001338 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001339 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001340 // | for | simd | * |
1341 // | for | sections | + |
1342 // | for | section | + |
1343 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001344 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001345 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001346 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001347 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001348 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001349 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001350 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001351 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001352 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001353 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001354 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001355 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001356 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001357 // | master | parallel | * |
1358 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001359 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001360 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001361 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001362 // | master | simd | * |
1363 // | master | sections | + |
1364 // | master | section | + |
1365 // | master | single | + |
1366 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001367 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001368 // | master |parallel sections| * |
1369 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001370 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001371 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001372 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001373 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001374 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001375 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001376 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001377 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001378 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001379 // | critical | parallel | * |
1380 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001381 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001382 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001383 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001384 // | critical | simd | * |
1385 // | critical | sections | + |
1386 // | critical | section | + |
1387 // | critical | single | + |
1388 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001389 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001390 // | critical |parallel sections| * |
1391 // | critical | task | * |
1392 // | critical | taskyield | * |
1393 // | critical | barrier | + |
1394 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001395 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001396 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001397 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001398 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001399 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001400 // | simd | parallel | |
1401 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001402 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001403 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001404 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001405 // | simd | simd | |
1406 // | simd | sections | |
1407 // | simd | section | |
1408 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001409 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001410 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001411 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001412 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001413 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001414 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001415 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001416 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001417 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001418 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001419 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001420 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001421 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001422 // | for simd | parallel | |
1423 // | for simd | for | |
1424 // | for simd | for simd | |
1425 // | for simd | master | |
1426 // | for simd | critical | |
1427 // | for simd | simd | |
1428 // | for simd | sections | |
1429 // | for simd | section | |
1430 // | for simd | single | |
1431 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001432 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001433 // | for simd |parallel sections| |
1434 // | for simd | task | |
1435 // | for simd | taskyield | |
1436 // | for simd | barrier | |
1437 // | for simd | taskwait | |
1438 // | for simd | flush | |
1439 // | for simd | ordered | |
1440 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001441 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001442 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001443 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001444 // | parallel for simd| parallel | |
1445 // | parallel for simd| for | |
1446 // | parallel for simd| for simd | |
1447 // | parallel for simd| master | |
1448 // | parallel for simd| critical | |
1449 // | parallel for simd| simd | |
1450 // | parallel for simd| sections | |
1451 // | parallel for simd| section | |
1452 // | parallel for simd| single | |
1453 // | parallel for simd| parallel for | |
1454 // | parallel for simd|parallel for simd| |
1455 // | parallel for simd|parallel sections| |
1456 // | parallel for simd| task | |
1457 // | parallel for simd| taskyield | |
1458 // | parallel for simd| barrier | |
1459 // | parallel for simd| taskwait | |
1460 // | parallel for simd| flush | |
1461 // | parallel for simd| ordered | |
1462 // | parallel for simd| atomic | |
1463 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001464 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001465 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001466 // | sections | parallel | * |
1467 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001468 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001469 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001470 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001471 // | sections | simd | * |
1472 // | sections | sections | + |
1473 // | sections | section | * |
1474 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001475 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001476 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001477 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001478 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001479 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001480 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001481 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001482 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001483 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001484 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001485 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001486 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001487 // +------------------+-----------------+------------------------------------+
1488 // | section | parallel | * |
1489 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001490 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001491 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001492 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001493 // | section | simd | * |
1494 // | section | sections | + |
1495 // | section | section | + |
1496 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001497 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001498 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001499 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001500 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001501 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001502 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001503 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001504 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001505 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001506 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001507 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001508 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001509 // +------------------+-----------------+------------------------------------+
1510 // | single | parallel | * |
1511 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001512 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001513 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001514 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001515 // | single | simd | * |
1516 // | single | sections | + |
1517 // | single | section | + |
1518 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001519 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001520 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001521 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001522 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001523 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001524 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001525 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001526 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001527 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001528 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001529 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001530 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001531 // +------------------+-----------------+------------------------------------+
1532 // | parallel for | parallel | * |
1533 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001534 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001535 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001536 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001537 // | parallel for | simd | * |
1538 // | parallel for | sections | + |
1539 // | parallel for | section | + |
1540 // | parallel for | single | + |
1541 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001542 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001543 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001544 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001545 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001546 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001547 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001548 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001549 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001550 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001551 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001552 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001553 // +------------------+-----------------+------------------------------------+
1554 // | parallel sections| parallel | * |
1555 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001556 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001557 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001558 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001559 // | parallel sections| simd | * |
1560 // | parallel sections| sections | + |
1561 // | parallel sections| section | * |
1562 // | parallel sections| single | + |
1563 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001564 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001565 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001566 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001567 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001568 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001569 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001570 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001571 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001572 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001573 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001574 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001575 // +------------------+-----------------+------------------------------------+
1576 // | task | parallel | * |
1577 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001578 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001579 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001580 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001581 // | task | simd | * |
1582 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001583 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001584 // | task | single | + |
1585 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001586 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001587 // | task |parallel sections| * |
1588 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001589 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001590 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001591 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001592 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001593 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001594 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001595 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001596 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001597 // +------------------+-----------------+------------------------------------+
1598 // | ordered | parallel | * |
1599 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001600 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001601 // | ordered | master | * |
1602 // | ordered | critical | * |
1603 // | ordered | simd | * |
1604 // | ordered | sections | + |
1605 // | ordered | section | + |
1606 // | ordered | single | + |
1607 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001608 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001609 // | ordered |parallel sections| * |
1610 // | ordered | task | * |
1611 // | ordered | taskyield | * |
1612 // | ordered | barrier | + |
1613 // | ordered | taskwait | * |
1614 // | ordered | flush | * |
1615 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001616 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001617 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001618 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001619 // +------------------+-----------------+------------------------------------+
1620 // | atomic | parallel | |
1621 // | atomic | for | |
1622 // | atomic | for simd | |
1623 // | atomic | master | |
1624 // | atomic | critical | |
1625 // | atomic | simd | |
1626 // | atomic | sections | |
1627 // | atomic | section | |
1628 // | atomic | single | |
1629 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001630 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001631 // | atomic |parallel sections| |
1632 // | atomic | task | |
1633 // | atomic | taskyield | |
1634 // | atomic | barrier | |
1635 // | atomic | taskwait | |
1636 // | atomic | flush | |
1637 // | atomic | ordered | |
1638 // | atomic | atomic | |
1639 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001640 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001641 // +------------------+-----------------+------------------------------------+
1642 // | target | parallel | * |
1643 // | target | for | * |
1644 // | target | for simd | * |
1645 // | target | master | * |
1646 // | target | critical | * |
1647 // | target | simd | * |
1648 // | target | sections | * |
1649 // | target | section | * |
1650 // | target | single | * |
1651 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001652 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001653 // | target |parallel sections| * |
1654 // | target | task | * |
1655 // | target | taskyield | * |
1656 // | target | barrier | * |
1657 // | target | taskwait | * |
1658 // | target | flush | * |
1659 // | target | ordered | * |
1660 // | target | atomic | * |
1661 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001662 // | target | teams | * |
1663 // +------------------+-----------------+------------------------------------+
1664 // | teams | parallel | * |
1665 // | teams | for | + |
1666 // | teams | for simd | + |
1667 // | teams | master | + |
1668 // | teams | critical | + |
1669 // | teams | simd | + |
1670 // | teams | sections | + |
1671 // | teams | section | + |
1672 // | teams | single | + |
1673 // | teams | parallel for | * |
1674 // | teams |parallel for simd| * |
1675 // | teams |parallel sections| * |
1676 // | teams | task | + |
1677 // | teams | taskyield | + |
1678 // | teams | barrier | + |
1679 // | teams | taskwait | + |
1680 // | teams | flush | + |
1681 // | teams | ordered | + |
1682 // | teams | atomic | + |
1683 // | teams | target | + |
1684 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001685 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001686 if (Stack->getCurScope()) {
1687 auto ParentRegion = Stack->getParentDirective();
1688 bool NestingProhibited = false;
1689 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001690 enum {
1691 NoRecommend,
1692 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001693 ShouldBeInOrderedRegion,
1694 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001695 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001696 if (isOpenMPSimdDirective(ParentRegion)) {
1697 // OpenMP [2.16, Nesting of Regions]
1698 // OpenMP constructs may not be nested inside a simd region.
1699 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1700 return true;
1701 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001702 if (ParentRegion == OMPD_atomic) {
1703 // OpenMP [2.16, Nesting of Regions]
1704 // OpenMP constructs may not be nested inside an atomic region.
1705 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1706 return true;
1707 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001708 if (CurrentRegion == OMPD_section) {
1709 // OpenMP [2.7.2, sections Construct, Restrictions]
1710 // Orphaned section directives are prohibited. That is, the section
1711 // directives must appear within the sections construct and must not be
1712 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001713 if (ParentRegion != OMPD_sections &&
1714 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001715 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1716 << (ParentRegion != OMPD_unknown)
1717 << getOpenMPDirectiveName(ParentRegion);
1718 return true;
1719 }
1720 return false;
1721 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001722 // Allow some constructs to be orphaned (they could be used in functions,
1723 // called from OpenMP regions with the required preconditions).
1724 if (ParentRegion == OMPD_unknown)
1725 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001726 if (CurrentRegion == OMPD_master) {
1727 // OpenMP [2.16, Nesting of Regions]
1728 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001729 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001730 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1731 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001732 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1733 // OpenMP [2.16, Nesting of Regions]
1734 // A critical region may not be nested (closely or otherwise) inside a
1735 // critical region with the same name. Note that this restriction is not
1736 // sufficient to prevent deadlock.
1737 SourceLocation PreviousCriticalLoc;
1738 bool DeadLock =
1739 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1740 OpenMPDirectiveKind K,
1741 const DeclarationNameInfo &DNI,
1742 SourceLocation Loc)
1743 ->bool {
1744 if (K == OMPD_critical &&
1745 DNI.getName() == CurrentName.getName()) {
1746 PreviousCriticalLoc = Loc;
1747 return true;
1748 } else
1749 return false;
1750 },
1751 false /* skip top directive */);
1752 if (DeadLock) {
1753 SemaRef.Diag(StartLoc,
1754 diag::err_omp_prohibited_region_critical_same_name)
1755 << CurrentName.getName();
1756 if (PreviousCriticalLoc.isValid())
1757 SemaRef.Diag(PreviousCriticalLoc,
1758 diag::note_omp_previous_critical_region);
1759 return true;
1760 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001761 } else if (CurrentRegion == OMPD_barrier) {
1762 // OpenMP [2.16, Nesting of Regions]
1763 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001764 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001765 NestingProhibited =
1766 isOpenMPWorksharingDirective(ParentRegion) ||
1767 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1768 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001769 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001770 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001771 // OpenMP [2.16, Nesting of Regions]
1772 // A worksharing region may not be closely nested inside a worksharing,
1773 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001774 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001775 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001776 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1777 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1778 Recommend = ShouldBeInParallelRegion;
1779 } else if (CurrentRegion == OMPD_ordered) {
1780 // OpenMP [2.16, Nesting of Regions]
1781 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001782 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001783 // An ordered region must be closely nested inside a loop region (or
1784 // parallel loop region) with an ordered clause.
1785 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001786 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001787 !Stack->isParentOrderedRegion();
1788 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001789 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1790 // OpenMP [2.16, Nesting of Regions]
1791 // If specified, a teams construct must be contained within a target
1792 // construct.
1793 NestingProhibited = ParentRegion != OMPD_target;
1794 Recommend = ShouldBeInTargetRegion;
1795 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1796 }
1797 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1798 // OpenMP [2.16, Nesting of Regions]
1799 // distribute, parallel, parallel sections, parallel workshare, and the
1800 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1801 // constructs that can be closely nested in the teams region.
1802 // TODO: add distribute directive.
1803 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1804 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001805 }
1806 if (NestingProhibited) {
1807 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001808 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1809 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001810 return true;
1811 }
1812 }
1813 return false;
1814}
1815
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001816StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001817 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001818 ArrayRef<OMPClause *> Clauses,
1819 Stmt *AStmt,
1820 SourceLocation StartLoc,
1821 SourceLocation EndLoc) {
1822 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001823 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001824 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001825
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001826 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001827 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001828 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001829 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001830 if (AStmt) {
1831 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1832
1833 // Check default data sharing attributes for referenced variables.
1834 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1835 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1836 if (DSAChecker.isErrorFound())
1837 return StmtError();
1838 // Generate list of implicitly defined firstprivate variables.
1839 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001840
1841 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1842 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1843 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1844 SourceLocation(), SourceLocation())) {
1845 ClausesWithImplicit.push_back(Implicit);
1846 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1847 DSAChecker.getImplicitFirstprivate().size();
1848 } else
1849 ErrorFound = true;
1850 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001851 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001852
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001853 switch (Kind) {
1854 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001855 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1856 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001857 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001858 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001859 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1860 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001861 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001862 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001863 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1864 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001865 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001866 case OMPD_for_simd:
1867 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1868 EndLoc, VarsWithInheritedDSA);
1869 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001870 case OMPD_sections:
1871 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1872 EndLoc);
1873 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001874 case OMPD_section:
1875 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001876 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001877 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1878 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001879 case OMPD_single:
1880 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1881 EndLoc);
1882 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001883 case OMPD_master:
1884 assert(ClausesWithImplicit.empty() &&
1885 "No clauses are allowed for 'omp master' directive");
1886 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1887 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001888 case OMPD_critical:
1889 assert(ClausesWithImplicit.empty() &&
1890 "No clauses are allowed for 'omp critical' directive");
1891 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1892 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001893 case OMPD_parallel_for:
1894 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1895 EndLoc, VarsWithInheritedDSA);
1896 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001897 case OMPD_parallel_for_simd:
1898 Res = ActOnOpenMPParallelForSimdDirective(
1899 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1900 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001901 case OMPD_parallel_sections:
1902 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1903 StartLoc, EndLoc);
1904 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001905 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001906 Res =
1907 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1908 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001909 case OMPD_taskyield:
1910 assert(ClausesWithImplicit.empty() &&
1911 "No clauses are allowed for 'omp taskyield' directive");
1912 assert(AStmt == nullptr &&
1913 "No associated statement allowed for 'omp taskyield' directive");
1914 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1915 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001916 case OMPD_barrier:
1917 assert(ClausesWithImplicit.empty() &&
1918 "No clauses are allowed for 'omp barrier' directive");
1919 assert(AStmt == nullptr &&
1920 "No associated statement allowed for 'omp barrier' directive");
1921 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1922 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001923 case OMPD_taskwait:
1924 assert(ClausesWithImplicit.empty() &&
1925 "No clauses are allowed for 'omp taskwait' directive");
1926 assert(AStmt == nullptr &&
1927 "No associated statement allowed for 'omp taskwait' directive");
1928 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1929 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001930 case OMPD_flush:
1931 assert(AStmt == nullptr &&
1932 "No associated statement allowed for 'omp flush' directive");
1933 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1934 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001935 case OMPD_ordered:
1936 assert(ClausesWithImplicit.empty() &&
1937 "No clauses are allowed for 'omp ordered' directive");
1938 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1939 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001940 case OMPD_atomic:
1941 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1942 EndLoc);
1943 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001944 case OMPD_teams:
1945 Res =
1946 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1947 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001948 case OMPD_target:
1949 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1950 EndLoc);
1951 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001952 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001953 llvm_unreachable("OpenMP Directive is not allowed");
1954 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001955 llvm_unreachable("Unknown OpenMP directive");
1956 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001957
Alexey Bataev4acb8592014-07-07 13:01:15 +00001958 for (auto P : VarsWithInheritedDSA) {
1959 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1960 << P.first << P.second->getSourceRange();
1961 }
1962 if (!VarsWithInheritedDSA.empty())
1963 return StmtError();
1964
Alexey Bataeved09d242014-05-28 05:53:51 +00001965 if (ErrorFound)
1966 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001967 return Res;
1968}
1969
1970StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1971 Stmt *AStmt,
1972 SourceLocation StartLoc,
1973 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001974 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1975 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1976 // 1.2.2 OpenMP Language Terminology
1977 // Structured block - An executable statement with a single entry at the
1978 // top and a single exit at the bottom.
1979 // The point of exit cannot be a branch out of the structured block.
1980 // longjmp() and throw() must not violate the entry/exit criteria.
1981 CS->getCapturedDecl()->setNothrow();
1982
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001983 getCurFunction()->setHasBranchProtectedScope();
1984
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001985 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1986 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001987}
1988
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001989namespace {
1990/// \brief Helper class for checking canonical form of the OpenMP loops and
1991/// extracting iteration space of each loop in the loop nest, that will be used
1992/// for IR generation.
1993class OpenMPIterationSpaceChecker {
1994 /// \brief Reference to Sema.
1995 Sema &SemaRef;
1996 /// \brief A location for diagnostics (when there is no some better location).
1997 SourceLocation DefaultLoc;
1998 /// \brief A location for diagnostics (when increment is not compatible).
1999 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002000 /// \brief A source location for referring to loop init later.
2001 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002002 /// \brief A source location for referring to condition later.
2003 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002004 /// \brief A source location for referring to increment later.
2005 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002006 /// \brief Loop variable.
2007 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002008 /// \brief Reference to loop variable.
2009 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002010 /// \brief Lower bound (initializer for the var).
2011 Expr *LB;
2012 /// \brief Upper bound.
2013 Expr *UB;
2014 /// \brief Loop step (increment).
2015 Expr *Step;
2016 /// \brief This flag is true when condition is one of:
2017 /// Var < UB
2018 /// Var <= UB
2019 /// UB > Var
2020 /// UB >= Var
2021 bool TestIsLessOp;
2022 /// \brief This flag is true when condition is strict ( < or > ).
2023 bool TestIsStrictOp;
2024 /// \brief This flag is true when step is subtracted on each iteration.
2025 bool SubtractStep;
2026
2027public:
2028 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2029 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002030 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2031 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002032 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2033 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002034 /// \brief Check init-expr for canonical loop form and save loop counter
2035 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002036 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002037 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2038 /// for less/greater and for strict/non-strict comparison.
2039 bool CheckCond(Expr *S);
2040 /// \brief Check incr-expr for canonical loop form and return true if it
2041 /// does not conform, otherwise save loop step (#Step).
2042 bool CheckInc(Expr *S);
2043 /// \brief Return the loop counter variable.
2044 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002045 /// \brief Return the reference expression to loop counter variable.
2046 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002047 /// \brief Source range of the loop init.
2048 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2049 /// \brief Source range of the loop condition.
2050 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2051 /// \brief Source range of the loop increment.
2052 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2053 /// \brief True if the step should be subtracted.
2054 bool ShouldSubtractStep() const { return SubtractStep; }
2055 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002056 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002057 /// \brief Build the precondition expression for the loops.
2058 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002059 /// \brief Build reference expression to the counter be used for codegen.
2060 Expr *BuildCounterVar() const;
2061 /// \brief Build initization of the counter be used for codegen.
2062 Expr *BuildCounterInit() const;
2063 /// \brief Build step of the counter be used for codegen.
2064 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002065 /// \brief Return true if any expression is dependent.
2066 bool Dependent() const;
2067
2068private:
2069 /// \brief Check the right-hand side of an assignment in the increment
2070 /// expression.
2071 bool CheckIncRHS(Expr *RHS);
2072 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002073 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002074 /// \brief Helper to set upper bound.
2075 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2076 const SourceLocation &SL);
2077 /// \brief Helper to set loop increment.
2078 bool SetStep(Expr *NewStep, bool Subtract);
2079};
2080
2081bool OpenMPIterationSpaceChecker::Dependent() const {
2082 if (!Var) {
2083 assert(!LB && !UB && !Step);
2084 return false;
2085 }
2086 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2087 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2088}
2089
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002090bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2091 DeclRefExpr *NewVarRefExpr,
2092 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002093 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002094 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2095 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002096 if (!NewVar || !NewLB)
2097 return true;
2098 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002099 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002100 LB = NewLB;
2101 return false;
2102}
2103
2104bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2105 const SourceRange &SR,
2106 const SourceLocation &SL) {
2107 // State consistency checking to ensure correct usage.
2108 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2109 !TestIsLessOp && !TestIsStrictOp);
2110 if (!NewUB)
2111 return true;
2112 UB = NewUB;
2113 TestIsLessOp = LessOp;
2114 TestIsStrictOp = StrictOp;
2115 ConditionSrcRange = SR;
2116 ConditionLoc = SL;
2117 return false;
2118}
2119
2120bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2121 // State consistency checking to ensure correct usage.
2122 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2123 if (!NewStep)
2124 return true;
2125 if (!NewStep->isValueDependent()) {
2126 // Check that the step is integer expression.
2127 SourceLocation StepLoc = NewStep->getLocStart();
2128 ExprResult Val =
2129 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2130 if (Val.isInvalid())
2131 return true;
2132 NewStep = Val.get();
2133
2134 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2135 // If test-expr is of form var relational-op b and relational-op is < or
2136 // <= then incr-expr must cause var to increase on each iteration of the
2137 // loop. If test-expr is of form var relational-op b and relational-op is
2138 // > or >= then incr-expr must cause var to decrease on each iteration of
2139 // the loop.
2140 // If test-expr is of form b relational-op var and relational-op is < or
2141 // <= then incr-expr must cause var to decrease on each iteration of the
2142 // loop. If test-expr is of form b relational-op var and relational-op is
2143 // > or >= then incr-expr must cause var to increase on each iteration of
2144 // the loop.
2145 llvm::APSInt Result;
2146 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2147 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2148 bool IsConstNeg =
2149 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002150 bool IsConstPos =
2151 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002152 bool IsConstZero = IsConstant && !Result.getBoolValue();
2153 if (UB && (IsConstZero ||
2154 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002155 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002156 SemaRef.Diag(NewStep->getExprLoc(),
2157 diag::err_omp_loop_incr_not_compatible)
2158 << Var << TestIsLessOp << NewStep->getSourceRange();
2159 SemaRef.Diag(ConditionLoc,
2160 diag::note_omp_loop_cond_requres_compatible_incr)
2161 << TestIsLessOp << ConditionSrcRange;
2162 return true;
2163 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002164 if (TestIsLessOp == Subtract) {
2165 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2166 NewStep).get();
2167 Subtract = !Subtract;
2168 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002169 }
2170
2171 Step = NewStep;
2172 SubtractStep = Subtract;
2173 return false;
2174}
2175
Alexey Bataev9c821032015-04-30 04:23:23 +00002176bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002177 // Check init-expr for canonical loop form and save loop counter
2178 // variable - #Var and its initialization value - #LB.
2179 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2180 // var = lb
2181 // integer-type var = lb
2182 // random-access-iterator-type var = lb
2183 // pointer-type var = lb
2184 //
2185 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002186 if (EmitDiags) {
2187 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2188 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002189 return true;
2190 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002191 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002192 if (Expr *E = dyn_cast<Expr>(S))
2193 S = E->IgnoreParens();
2194 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2195 if (BO->getOpcode() == BO_Assign)
2196 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002197 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002198 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002199 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2200 if (DS->isSingleDecl()) {
2201 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2202 if (Var->hasInit()) {
2203 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002204 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002205 SemaRef.Diag(S->getLocStart(),
2206 diag::ext_omp_loop_not_canonical_init)
2207 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002208 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002209 }
2210 }
2211 }
2212 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2213 if (CE->getOperator() == OO_Equal)
2214 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002215 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2216 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002217
Alexey Bataev9c821032015-04-30 04:23:23 +00002218 if (EmitDiags) {
2219 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2220 << S->getSourceRange();
2221 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002222 return true;
2223}
2224
Alexey Bataev23b69422014-06-18 07:08:49 +00002225/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002226/// variable (which may be the loop variable) if possible.
2227static const VarDecl *GetInitVarDecl(const Expr *E) {
2228 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002229 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002230 E = E->IgnoreParenImpCasts();
2231 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2232 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2233 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2234 CE->getArg(0) != nullptr)
2235 E = CE->getArg(0)->IgnoreParenImpCasts();
2236 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2237 if (!DRE)
2238 return nullptr;
2239 return dyn_cast<VarDecl>(DRE->getDecl());
2240}
2241
2242bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2243 // Check test-expr for canonical form, save upper-bound UB, flags for
2244 // less/greater and for strict/non-strict comparison.
2245 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2246 // var relational-op b
2247 // b relational-op var
2248 //
2249 if (!S) {
2250 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2251 return true;
2252 }
2253 S = S->IgnoreParenImpCasts();
2254 SourceLocation CondLoc = S->getLocStart();
2255 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2256 if (BO->isRelationalOp()) {
2257 if (GetInitVarDecl(BO->getLHS()) == Var)
2258 return SetUB(BO->getRHS(),
2259 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2260 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2261 BO->getSourceRange(), BO->getOperatorLoc());
2262 if (GetInitVarDecl(BO->getRHS()) == Var)
2263 return SetUB(BO->getLHS(),
2264 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2265 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2266 BO->getSourceRange(), BO->getOperatorLoc());
2267 }
2268 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2269 if (CE->getNumArgs() == 2) {
2270 auto Op = CE->getOperator();
2271 switch (Op) {
2272 case OO_Greater:
2273 case OO_GreaterEqual:
2274 case OO_Less:
2275 case OO_LessEqual:
2276 if (GetInitVarDecl(CE->getArg(0)) == Var)
2277 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2278 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2279 CE->getOperatorLoc());
2280 if (GetInitVarDecl(CE->getArg(1)) == Var)
2281 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2282 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2283 CE->getOperatorLoc());
2284 break;
2285 default:
2286 break;
2287 }
2288 }
2289 }
2290 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2291 << S->getSourceRange() << Var;
2292 return true;
2293}
2294
2295bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2296 // RHS of canonical loop form increment can be:
2297 // var + incr
2298 // incr + var
2299 // var - incr
2300 //
2301 RHS = RHS->IgnoreParenImpCasts();
2302 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2303 if (BO->isAdditiveOp()) {
2304 bool IsAdd = BO->getOpcode() == BO_Add;
2305 if (GetInitVarDecl(BO->getLHS()) == Var)
2306 return SetStep(BO->getRHS(), !IsAdd);
2307 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2308 return SetStep(BO->getLHS(), false);
2309 }
2310 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2311 bool IsAdd = CE->getOperator() == OO_Plus;
2312 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2313 if (GetInitVarDecl(CE->getArg(0)) == Var)
2314 return SetStep(CE->getArg(1), !IsAdd);
2315 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2316 return SetStep(CE->getArg(0), false);
2317 }
2318 }
2319 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2320 << RHS->getSourceRange() << Var;
2321 return true;
2322}
2323
2324bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2325 // Check incr-expr for canonical loop form and return true if it
2326 // does not conform.
2327 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2328 // ++var
2329 // var++
2330 // --var
2331 // var--
2332 // var += incr
2333 // var -= incr
2334 // var = var + incr
2335 // var = incr + var
2336 // var = var - incr
2337 //
2338 if (!S) {
2339 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2340 return true;
2341 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002342 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002343 S = S->IgnoreParens();
2344 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2345 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2346 return SetStep(
2347 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2348 (UO->isDecrementOp() ? -1 : 1)).get(),
2349 false);
2350 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2351 switch (BO->getOpcode()) {
2352 case BO_AddAssign:
2353 case BO_SubAssign:
2354 if (GetInitVarDecl(BO->getLHS()) == Var)
2355 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2356 break;
2357 case BO_Assign:
2358 if (GetInitVarDecl(BO->getLHS()) == Var)
2359 return CheckIncRHS(BO->getRHS());
2360 break;
2361 default:
2362 break;
2363 }
2364 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2365 switch (CE->getOperator()) {
2366 case OO_PlusPlus:
2367 case OO_MinusMinus:
2368 if (GetInitVarDecl(CE->getArg(0)) == Var)
2369 return SetStep(
2370 SemaRef.ActOnIntegerConstant(
2371 CE->getLocStart(),
2372 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2373 false);
2374 break;
2375 case OO_PlusEqual:
2376 case OO_MinusEqual:
2377 if (GetInitVarDecl(CE->getArg(0)) == Var)
2378 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2379 break;
2380 case OO_Equal:
2381 if (GetInitVarDecl(CE->getArg(0)) == Var)
2382 return CheckIncRHS(CE->getArg(1));
2383 break;
2384 default:
2385 break;
2386 }
2387 }
2388 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2389 << S->getSourceRange() << Var;
2390 return true;
2391}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002392
2393/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002394Expr *
2395OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2396 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002397 ExprResult Diff;
2398 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2399 SemaRef.getLangOpts().CPlusPlus) {
2400 // Upper - Lower
2401 Expr *Upper = TestIsLessOp ? UB : LB;
2402 Expr *Lower = TestIsLessOp ? LB : UB;
2403
2404 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2405
2406 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2407 // BuildBinOp already emitted error, this one is to point user to upper
2408 // and lower bound, and to tell what is passed to 'operator-'.
2409 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2410 << Upper->getSourceRange() << Lower->getSourceRange();
2411 return nullptr;
2412 }
2413 }
2414
2415 if (!Diff.isUsable())
2416 return nullptr;
2417
2418 // Upper - Lower [- 1]
2419 if (TestIsStrictOp)
2420 Diff = SemaRef.BuildBinOp(
2421 S, DefaultLoc, BO_Sub, Diff.get(),
2422 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2423 if (!Diff.isUsable())
2424 return nullptr;
2425
2426 // Upper - Lower [- 1] + Step
2427 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2428 Step->IgnoreImplicit());
2429 if (!Diff.isUsable())
2430 return nullptr;
2431
2432 // Parentheses (for dumping/debugging purposes only).
2433 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2434 if (!Diff.isUsable())
2435 return nullptr;
2436
2437 // (Upper - Lower [- 1] + Step) / Step
2438 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2439 Step->IgnoreImplicit());
2440 if (!Diff.isUsable())
2441 return nullptr;
2442
Alexander Musman174b3ca2014-10-06 11:16:29 +00002443 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2444 if (LimitedType) {
2445 auto &C = SemaRef.Context;
2446 QualType Type = Diff.get()->getType();
2447 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2448 if (NewSize != C.getTypeSize(Type)) {
2449 if (NewSize < C.getTypeSize(Type)) {
2450 assert(NewSize == 64 && "incorrect loop var size");
2451 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2452 << InitSrcRange << ConditionSrcRange;
2453 }
2454 QualType NewType = C.getIntTypeForBitwidth(
2455 NewSize, Type->hasSignedIntegerRepresentation());
2456 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2457 Sema::AA_Converting, true);
2458 if (!Diff.isUsable())
2459 return nullptr;
2460 }
2461 }
2462
Alexander Musmana5f070a2014-10-01 06:03:56 +00002463 return Diff.get();
2464}
2465
Alexey Bataev62dbb972015-04-22 11:59:37 +00002466Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2467 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2468 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2469 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2470 auto CondExpr = SemaRef.BuildBinOp(
2471 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2472 : (TestIsStrictOp ? BO_GT : BO_GE),
2473 LB, UB);
2474 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2475 // Otherwise use original loop conditon and evaluate it in runtime.
2476 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2477}
2478
Alexander Musmana5f070a2014-10-01 06:03:56 +00002479/// \brief Build reference expression to the counter be used for codegen.
2480Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002481 return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002482}
2483
2484/// \brief Build initization of the counter be used for codegen.
2485Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2486
2487/// \brief Build step of the counter be used for codegen.
2488Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2489
2490/// \brief Iteration space of a single for loop.
2491struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002492 /// \brief Condition of the loop.
2493 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002494 /// \brief This expression calculates the number of iterations in the loop.
2495 /// It is always possible to calculate it before starting the loop.
2496 Expr *NumIterations;
2497 /// \brief The loop counter variable.
2498 Expr *CounterVar;
2499 /// \brief This is initializer for the initial value of #CounterVar.
2500 Expr *CounterInit;
2501 /// \brief This is step for the #CounterVar used to generate its update:
2502 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2503 Expr *CounterStep;
2504 /// \brief Should step be subtracted?
2505 bool Subtract;
2506 /// \brief Source range of the loop init.
2507 SourceRange InitSrcRange;
2508 /// \brief Source range of the loop condition.
2509 SourceRange CondSrcRange;
2510 /// \brief Source range of the loop increment.
2511 SourceRange IncSrcRange;
2512};
2513
Alexey Bataev23b69422014-06-18 07:08:49 +00002514} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002515
Alexey Bataev9c821032015-04-30 04:23:23 +00002516void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2517 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2518 assert(Init && "Expected loop in canonical form.");
2519 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2520 if (CollapseIteration > 0 &&
2521 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2522 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2523 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2524 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2525 }
2526 DSAStack->setCollapseNumber(CollapseIteration - 1);
2527 }
2528}
2529
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002530/// \brief Called on a for stmt to check and extract its iteration space
2531/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002532static bool CheckOpenMPIterationSpace(
2533 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2534 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2535 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002536 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2537 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002538 // OpenMP [2.6, Canonical Loop Form]
2539 // for (init-expr; test-expr; incr-expr) structured-block
2540 auto For = dyn_cast_or_null<ForStmt>(S);
2541 if (!For) {
2542 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002543 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2544 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2545 << CurrentNestedLoopCount;
2546 if (NestedLoopCount > 1)
2547 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2548 diag::note_omp_collapse_expr)
2549 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002550 return true;
2551 }
2552 assert(For->getBody());
2553
2554 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2555
2556 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002557 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002558 if (ISC.CheckInit(Init)) {
2559 return true;
2560 }
2561
2562 bool HasErrors = false;
2563
2564 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002565 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002566
2567 // OpenMP [2.6, Canonical Loop Form]
2568 // Var is one of the following:
2569 // A variable of signed or unsigned integer type.
2570 // For C++, a variable of a random access iterator type.
2571 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002572 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002573 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2574 !VarType->isPointerType() &&
2575 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2576 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2577 << SemaRef.getLangOpts().CPlusPlus;
2578 HasErrors = true;
2579 }
2580
Alexey Bataev4acb8592014-07-07 13:01:15 +00002581 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2582 // Construct
2583 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2584 // parallel for construct is (are) private.
2585 // The loop iteration variable in the associated for-loop of a simd construct
2586 // with just one associated for-loop is linear with a constant-linear-step
2587 // that is the increment of the associated for-loop.
2588 // Exclude loop var from the list of variables with implicitly defined data
2589 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002590 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002591
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002592 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2593 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002594 // The loop iteration variable in the associated for-loop of a simd construct
2595 // with just one associated for-loop may be listed in a linear clause with a
2596 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002597 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2598 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002599 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002600 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2601 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2602 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002603 auto PredeterminedCKind =
2604 isOpenMPSimdDirective(DKind)
2605 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2606 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002607 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002608 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002609 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2610 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00002611 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2612 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2613 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002614 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002615 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2616 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00002617 if (DVar.RefExpr == nullptr)
2618 DVar.CKind = PredeterminedCKind;
2619 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002620 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002621 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002622 // Make the loop iteration variable private (for worksharing constructs),
2623 // linear (for simd directives with the only one associated loop) or
2624 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002625 if (DVar.CKind == OMPC_unknown)
2626 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2627 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00002628 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002629 }
2630
Alexey Bataev7ff55242014-06-19 09:13:45 +00002631 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002632
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002633 // Check test-expr.
2634 HasErrors |= ISC.CheckCond(For->getCond());
2635
2636 // Check incr-expr.
2637 HasErrors |= ISC.CheckInc(For->getInc());
2638
Alexander Musmana5f070a2014-10-01 06:03:56 +00002639 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002640 return HasErrors;
2641
Alexander Musmana5f070a2014-10-01 06:03:56 +00002642 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002643 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00002644 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2645 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002646 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2647 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2648 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2649 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2650 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2651 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2652 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2653
Alexey Bataev62dbb972015-04-22 11:59:37 +00002654 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2655 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002656 ResultIterSpace.CounterVar == nullptr ||
2657 ResultIterSpace.CounterInit == nullptr ||
2658 ResultIterSpace.CounterStep == nullptr);
2659
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002660 return HasErrors;
2661}
2662
Alexander Musmana5f070a2014-10-01 06:03:56 +00002663/// \brief Build 'VarRef = Start + Iter * Step'.
2664static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2665 SourceLocation Loc, ExprResult VarRef,
2666 ExprResult Start, ExprResult Iter,
2667 ExprResult Step, bool Subtract) {
2668 // Add parentheses (for debugging purposes only).
2669 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2670 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2671 !Step.isUsable())
2672 return ExprError();
2673
2674 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2675 Step.get()->IgnoreImplicit());
2676 if (!Update.isUsable())
2677 return ExprError();
2678
2679 // Build 'VarRef = Start + Iter * Step'.
2680 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2681 Start.get()->IgnoreImplicit(), Update.get());
2682 if (!Update.isUsable())
2683 return ExprError();
2684
2685 Update = SemaRef.PerformImplicitConversion(
2686 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2687 if (!Update.isUsable())
2688 return ExprError();
2689
2690 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2691 return Update;
2692}
2693
2694/// \brief Convert integer expression \a E to make it have at least \a Bits
2695/// bits.
2696static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2697 Sema &SemaRef) {
2698 if (E == nullptr)
2699 return ExprError();
2700 auto &C = SemaRef.Context;
2701 QualType OldType = E->getType();
2702 unsigned HasBits = C.getTypeSize(OldType);
2703 if (HasBits >= Bits)
2704 return ExprResult(E);
2705 // OK to convert to signed, because new type has more bits than old.
2706 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2707 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2708 true);
2709}
2710
2711/// \brief Check if the given expression \a E is a constant integer that fits
2712/// into \a Bits bits.
2713static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2714 if (E == nullptr)
2715 return false;
2716 llvm::APSInt Result;
2717 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2718 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2719 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002720}
2721
2722/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002723/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2724/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002725static unsigned
2726CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2727 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002728 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002729 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002730 unsigned NestedLoopCount = 1;
2731 if (NestedLoopCountExpr) {
2732 // Found 'collapse' clause - calculate collapse number.
2733 llvm::APSInt Result;
2734 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2735 NestedLoopCount = Result.getLimitedValue();
2736 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002737 // This is helper routine for loop directives (e.g., 'for', 'simd',
2738 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002739 SmallVector<LoopIterationSpace, 4> IterSpaces;
2740 IterSpaces.resize(NestedLoopCount);
2741 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002742 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002743 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002744 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002745 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002746 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002747 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002748 // OpenMP [2.8.1, simd construct, Restrictions]
2749 // All loops associated with the construct must be perfectly nested; that
2750 // is, there must be no intervening code nor any OpenMP directive between
2751 // any two loops.
2752 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002753 }
2754
Alexander Musmana5f070a2014-10-01 06:03:56 +00002755 Built.clear(/* size */ NestedLoopCount);
2756
2757 if (SemaRef.CurContext->isDependentContext())
2758 return NestedLoopCount;
2759
2760 // An example of what is generated for the following code:
2761 //
2762 // #pragma omp simd collapse(2)
2763 // for (i = 0; i < NI; ++i)
2764 // for (j = J0; j < NJ; j+=2) {
2765 // <loop body>
2766 // }
2767 //
2768 // We generate the code below.
2769 // Note: the loop body may be outlined in CodeGen.
2770 // Note: some counters may be C++ classes, operator- is used to find number of
2771 // iterations and operator+= to calculate counter value.
2772 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2773 // or i64 is currently supported).
2774 //
2775 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2776 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2777 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2778 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2779 // // similar updates for vars in clauses (e.g. 'linear')
2780 // <loop body (using local i and j)>
2781 // }
2782 // i = NI; // assign final values of counters
2783 // j = NJ;
2784 //
2785
2786 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2787 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002788 // Precondition tests if there is at least one iteration (all conditions are
2789 // true).
2790 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002791 auto N0 = IterSpaces[0].NumIterations;
2792 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2793 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2794
2795 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2796 return NestedLoopCount;
2797
2798 auto &C = SemaRef.Context;
2799 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2800
2801 Scope *CurScope = DSA.getCurScope();
2802 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002803 if (PreCond.isUsable()) {
2804 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2805 PreCond.get(), IterSpaces[Cnt].PreCond);
2806 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002807 auto N = IterSpaces[Cnt].NumIterations;
2808 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2809 if (LastIteration32.isUsable())
2810 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2811 LastIteration32.get(), N);
2812 if (LastIteration64.isUsable())
2813 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2814 LastIteration64.get(), N);
2815 }
2816
2817 // Choose either the 32-bit or 64-bit version.
2818 ExprResult LastIteration = LastIteration64;
2819 if (LastIteration32.isUsable() &&
2820 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2821 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2822 FitsInto(
2823 32 /* Bits */,
2824 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2825 LastIteration64.get(), SemaRef)))
2826 LastIteration = LastIteration32;
2827
2828 if (!LastIteration.isUsable())
2829 return 0;
2830
2831 // Save the number of iterations.
2832 ExprResult NumIterations = LastIteration;
2833 {
2834 LastIteration = SemaRef.BuildBinOp(
2835 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2836 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2837 if (!LastIteration.isUsable())
2838 return 0;
2839 }
2840
2841 // Calculate the last iteration number beforehand instead of doing this on
2842 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2843 llvm::APSInt Result;
2844 bool IsConstant =
2845 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2846 ExprResult CalcLastIteration;
2847 if (!IsConstant) {
2848 SourceLocation SaveLoc;
2849 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00002850 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002851 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00002852 ExprResult SaveRef = buildDeclRefExpr(
2853 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002854 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2855 SaveRef.get(), LastIteration.get());
2856 LastIteration = SaveRef;
2857
2858 // Prepare SaveRef + 1.
2859 NumIterations = SemaRef.BuildBinOp(
2860 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2861 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2862 if (!NumIterations.isUsable())
2863 return 0;
2864 }
2865
2866 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2867
Alexander Musmanc6388682014-12-15 07:07:06 +00002868 QualType VType = LastIteration.get()->getType();
2869 // Build variables passed into runtime, nesessary for worksharing directives.
2870 ExprResult LB, UB, IL, ST, EUB;
2871 if (isOpenMPWorksharingDirective(DKind)) {
2872 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002873 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2874 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002875 SemaRef.AddInitializerToDecl(
2876 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2877 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2878
2879 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00002880 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2881 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002882 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2883 /*DirectInit*/ false,
2884 /*TypeMayContainAuto*/ false);
2885
2886 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2887 // This will be used to implement clause 'lastprivate'.
2888 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002889 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2890 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002891 SemaRef.AddInitializerToDecl(
2892 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2893 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2894
2895 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00002896 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2897 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002898 SemaRef.AddInitializerToDecl(
2899 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2900 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2901
2902 // Build expression: UB = min(UB, LastIteration)
2903 // It is nesessary for CodeGen of directives with static scheduling.
2904 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2905 UB.get(), LastIteration.get());
2906 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2907 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2908 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2909 CondOp.get());
2910 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2911 }
2912
2913 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002914 ExprResult IV;
2915 ExprResult Init;
2916 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00002917 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2918 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00002919 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2920 ? LB.get()
2921 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2922 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2923 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002924 }
2925
Alexander Musmanc6388682014-12-15 07:07:06 +00002926 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002927 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002928 ExprResult Cond =
2929 isOpenMPWorksharingDirective(DKind)
2930 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2931 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2932 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002933 // Loop condition with 1 iteration separated (IV < LastIteration)
2934 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2935 IV.get(), LastIteration.get());
2936
2937 // Loop increment (IV = IV + 1)
2938 SourceLocation IncLoc;
2939 ExprResult Inc =
2940 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2941 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2942 if (!Inc.isUsable())
2943 return 0;
2944 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002945 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2946 if (!Inc.isUsable())
2947 return 0;
2948
2949 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2950 // Used for directives with static scheduling.
2951 ExprResult NextLB, NextUB;
2952 if (isOpenMPWorksharingDirective(DKind)) {
2953 // LB + ST
2954 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2955 if (!NextLB.isUsable())
2956 return 0;
2957 // LB = LB + ST
2958 NextLB =
2959 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2960 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2961 if (!NextLB.isUsable())
2962 return 0;
2963 // UB + ST
2964 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2965 if (!NextUB.isUsable())
2966 return 0;
2967 // UB = UB + ST
2968 NextUB =
2969 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2970 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2971 if (!NextUB.isUsable())
2972 return 0;
2973 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002974
2975 // Build updates and final values of the loop counters.
2976 bool HasErrors = false;
2977 Built.Counters.resize(NestedLoopCount);
2978 Built.Updates.resize(NestedLoopCount);
2979 Built.Finals.resize(NestedLoopCount);
2980 {
2981 ExprResult Div;
2982 // Go from inner nested loop to outer.
2983 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2984 LoopIterationSpace &IS = IterSpaces[Cnt];
2985 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2986 // Build: Iter = (IV / Div) % IS.NumIters
2987 // where Div is product of previous iterations' IS.NumIters.
2988 ExprResult Iter;
2989 if (Div.isUsable()) {
2990 Iter =
2991 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2992 } else {
2993 Iter = IV;
2994 assert((Cnt == (int)NestedLoopCount - 1) &&
2995 "unusable div expected on first iteration only");
2996 }
2997
2998 if (Cnt != 0 && Iter.isUsable())
2999 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3000 IS.NumIterations);
3001 if (!Iter.isUsable()) {
3002 HasErrors = true;
3003 break;
3004 }
3005
Alexey Bataev39f915b82015-05-08 10:41:21 +00003006 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3007 auto *CounterVar = buildDeclRefExpr(
3008 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3009 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3010 /*RefersToCapture=*/true);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003011 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003012 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003013 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3014 if (!Update.isUsable()) {
3015 HasErrors = true;
3016 break;
3017 }
3018
3019 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3020 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003021 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003022 IS.NumIterations, IS.CounterStep, IS.Subtract);
3023 if (!Final.isUsable()) {
3024 HasErrors = true;
3025 break;
3026 }
3027
3028 // Build Div for the next iteration: Div <- Div * IS.NumIters
3029 if (Cnt != 0) {
3030 if (Div.isUnset())
3031 Div = IS.NumIterations;
3032 else
3033 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3034 IS.NumIterations);
3035
3036 // Add parentheses (for debugging purposes only).
3037 if (Div.isUsable())
3038 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3039 if (!Div.isUsable()) {
3040 HasErrors = true;
3041 break;
3042 }
3043 }
3044 if (!Update.isUsable() || !Final.isUsable()) {
3045 HasErrors = true;
3046 break;
3047 }
3048 // Save results
3049 Built.Counters[Cnt] = IS.CounterVar;
3050 Built.Updates[Cnt] = Update.get();
3051 Built.Finals[Cnt] = Final.get();
3052 }
3053 }
3054
3055 if (HasErrors)
3056 return 0;
3057
3058 // Save results
3059 Built.IterationVarRef = IV.get();
3060 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003061 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003062 Built.CalcLastIteration = CalcLastIteration.get();
3063 Built.PreCond = PreCond.get();
3064 Built.Cond = Cond.get();
3065 Built.SeparatedCond = SeparatedCond.get();
3066 Built.Init = Init.get();
3067 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003068 Built.LB = LB.get();
3069 Built.UB = UB.get();
3070 Built.IL = IL.get();
3071 Built.ST = ST.get();
3072 Built.EUB = EUB.get();
3073 Built.NLB = NextLB.get();
3074 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003075
Alexey Bataevabfc0692014-06-25 06:52:00 +00003076 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003077}
3078
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003079static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevc925aa32015-04-27 08:00:32 +00003080 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003081 return C->getClauseKind() == OMPC_collapse;
3082 };
3083 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
Alexey Bataevc925aa32015-04-27 08:00:32 +00003084 Clauses, std::move(CollapseFilter));
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003085 if (I)
3086 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3087 return nullptr;
3088}
3089
Alexey Bataev4acb8592014-07-07 13:01:15 +00003090StmtResult Sema::ActOnOpenMPSimdDirective(
3091 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3092 SourceLocation EndLoc,
3093 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003094 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003095 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003096 unsigned NestedLoopCount =
3097 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003098 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003099 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003100 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003101
Alexander Musmana5f070a2014-10-01 06:03:56 +00003102 assert((CurContext->isDependentContext() || B.builtAll()) &&
3103 "omp simd loop exprs were not built");
3104
Alexander Musman3276a272015-03-21 10:12:56 +00003105 if (!CurContext->isDependentContext()) {
3106 // Finalize the clauses that need pre-built expressions for CodeGen.
3107 for (auto C : Clauses) {
3108 if (auto LC = dyn_cast<OMPLinearClause>(C))
3109 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3110 B.NumIterations, *this, CurScope))
3111 return StmtError();
3112 }
3113 }
3114
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003115 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003116 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3117 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003118}
3119
Alexey Bataev4acb8592014-07-07 13:01:15 +00003120StmtResult Sema::ActOnOpenMPForDirective(
3121 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3122 SourceLocation EndLoc,
3123 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003124 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003125 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003126 unsigned NestedLoopCount =
3127 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003128 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003129 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003130 return StmtError();
3131
Alexander Musmana5f070a2014-10-01 06:03:56 +00003132 assert((CurContext->isDependentContext() || B.builtAll()) &&
3133 "omp for loop exprs were not built");
3134
Alexey Bataevf29276e2014-06-18 04:14:57 +00003135 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003136 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3137 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003138}
3139
Alexander Musmanf82886e2014-09-18 05:12:34 +00003140StmtResult Sema::ActOnOpenMPForSimdDirective(
3141 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3142 SourceLocation EndLoc,
3143 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003144 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003145 // In presence of clause 'collapse', it will define the nested loops number.
3146 unsigned NestedLoopCount =
3147 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003148 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003149 if (NestedLoopCount == 0)
3150 return StmtError();
3151
Alexander Musmanc6388682014-12-15 07:07:06 +00003152 assert((CurContext->isDependentContext() || B.builtAll()) &&
3153 "omp for simd loop exprs were not built");
3154
Alexander Musmanf82886e2014-09-18 05:12:34 +00003155 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003156 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3157 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003158}
3159
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003160StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3161 Stmt *AStmt,
3162 SourceLocation StartLoc,
3163 SourceLocation EndLoc) {
3164 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3165 auto BaseStmt = AStmt;
3166 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3167 BaseStmt = CS->getCapturedStmt();
3168 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3169 auto S = C->children();
3170 if (!S)
3171 return StmtError();
3172 // All associated statements must be '#pragma omp section' except for
3173 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003174 for (++S; S; ++S) {
3175 auto SectionStmt = *S;
3176 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3177 if (SectionStmt)
3178 Diag(SectionStmt->getLocStart(),
3179 diag::err_omp_sections_substmt_not_section);
3180 return StmtError();
3181 }
3182 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003183 } else {
3184 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3185 return StmtError();
3186 }
3187
3188 getCurFunction()->setHasBranchProtectedScope();
3189
3190 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3191 AStmt);
3192}
3193
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003194StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3195 SourceLocation StartLoc,
3196 SourceLocation EndLoc) {
3197 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3198
3199 getCurFunction()->setHasBranchProtectedScope();
3200
3201 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3202}
3203
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003204StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3205 Stmt *AStmt,
3206 SourceLocation StartLoc,
3207 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003208 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3209
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003210 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003211
Alexey Bataev3255bf32015-01-19 05:20:46 +00003212 // OpenMP [2.7.3, single Construct, Restrictions]
3213 // The copyprivate clause must not be used with the nowait clause.
3214 OMPClause *Nowait = nullptr;
3215 OMPClause *Copyprivate = nullptr;
3216 for (auto *Clause : Clauses) {
3217 if (Clause->getClauseKind() == OMPC_nowait)
3218 Nowait = Clause;
3219 else if (Clause->getClauseKind() == OMPC_copyprivate)
3220 Copyprivate = Clause;
3221 if (Copyprivate && Nowait) {
3222 Diag(Copyprivate->getLocStart(),
3223 diag::err_omp_single_copyprivate_with_nowait);
3224 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3225 return StmtError();
3226 }
3227 }
3228
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003229 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3230}
3231
Alexander Musman80c22892014-07-17 08:54:58 +00003232StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3233 SourceLocation StartLoc,
3234 SourceLocation EndLoc) {
3235 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3236
3237 getCurFunction()->setHasBranchProtectedScope();
3238
3239 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3240}
3241
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003242StmtResult
3243Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3244 Stmt *AStmt, SourceLocation StartLoc,
3245 SourceLocation EndLoc) {
3246 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3247
3248 getCurFunction()->setHasBranchProtectedScope();
3249
3250 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3251 AStmt);
3252}
3253
Alexey Bataev4acb8592014-07-07 13:01:15 +00003254StmtResult Sema::ActOnOpenMPParallelForDirective(
3255 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3256 SourceLocation EndLoc,
3257 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3258 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3259 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3260 // 1.2.2 OpenMP Language Terminology
3261 // Structured block - An executable statement with a single entry at the
3262 // top and a single exit at the bottom.
3263 // The point of exit cannot be a branch out of the structured block.
3264 // longjmp() and throw() must not violate the entry/exit criteria.
3265 CS->getCapturedDecl()->setNothrow();
3266
Alexander Musmanc6388682014-12-15 07:07:06 +00003267 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003268 // In presence of clause 'collapse', it will define the nested loops number.
3269 unsigned NestedLoopCount =
3270 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003271 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003272 if (NestedLoopCount == 0)
3273 return StmtError();
3274
Alexander Musmana5f070a2014-10-01 06:03:56 +00003275 assert((CurContext->isDependentContext() || B.builtAll()) &&
3276 "omp parallel for loop exprs were not built");
3277
Alexey Bataev4acb8592014-07-07 13:01:15 +00003278 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003279 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3280 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003281}
3282
Alexander Musmane4e893b2014-09-23 09:33:00 +00003283StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3284 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3285 SourceLocation EndLoc,
3286 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3287 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3288 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3289 // 1.2.2 OpenMP Language Terminology
3290 // Structured block - An executable statement with a single entry at the
3291 // top and a single exit at the bottom.
3292 // The point of exit cannot be a branch out of the structured block.
3293 // longjmp() and throw() must not violate the entry/exit criteria.
3294 CS->getCapturedDecl()->setNothrow();
3295
Alexander Musmanc6388682014-12-15 07:07:06 +00003296 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003297 // In presence of clause 'collapse', it will define the nested loops number.
3298 unsigned NestedLoopCount =
3299 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003300 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003301 if (NestedLoopCount == 0)
3302 return StmtError();
3303
3304 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003305 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003306 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003307}
3308
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003309StmtResult
3310Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3311 Stmt *AStmt, SourceLocation StartLoc,
3312 SourceLocation EndLoc) {
3313 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3314 auto BaseStmt = AStmt;
3315 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3316 BaseStmt = CS->getCapturedStmt();
3317 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3318 auto S = C->children();
3319 if (!S)
3320 return StmtError();
3321 // All associated statements must be '#pragma omp section' except for
3322 // the first one.
3323 for (++S; S; ++S) {
3324 auto SectionStmt = *S;
3325 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3326 if (SectionStmt)
3327 Diag(SectionStmt->getLocStart(),
3328 diag::err_omp_parallel_sections_substmt_not_section);
3329 return StmtError();
3330 }
3331 }
3332 } else {
3333 Diag(AStmt->getLocStart(),
3334 diag::err_omp_parallel_sections_not_compound_stmt);
3335 return StmtError();
3336 }
3337
3338 getCurFunction()->setHasBranchProtectedScope();
3339
3340 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3341 Clauses, AStmt);
3342}
3343
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003344StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3345 Stmt *AStmt, SourceLocation StartLoc,
3346 SourceLocation EndLoc) {
3347 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3348 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3349 // 1.2.2 OpenMP Language Terminology
3350 // Structured block - An executable statement with a single entry at the
3351 // top and a single exit at the bottom.
3352 // The point of exit cannot be a branch out of the structured block.
3353 // longjmp() and throw() must not violate the entry/exit criteria.
3354 CS->getCapturedDecl()->setNothrow();
3355
3356 getCurFunction()->setHasBranchProtectedScope();
3357
3358 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3359}
3360
Alexey Bataev68446b72014-07-18 07:47:19 +00003361StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3362 SourceLocation EndLoc) {
3363 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3364}
3365
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003366StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3367 SourceLocation EndLoc) {
3368 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3369}
3370
Alexey Bataev2df347a2014-07-18 10:17:07 +00003371StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3372 SourceLocation EndLoc) {
3373 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3374}
3375
Alexey Bataev6125da92014-07-21 11:26:11 +00003376StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3377 SourceLocation StartLoc,
3378 SourceLocation EndLoc) {
3379 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3380 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3381}
3382
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003383StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3384 SourceLocation StartLoc,
3385 SourceLocation EndLoc) {
3386 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3387
3388 getCurFunction()->setHasBranchProtectedScope();
3389
3390 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3391}
3392
Alexey Bataev1d160b12015-03-13 12:27:31 +00003393namespace {
3394/// \brief Helper class for checking expression in 'omp atomic [update]'
3395/// construct.
3396class OpenMPAtomicUpdateChecker {
3397 /// \brief Error results for atomic update expressions.
3398 enum ExprAnalysisErrorCode {
3399 /// \brief A statement is not an expression statement.
3400 NotAnExpression,
3401 /// \brief Expression is not builtin binary or unary operation.
3402 NotABinaryOrUnaryExpression,
3403 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3404 NotAnUnaryIncDecExpression,
3405 /// \brief An expression is not of scalar type.
3406 NotAScalarType,
3407 /// \brief A binary operation is not an assignment operation.
3408 NotAnAssignmentOp,
3409 /// \brief RHS part of the binary operation is not a binary expression.
3410 NotABinaryExpression,
3411 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3412 /// expression.
3413 NotABinaryOperator,
3414 /// \brief RHS binary operation does not have reference to the updated LHS
3415 /// part.
3416 NotAnUpdateExpression,
3417 /// \brief No errors is found.
3418 NoError
3419 };
3420 /// \brief Reference to Sema.
3421 Sema &SemaRef;
3422 /// \brief A location for note diagnostics (when error is found).
3423 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003424 /// \brief 'x' lvalue part of the source atomic expression.
3425 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003426 /// \brief 'expr' rvalue part of the source atomic expression.
3427 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003428 /// \brief Helper expression of the form
3429 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3430 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3431 Expr *UpdateExpr;
3432 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3433 /// important for non-associative operations.
3434 bool IsXLHSInRHSPart;
3435 BinaryOperatorKind Op;
3436 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003437 /// \brief true if the source expression is a postfix unary operation, false
3438 /// if it is a prefix unary operation.
3439 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003440
3441public:
3442 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003443 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003444 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003445 /// \brief Check specified statement that it is suitable for 'atomic update'
3446 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003447 /// expression. If DiagId and NoteId == 0, then only check is performed
3448 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003449 /// \param DiagId Diagnostic which should be emitted if error is found.
3450 /// \param NoteId Diagnostic note for the main error message.
3451 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003452 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003453 /// \brief Return the 'x' lvalue part of the source atomic expression.
3454 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003455 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3456 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003457 /// \brief Return the update expression used in calculation of the updated
3458 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3459 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3460 Expr *getUpdateExpr() const { return UpdateExpr; }
3461 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3462 /// false otherwise.
3463 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3464
Alexey Bataevb78ca832015-04-01 03:33:17 +00003465 /// \brief true if the source expression is a postfix unary operation, false
3466 /// if it is a prefix unary operation.
3467 bool isPostfixUpdate() const { return IsPostfixUpdate; }
3468
Alexey Bataev1d160b12015-03-13 12:27:31 +00003469private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003470 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3471 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003472};
3473} // namespace
3474
3475bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3476 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3477 ExprAnalysisErrorCode ErrorFound = NoError;
3478 SourceLocation ErrorLoc, NoteLoc;
3479 SourceRange ErrorRange, NoteRange;
3480 // Allowed constructs are:
3481 // x = x binop expr;
3482 // x = expr binop x;
3483 if (AtomicBinOp->getOpcode() == BO_Assign) {
3484 X = AtomicBinOp->getLHS();
3485 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3486 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3487 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3488 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3489 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003490 Op = AtomicInnerBinOp->getOpcode();
3491 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003492 auto *LHS = AtomicInnerBinOp->getLHS();
3493 auto *RHS = AtomicInnerBinOp->getRHS();
3494 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3495 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3496 /*Canonical=*/true);
3497 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3498 /*Canonical=*/true);
3499 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3500 /*Canonical=*/true);
3501 if (XId == LHSId) {
3502 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003503 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003504 } else if (XId == RHSId) {
3505 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003506 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003507 } else {
3508 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3509 ErrorRange = AtomicInnerBinOp->getSourceRange();
3510 NoteLoc = X->getExprLoc();
3511 NoteRange = X->getSourceRange();
3512 ErrorFound = NotAnUpdateExpression;
3513 }
3514 } else {
3515 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3516 ErrorRange = AtomicInnerBinOp->getSourceRange();
3517 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3518 NoteRange = SourceRange(NoteLoc, NoteLoc);
3519 ErrorFound = NotABinaryOperator;
3520 }
3521 } else {
3522 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3523 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3524 ErrorFound = NotABinaryExpression;
3525 }
3526 } else {
3527 ErrorLoc = AtomicBinOp->getExprLoc();
3528 ErrorRange = AtomicBinOp->getSourceRange();
3529 NoteLoc = AtomicBinOp->getOperatorLoc();
3530 NoteRange = SourceRange(NoteLoc, NoteLoc);
3531 ErrorFound = NotAnAssignmentOp;
3532 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003533 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003534 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3535 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3536 return true;
3537 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003538 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003539 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003540}
3541
3542bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3543 unsigned NoteId) {
3544 ExprAnalysisErrorCode ErrorFound = NoError;
3545 SourceLocation ErrorLoc, NoteLoc;
3546 SourceRange ErrorRange, NoteRange;
3547 // Allowed constructs are:
3548 // x++;
3549 // x--;
3550 // ++x;
3551 // --x;
3552 // x binop= expr;
3553 // x = x binop expr;
3554 // x = expr binop x;
3555 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3556 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3557 if (AtomicBody->getType()->isScalarType() ||
3558 AtomicBody->isInstantiationDependent()) {
3559 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3560 AtomicBody->IgnoreParenImpCasts())) {
3561 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003562 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003563 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003564 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003565 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003566 X = AtomicCompAssignOp->getLHS();
3567 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003568 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3569 AtomicBody->IgnoreParenImpCasts())) {
3570 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003571 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3572 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003573 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003574 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3575 // Check for Unary Operation
3576 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003577 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003578 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3579 OpLoc = AtomicUnaryOp->getOperatorLoc();
3580 X = AtomicUnaryOp->getSubExpr();
3581 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3582 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003583 } else {
3584 ErrorFound = NotAnUnaryIncDecExpression;
3585 ErrorLoc = AtomicUnaryOp->getExprLoc();
3586 ErrorRange = AtomicUnaryOp->getSourceRange();
3587 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3588 NoteRange = SourceRange(NoteLoc, NoteLoc);
3589 }
3590 } else {
3591 ErrorFound = NotABinaryOrUnaryExpression;
3592 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3593 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3594 }
3595 } else {
3596 ErrorFound = NotAScalarType;
3597 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3598 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3599 }
3600 } else {
3601 ErrorFound = NotAnExpression;
3602 NoteLoc = ErrorLoc = S->getLocStart();
3603 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3604 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003605 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003606 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3607 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3608 return true;
3609 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003610 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003611 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003612 // Build an update expression of form 'OpaqueValueExpr(x) binop
3613 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3614 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3615 auto *OVEX = new (SemaRef.getASTContext())
3616 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3617 auto *OVEExpr = new (SemaRef.getASTContext())
3618 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3619 auto Update =
3620 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3621 IsXLHSInRHSPart ? OVEExpr : OVEX);
3622 if (Update.isInvalid())
3623 return true;
3624 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3625 Sema::AA_Casting);
3626 if (Update.isInvalid())
3627 return true;
3628 UpdateExpr = Update.get();
3629 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003630 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003631}
3632
Alexey Bataev0162e452014-07-22 10:10:35 +00003633StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3634 Stmt *AStmt,
3635 SourceLocation StartLoc,
3636 SourceLocation EndLoc) {
3637 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003638 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003639 // 1.2.2 OpenMP Language Terminology
3640 // Structured block - An executable statement with a single entry at the
3641 // top and a single exit at the bottom.
3642 // The point of exit cannot be a branch out of the structured block.
3643 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003644 OpenMPClauseKind AtomicKind = OMPC_unknown;
3645 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003646 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003647 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003648 C->getClauseKind() == OMPC_update ||
3649 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003650 if (AtomicKind != OMPC_unknown) {
3651 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3652 << SourceRange(C->getLocStart(), C->getLocEnd());
3653 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3654 << getOpenMPClauseName(AtomicKind);
3655 } else {
3656 AtomicKind = C->getClauseKind();
3657 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003658 }
3659 }
3660 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003661
Alexey Bataev459dec02014-07-24 06:46:57 +00003662 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003663 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3664 Body = EWC->getSubExpr();
3665
Alexey Bataev62cec442014-11-18 10:14:22 +00003666 Expr *X = nullptr;
3667 Expr *V = nullptr;
3668 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003669 Expr *UE = nullptr;
3670 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003671 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003672 // OpenMP [2.12.6, atomic Construct]
3673 // In the next expressions:
3674 // * x and v (as applicable) are both l-value expressions with scalar type.
3675 // * During the execution of an atomic region, multiple syntactic
3676 // occurrences of x must designate the same storage location.
3677 // * Neither of v and expr (as applicable) may access the storage location
3678 // designated by x.
3679 // * Neither of x and expr (as applicable) may access the storage location
3680 // designated by v.
3681 // * expr is an expression with scalar type.
3682 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3683 // * binop, binop=, ++, and -- are not overloaded operators.
3684 // * The expression x binop expr must be numerically equivalent to x binop
3685 // (expr). This requirement is satisfied if the operators in expr have
3686 // precedence greater than binop, or by using parentheses around expr or
3687 // subexpressions of expr.
3688 // * The expression expr binop x must be numerically equivalent to (expr)
3689 // binop x. This requirement is satisfied if the operators in expr have
3690 // precedence equal to or greater than binop, or by using parentheses around
3691 // expr or subexpressions of expr.
3692 // * For forms that allow multiple occurrences of x, the number of times
3693 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003694 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003695 enum {
3696 NotAnExpression,
3697 NotAnAssignmentOp,
3698 NotAScalarType,
3699 NotAnLValue,
3700 NoError
3701 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003702 SourceLocation ErrorLoc, NoteLoc;
3703 SourceRange ErrorRange, NoteRange;
3704 // If clause is read:
3705 // v = x;
3706 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3707 auto AtomicBinOp =
3708 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3709 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3710 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3711 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3712 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3713 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3714 if (!X->isLValue() || !V->isLValue()) {
3715 auto NotLValueExpr = X->isLValue() ? V : X;
3716 ErrorFound = NotAnLValue;
3717 ErrorLoc = AtomicBinOp->getExprLoc();
3718 ErrorRange = AtomicBinOp->getSourceRange();
3719 NoteLoc = NotLValueExpr->getExprLoc();
3720 NoteRange = NotLValueExpr->getSourceRange();
3721 }
3722 } else if (!X->isInstantiationDependent() ||
3723 !V->isInstantiationDependent()) {
3724 auto NotScalarExpr =
3725 (X->isInstantiationDependent() || X->getType()->isScalarType())
3726 ? V
3727 : X;
3728 ErrorFound = NotAScalarType;
3729 ErrorLoc = AtomicBinOp->getExprLoc();
3730 ErrorRange = AtomicBinOp->getSourceRange();
3731 NoteLoc = NotScalarExpr->getExprLoc();
3732 NoteRange = NotScalarExpr->getSourceRange();
3733 }
3734 } else {
3735 ErrorFound = NotAnAssignmentOp;
3736 ErrorLoc = AtomicBody->getExprLoc();
3737 ErrorRange = AtomicBody->getSourceRange();
3738 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3739 : AtomicBody->getExprLoc();
3740 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3741 : AtomicBody->getSourceRange();
3742 }
3743 } else {
3744 ErrorFound = NotAnExpression;
3745 NoteLoc = ErrorLoc = Body->getLocStart();
3746 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003747 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003748 if (ErrorFound != NoError) {
3749 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3750 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003751 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3752 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003753 return StmtError();
3754 } else if (CurContext->isDependentContext())
3755 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003756 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003757 enum {
3758 NotAnExpression,
3759 NotAnAssignmentOp,
3760 NotAScalarType,
3761 NotAnLValue,
3762 NoError
3763 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003764 SourceLocation ErrorLoc, NoteLoc;
3765 SourceRange ErrorRange, NoteRange;
3766 // If clause is write:
3767 // x = expr;
3768 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3769 auto AtomicBinOp =
3770 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3771 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003772 X = AtomicBinOp->getLHS();
3773 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003774 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3775 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3776 if (!X->isLValue()) {
3777 ErrorFound = NotAnLValue;
3778 ErrorLoc = AtomicBinOp->getExprLoc();
3779 ErrorRange = AtomicBinOp->getSourceRange();
3780 NoteLoc = X->getExprLoc();
3781 NoteRange = X->getSourceRange();
3782 }
3783 } else if (!X->isInstantiationDependent() ||
3784 !E->isInstantiationDependent()) {
3785 auto NotScalarExpr =
3786 (X->isInstantiationDependent() || X->getType()->isScalarType())
3787 ? E
3788 : X;
3789 ErrorFound = NotAScalarType;
3790 ErrorLoc = AtomicBinOp->getExprLoc();
3791 ErrorRange = AtomicBinOp->getSourceRange();
3792 NoteLoc = NotScalarExpr->getExprLoc();
3793 NoteRange = NotScalarExpr->getSourceRange();
3794 }
3795 } else {
3796 ErrorFound = NotAnAssignmentOp;
3797 ErrorLoc = AtomicBody->getExprLoc();
3798 ErrorRange = AtomicBody->getSourceRange();
3799 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3800 : AtomicBody->getExprLoc();
3801 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3802 : AtomicBody->getSourceRange();
3803 }
3804 } else {
3805 ErrorFound = NotAnExpression;
3806 NoteLoc = ErrorLoc = Body->getLocStart();
3807 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003808 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003809 if (ErrorFound != NoError) {
3810 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3811 << ErrorRange;
3812 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3813 << NoteRange;
3814 return StmtError();
3815 } else if (CurContext->isDependentContext())
3816 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003817 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003818 // If clause is update:
3819 // x++;
3820 // x--;
3821 // ++x;
3822 // --x;
3823 // x binop= expr;
3824 // x = x binop expr;
3825 // x = expr binop x;
3826 OpenMPAtomicUpdateChecker Checker(*this);
3827 if (Checker.checkStatement(
3828 Body, (AtomicKind == OMPC_update)
3829 ? diag::err_omp_atomic_update_not_expression_statement
3830 : diag::err_omp_atomic_not_expression_statement,
3831 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003832 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003833 if (!CurContext->isDependentContext()) {
3834 E = Checker.getExpr();
3835 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003836 UE = Checker.getUpdateExpr();
3837 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003838 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003839 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003840 enum {
3841 NotAnAssignmentOp,
3842 NotACompoundStatement,
3843 NotTwoSubstatements,
3844 NotASpecificExpression,
3845 NoError
3846 } ErrorFound = NoError;
3847 SourceLocation ErrorLoc, NoteLoc;
3848 SourceRange ErrorRange, NoteRange;
3849 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3850 // If clause is a capture:
3851 // v = x++;
3852 // v = x--;
3853 // v = ++x;
3854 // v = --x;
3855 // v = x binop= expr;
3856 // v = x = x binop expr;
3857 // v = x = expr binop x;
3858 auto *AtomicBinOp =
3859 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3860 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3861 V = AtomicBinOp->getLHS();
3862 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3863 OpenMPAtomicUpdateChecker Checker(*this);
3864 if (Checker.checkStatement(
3865 Body, diag::err_omp_atomic_capture_not_expression_statement,
3866 diag::note_omp_atomic_update))
3867 return StmtError();
3868 E = Checker.getExpr();
3869 X = Checker.getX();
3870 UE = Checker.getUpdateExpr();
3871 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3872 IsPostfixUpdate = Checker.isPostfixUpdate();
3873 } else {
3874 ErrorLoc = AtomicBody->getExprLoc();
3875 ErrorRange = AtomicBody->getSourceRange();
3876 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3877 : AtomicBody->getExprLoc();
3878 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3879 : AtomicBody->getSourceRange();
3880 ErrorFound = NotAnAssignmentOp;
3881 }
3882 if (ErrorFound != NoError) {
3883 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3884 << ErrorRange;
3885 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3886 return StmtError();
3887 } else if (CurContext->isDependentContext()) {
3888 UE = V = E = X = nullptr;
3889 }
3890 } else {
3891 // If clause is a capture:
3892 // { v = x; x = expr; }
3893 // { v = x; x++; }
3894 // { v = x; x--; }
3895 // { v = x; ++x; }
3896 // { v = x; --x; }
3897 // { v = x; x binop= expr; }
3898 // { v = x; x = x binop expr; }
3899 // { v = x; x = expr binop x; }
3900 // { x++; v = x; }
3901 // { x--; v = x; }
3902 // { ++x; v = x; }
3903 // { --x; v = x; }
3904 // { x binop= expr; v = x; }
3905 // { x = x binop expr; v = x; }
3906 // { x = expr binop x; v = x; }
3907 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3908 // Check that this is { expr1; expr2; }
3909 if (CS->size() == 2) {
3910 auto *First = CS->body_front();
3911 auto *Second = CS->body_back();
3912 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3913 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3914 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3915 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3916 // Need to find what subexpression is 'v' and what is 'x'.
3917 OpenMPAtomicUpdateChecker Checker(*this);
3918 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3919 BinaryOperator *BinOp = nullptr;
3920 if (IsUpdateExprFound) {
3921 BinOp = dyn_cast<BinaryOperator>(First);
3922 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3923 }
3924 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3925 // { v = x; x++; }
3926 // { v = x; x--; }
3927 // { v = x; ++x; }
3928 // { v = x; --x; }
3929 // { v = x; x binop= expr; }
3930 // { v = x; x = x binop expr; }
3931 // { v = x; x = expr binop x; }
3932 // Check that the first expression has form v = x.
3933 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3934 llvm::FoldingSetNodeID XId, PossibleXId;
3935 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3936 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3937 IsUpdateExprFound = XId == PossibleXId;
3938 if (IsUpdateExprFound) {
3939 V = BinOp->getLHS();
3940 X = Checker.getX();
3941 E = Checker.getExpr();
3942 UE = Checker.getUpdateExpr();
3943 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003944 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003945 }
3946 }
3947 if (!IsUpdateExprFound) {
3948 IsUpdateExprFound = !Checker.checkStatement(First);
3949 BinOp = nullptr;
3950 if (IsUpdateExprFound) {
3951 BinOp = dyn_cast<BinaryOperator>(Second);
3952 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3953 }
3954 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3955 // { x++; v = x; }
3956 // { x--; v = x; }
3957 // { ++x; v = x; }
3958 // { --x; v = x; }
3959 // { x binop= expr; v = x; }
3960 // { x = x binop expr; v = x; }
3961 // { x = expr binop x; v = x; }
3962 // Check that the second expression has form v = x.
3963 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3964 llvm::FoldingSetNodeID XId, PossibleXId;
3965 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3966 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3967 IsUpdateExprFound = XId == PossibleXId;
3968 if (IsUpdateExprFound) {
3969 V = BinOp->getLHS();
3970 X = Checker.getX();
3971 E = Checker.getExpr();
3972 UE = Checker.getUpdateExpr();
3973 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003974 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003975 }
3976 }
3977 }
3978 if (!IsUpdateExprFound) {
3979 // { v = x; x = expr; }
3980 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3981 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3982 ErrorFound = NotAnAssignmentOp;
3983 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3984 : First->getLocStart();
3985 NoteRange = ErrorRange = FirstBinOp
3986 ? FirstBinOp->getSourceRange()
3987 : SourceRange(ErrorLoc, ErrorLoc);
3988 } else {
3989 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3990 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3991 ErrorFound = NotAnAssignmentOp;
3992 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3993 : Second->getLocStart();
3994 NoteRange = ErrorRange = SecondBinOp
3995 ? SecondBinOp->getSourceRange()
3996 : SourceRange(ErrorLoc, ErrorLoc);
3997 } else {
3998 auto *PossibleXRHSInFirst =
3999 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4000 auto *PossibleXLHSInSecond =
4001 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4002 llvm::FoldingSetNodeID X1Id, X2Id;
4003 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4004 PossibleXLHSInSecond->Profile(X2Id, Context,
4005 /*Canonical=*/true);
4006 IsUpdateExprFound = X1Id == X2Id;
4007 if (IsUpdateExprFound) {
4008 V = FirstBinOp->getLHS();
4009 X = SecondBinOp->getLHS();
4010 E = SecondBinOp->getRHS();
4011 UE = nullptr;
4012 IsXLHSInRHSPart = false;
4013 IsPostfixUpdate = true;
4014 } else {
4015 ErrorFound = NotASpecificExpression;
4016 ErrorLoc = FirstBinOp->getExprLoc();
4017 ErrorRange = FirstBinOp->getSourceRange();
4018 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4019 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4020 }
4021 }
4022 }
4023 }
4024 } else {
4025 NoteLoc = ErrorLoc = Body->getLocStart();
4026 NoteRange = ErrorRange =
4027 SourceRange(Body->getLocStart(), Body->getLocStart());
4028 ErrorFound = NotTwoSubstatements;
4029 }
4030 } else {
4031 NoteLoc = ErrorLoc = Body->getLocStart();
4032 NoteRange = ErrorRange =
4033 SourceRange(Body->getLocStart(), Body->getLocStart());
4034 ErrorFound = NotACompoundStatement;
4035 }
4036 if (ErrorFound != NoError) {
4037 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4038 << ErrorRange;
4039 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4040 return StmtError();
4041 } else if (CurContext->isDependentContext()) {
4042 UE = V = E = X = nullptr;
4043 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004044 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004045 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004046
4047 getCurFunction()->setHasBranchProtectedScope();
4048
Alexey Bataev62cec442014-11-18 10:14:22 +00004049 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004050 X, V, E, UE, IsXLHSInRHSPart,
4051 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004052}
4053
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004054StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4055 Stmt *AStmt,
4056 SourceLocation StartLoc,
4057 SourceLocation EndLoc) {
4058 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4059
Alexey Bataev13314bf2014-10-09 04:18:56 +00004060 // OpenMP [2.16, Nesting of Regions]
4061 // If specified, a teams construct must be contained within a target
4062 // construct. That target construct must contain no statements or directives
4063 // outside of the teams construct.
4064 if (DSAStack->hasInnerTeamsRegion()) {
4065 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4066 bool OMPTeamsFound = true;
4067 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4068 auto I = CS->body_begin();
4069 while (I != CS->body_end()) {
4070 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4071 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4072 OMPTeamsFound = false;
4073 break;
4074 }
4075 ++I;
4076 }
4077 assert(I != CS->body_end() && "Not found statement");
4078 S = *I;
4079 }
4080 if (!OMPTeamsFound) {
4081 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4082 Diag(DSAStack->getInnerTeamsRegionLoc(),
4083 diag::note_omp_nested_teams_construct_here);
4084 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4085 << isa<OMPExecutableDirective>(S);
4086 return StmtError();
4087 }
4088 }
4089
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004090 getCurFunction()->setHasBranchProtectedScope();
4091
4092 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4093}
4094
Alexey Bataev13314bf2014-10-09 04:18:56 +00004095StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4096 Stmt *AStmt, SourceLocation StartLoc,
4097 SourceLocation EndLoc) {
4098 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4099 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4100 // 1.2.2 OpenMP Language Terminology
4101 // Structured block - An executable statement with a single entry at the
4102 // top and a single exit at the bottom.
4103 // The point of exit cannot be a branch out of the structured block.
4104 // longjmp() and throw() must not violate the entry/exit criteria.
4105 CS->getCapturedDecl()->setNothrow();
4106
4107 getCurFunction()->setHasBranchProtectedScope();
4108
4109 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4110}
4111
Alexey Bataeved09d242014-05-28 05:53:51 +00004112OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004113 SourceLocation StartLoc,
4114 SourceLocation LParenLoc,
4115 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004116 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004117 switch (Kind) {
4118 case OMPC_if:
4119 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4120 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004121 case OMPC_final:
4122 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4123 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004124 case OMPC_num_threads:
4125 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4126 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004127 case OMPC_safelen:
4128 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4129 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004130 case OMPC_collapse:
4131 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4132 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004133 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004134 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004135 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004136 case OMPC_private:
4137 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004138 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004139 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004140 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004141 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004142 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004143 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004144 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004145 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004146 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004147 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004148 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004149 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004150 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004151 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004152 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004153 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004154 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004155 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004156 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004157 llvm_unreachable("Clause is not allowed.");
4158 }
4159 return Res;
4160}
4161
Alexey Bataeved09d242014-05-28 05:53:51 +00004162OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004163 SourceLocation LParenLoc,
4164 SourceLocation EndLoc) {
4165 Expr *ValExpr = Condition;
4166 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4167 !Condition->isInstantiationDependent() &&
4168 !Condition->containsUnexpandedParameterPack()) {
4169 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004170 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004171 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004172 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004173
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004174 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004175 }
4176
4177 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4178}
4179
Alexey Bataev3778b602014-07-17 07:32:53 +00004180OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4181 SourceLocation StartLoc,
4182 SourceLocation LParenLoc,
4183 SourceLocation EndLoc) {
4184 Expr *ValExpr = Condition;
4185 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4186 !Condition->isInstantiationDependent() &&
4187 !Condition->containsUnexpandedParameterPack()) {
4188 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4189 Condition->getExprLoc(), Condition);
4190 if (Val.isInvalid())
4191 return nullptr;
4192
4193 ValExpr = Val.get();
4194 }
4195
4196 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4197}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004198ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4199 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004200 if (!Op)
4201 return ExprError();
4202
4203 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4204 public:
4205 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004206 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004207 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4208 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004209 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4210 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004211 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4212 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004213 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4214 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004215 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4216 QualType T,
4217 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004218 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4219 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004220 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4221 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004222 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004223 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004224 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004225 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4226 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004227 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4228 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004229 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4230 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004231 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004232 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004233 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004234 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4235 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004236 llvm_unreachable("conversion functions are permitted");
4237 }
4238 } ConvertDiagnoser;
4239 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4240}
4241
4242OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4243 SourceLocation StartLoc,
4244 SourceLocation LParenLoc,
4245 SourceLocation EndLoc) {
4246 Expr *ValExpr = NumThreads;
4247 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004248 !NumThreads->containsUnexpandedParameterPack()) {
4249 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4250 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004251 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004252 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004253 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004254
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004255 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004256
4257 // OpenMP [2.5, Restrictions]
4258 // The num_threads expression must evaluate to a positive integer value.
4259 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004260 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4261 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004262 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4263 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004264 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004265 }
4266 }
4267
Alexey Bataeved09d242014-05-28 05:53:51 +00004268 return new (Context)
4269 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004270}
4271
Alexey Bataev62c87d22014-03-21 04:51:18 +00004272ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4273 OpenMPClauseKind CKind) {
4274 if (!E)
4275 return ExprError();
4276 if (E->isValueDependent() || E->isTypeDependent() ||
4277 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004278 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004279 llvm::APSInt Result;
4280 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4281 if (ICE.isInvalid())
4282 return ExprError();
4283 if (!Result.isStrictlyPositive()) {
4284 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4285 << getOpenMPClauseName(CKind) << E->getSourceRange();
4286 return ExprError();
4287 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004288 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4289 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4290 << E->getSourceRange();
4291 return ExprError();
4292 }
Alexey Bataev9c821032015-04-30 04:23:23 +00004293 if (CKind == OMPC_collapse) {
4294 DSAStack->setCollapseNumber(Result.getExtValue());
4295 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004296 return ICE;
4297}
4298
4299OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4300 SourceLocation LParenLoc,
4301 SourceLocation EndLoc) {
4302 // OpenMP [2.8.1, simd construct, Description]
4303 // The parameter of the safelen clause must be a constant
4304 // positive integer expression.
4305 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4306 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004307 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004308 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004309 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004310}
4311
Alexander Musman64d33f12014-06-04 07:53:32 +00004312OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4313 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004314 SourceLocation LParenLoc,
4315 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004316 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004317 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004318 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004319 // The parameter of the collapse clause must be a constant
4320 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004321 ExprResult NumForLoopsResult =
4322 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4323 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004324 return nullptr;
4325 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004326 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004327}
4328
Alexey Bataeved09d242014-05-28 05:53:51 +00004329OMPClause *Sema::ActOnOpenMPSimpleClause(
4330 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4331 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004332 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004333 switch (Kind) {
4334 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004335 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004336 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4337 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004338 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004339 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004340 Res = ActOnOpenMPProcBindClause(
4341 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4342 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004343 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004344 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004345 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004346 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004347 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004348 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004349 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004350 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004351 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004352 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004353 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004354 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004355 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004356 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004357 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004358 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004359 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004360 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004361 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004362 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004363 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004364 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004365 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004366 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004367 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004368 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004369 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004370 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004371 llvm_unreachable("Clause is not allowed.");
4372 }
4373 return Res;
4374}
4375
4376OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4377 SourceLocation KindKwLoc,
4378 SourceLocation StartLoc,
4379 SourceLocation LParenLoc,
4380 SourceLocation EndLoc) {
4381 if (Kind == OMPC_DEFAULT_unknown) {
4382 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004383 static_assert(OMPC_DEFAULT_unknown > 0,
4384 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004385 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004386 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004387 Values += "'";
4388 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4389 Values += "'";
4390 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004391 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004392 Values += " or ";
4393 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004394 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004395 break;
4396 default:
4397 Values += Sep;
4398 break;
4399 }
4400 }
4401 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004402 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004403 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004404 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004405 switch (Kind) {
4406 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004407 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004408 break;
4409 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004410 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004411 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004412 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004413 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004414 break;
4415 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004416 return new (Context)
4417 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004418}
4419
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004420OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4421 SourceLocation KindKwLoc,
4422 SourceLocation StartLoc,
4423 SourceLocation LParenLoc,
4424 SourceLocation EndLoc) {
4425 if (Kind == OMPC_PROC_BIND_unknown) {
4426 std::string Values;
4427 std::string Sep(", ");
4428 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4429 Values += "'";
4430 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4431 Values += "'";
4432 switch (i) {
4433 case OMPC_PROC_BIND_unknown - 2:
4434 Values += " or ";
4435 break;
4436 case OMPC_PROC_BIND_unknown - 1:
4437 break;
4438 default:
4439 Values += Sep;
4440 break;
4441 }
4442 }
4443 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004444 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004445 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004446 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004447 return new (Context)
4448 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004449}
4450
Alexey Bataev56dafe82014-06-20 07:16:17 +00004451OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4452 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4453 SourceLocation StartLoc, SourceLocation LParenLoc,
4454 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4455 SourceLocation EndLoc) {
4456 OMPClause *Res = nullptr;
4457 switch (Kind) {
4458 case OMPC_schedule:
4459 Res = ActOnOpenMPScheduleClause(
4460 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4461 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4462 break;
4463 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004464 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004465 case OMPC_num_threads:
4466 case OMPC_safelen:
4467 case OMPC_collapse:
4468 case OMPC_default:
4469 case OMPC_proc_bind:
4470 case OMPC_private:
4471 case OMPC_firstprivate:
4472 case OMPC_lastprivate:
4473 case OMPC_shared:
4474 case OMPC_reduction:
4475 case OMPC_linear:
4476 case OMPC_aligned:
4477 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004478 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004479 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004480 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004481 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004482 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004483 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004484 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004485 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004486 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004487 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004488 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004489 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004490 case OMPC_unknown:
4491 llvm_unreachable("Clause is not allowed.");
4492 }
4493 return Res;
4494}
4495
4496OMPClause *Sema::ActOnOpenMPScheduleClause(
4497 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4498 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4499 SourceLocation EndLoc) {
4500 if (Kind == OMPC_SCHEDULE_unknown) {
4501 std::string Values;
4502 std::string Sep(", ");
4503 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4504 Values += "'";
4505 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4506 Values += "'";
4507 switch (i) {
4508 case OMPC_SCHEDULE_unknown - 2:
4509 Values += " or ";
4510 break;
4511 case OMPC_SCHEDULE_unknown - 1:
4512 break;
4513 default:
4514 Values += Sep;
4515 break;
4516 }
4517 }
4518 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4519 << Values << getOpenMPClauseName(OMPC_schedule);
4520 return nullptr;
4521 }
4522 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00004523 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004524 if (ChunkSize) {
4525 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4526 !ChunkSize->isInstantiationDependent() &&
4527 !ChunkSize->containsUnexpandedParameterPack()) {
4528 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4529 ExprResult Val =
4530 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4531 if (Val.isInvalid())
4532 return nullptr;
4533
4534 ValExpr = Val.get();
4535
4536 // OpenMP [2.7.1, Restrictions]
4537 // chunk_size must be a loop invariant integer expression with a positive
4538 // value.
4539 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00004540 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4541 if (Result.isSigned() && !Result.isStrictlyPositive()) {
4542 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4543 << "schedule" << ChunkSize->getSourceRange();
4544 return nullptr;
4545 }
4546 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4547 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4548 ChunkSize->getType(), ".chunk.");
4549 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4550 ChunkSize->getExprLoc(),
4551 /*RefersToCapture=*/true);
4552 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00004553 }
4554 }
4555 }
4556
4557 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00004558 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00004559}
4560
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004561OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4562 SourceLocation StartLoc,
4563 SourceLocation EndLoc) {
4564 OMPClause *Res = nullptr;
4565 switch (Kind) {
4566 case OMPC_ordered:
4567 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4568 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004569 case OMPC_nowait:
4570 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4571 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004572 case OMPC_untied:
4573 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4574 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004575 case OMPC_mergeable:
4576 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4577 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004578 case OMPC_read:
4579 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4580 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004581 case OMPC_write:
4582 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4583 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004584 case OMPC_update:
4585 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4586 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004587 case OMPC_capture:
4588 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4589 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004590 case OMPC_seq_cst:
4591 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4592 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004593 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004594 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004595 case OMPC_num_threads:
4596 case OMPC_safelen:
4597 case OMPC_collapse:
4598 case OMPC_schedule:
4599 case OMPC_private:
4600 case OMPC_firstprivate:
4601 case OMPC_lastprivate:
4602 case OMPC_shared:
4603 case OMPC_reduction:
4604 case OMPC_linear:
4605 case OMPC_aligned:
4606 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004607 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004608 case OMPC_default:
4609 case OMPC_proc_bind:
4610 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004611 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004612 case OMPC_unknown:
4613 llvm_unreachable("Clause is not allowed.");
4614 }
4615 return Res;
4616}
4617
4618OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4619 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004620 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004621 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4622}
4623
Alexey Bataev236070f2014-06-20 11:19:47 +00004624OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4625 SourceLocation EndLoc) {
4626 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4627}
4628
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004629OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4630 SourceLocation EndLoc) {
4631 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4632}
4633
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004634OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4635 SourceLocation EndLoc) {
4636 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4637}
4638
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004639OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4640 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004641 return new (Context) OMPReadClause(StartLoc, EndLoc);
4642}
4643
Alexey Bataevdea47612014-07-23 07:46:59 +00004644OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4645 SourceLocation EndLoc) {
4646 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4647}
4648
Alexey Bataev67a4f222014-07-23 10:25:33 +00004649OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4650 SourceLocation EndLoc) {
4651 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4652}
4653
Alexey Bataev459dec02014-07-24 06:46:57 +00004654OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4655 SourceLocation EndLoc) {
4656 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4657}
4658
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004659OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4660 SourceLocation EndLoc) {
4661 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4662}
4663
Alexey Bataevc5e02582014-06-16 07:08:35 +00004664OMPClause *Sema::ActOnOpenMPVarListClause(
4665 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4666 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4667 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4668 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004669 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004670 switch (Kind) {
4671 case OMPC_private:
4672 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4673 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004674 case OMPC_firstprivate:
4675 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4676 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004677 case OMPC_lastprivate:
4678 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4679 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004680 case OMPC_shared:
4681 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4682 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004683 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004684 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4685 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004686 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004687 case OMPC_linear:
4688 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4689 ColonLoc, EndLoc);
4690 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004691 case OMPC_aligned:
4692 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4693 ColonLoc, EndLoc);
4694 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004695 case OMPC_copyin:
4696 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4697 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004698 case OMPC_copyprivate:
4699 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4700 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004701 case OMPC_flush:
4702 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4703 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004704 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004705 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004706 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004707 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004708 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004709 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004710 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004711 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004712 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004713 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004714 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004715 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004716 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004717 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004718 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004719 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004720 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004721 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004722 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004723 llvm_unreachable("Clause is not allowed.");
4724 }
4725 return Res;
4726}
4727
4728OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4729 SourceLocation StartLoc,
4730 SourceLocation LParenLoc,
4731 SourceLocation EndLoc) {
4732 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004733 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004734 for (auto &RefExpr : VarList) {
4735 assert(RefExpr && "NULL expr in OpenMP private clause.");
4736 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004737 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004738 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004739 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004740 continue;
4741 }
4742
Alexey Bataeved09d242014-05-28 05:53:51 +00004743 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004744 // OpenMP [2.1, C/C++]
4745 // A list item is a variable name.
4746 // OpenMP [2.9.3.3, Restrictions, p.1]
4747 // A variable that is part of another variable (as an array or
4748 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004749 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004750 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004751 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004752 continue;
4753 }
4754 Decl *D = DE->getDecl();
4755 VarDecl *VD = cast<VarDecl>(D);
4756
4757 QualType Type = VD->getType();
4758 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4759 // It will be analyzed later.
4760 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004761 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004762 continue;
4763 }
4764
4765 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4766 // A variable that appears in a private clause must not have an incomplete
4767 // type or a reference type.
4768 if (RequireCompleteType(ELoc, Type,
4769 diag::err_omp_private_incomplete_type)) {
4770 continue;
4771 }
4772 if (Type->isReferenceType()) {
4773 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004774 << getOpenMPClauseName(OMPC_private) << Type;
4775 bool IsDecl =
4776 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4777 Diag(VD->getLocation(),
4778 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4779 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004780 continue;
4781 }
4782
Alexey Bataev758e55e2013-09-06 18:03:48 +00004783 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4784 // in a Construct]
4785 // Variables with the predetermined data-sharing attributes may not be
4786 // listed in data-sharing attributes clauses, except for the cases
4787 // listed below. For these exceptions only, listing a predetermined
4788 // variable in a data-sharing attribute clause is allowed and overrides
4789 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004790 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004791 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004792 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4793 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004794 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004795 continue;
4796 }
4797
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004798 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00004799 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00004800 DSAStack->getCurrentDirective() == OMPD_task) {
4801 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
4802 << getOpenMPClauseName(OMPC_private) << Type
4803 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4804 bool IsDecl =
4805 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4806 Diag(VD->getLocation(),
4807 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4808 << VD;
4809 continue;
4810 }
4811
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004812 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4813 // A variable of class type (or array thereof) that appears in a private
4814 // clause requires an accessible, unambiguous default constructor for the
4815 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004816 // Generate helper private variable and initialize it with the default
4817 // value. The address of the original variable is replaced by the address of
4818 // the new private variable in CodeGen. This new variable is not added to
4819 // IdResolver, so the code in the OpenMP region uses original variable for
4820 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004821 Type = Type.getUnqualifiedType();
4822 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
Alexey Bataev39f915b82015-05-08 10:41:21 +00004823 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004824 if (VDPrivate->isInvalidDecl())
4825 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004826 auto VDPrivateRefExpr = buildDeclRefExpr(
4827 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00004828
Alexey Bataev758e55e2013-09-06 18:03:48 +00004829 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004830 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004831 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004832 }
4833
Alexey Bataeved09d242014-05-28 05:53:51 +00004834 if (Vars.empty())
4835 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004836
Alexey Bataev03b340a2014-10-21 03:16:40 +00004837 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4838 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004839}
4840
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004841namespace {
4842class DiagsUninitializedSeveretyRAII {
4843private:
4844 DiagnosticsEngine &Diags;
4845 SourceLocation SavedLoc;
4846 bool IsIgnored;
4847
4848public:
4849 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4850 bool IsIgnored)
4851 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4852 if (!IsIgnored) {
4853 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4854 /*Map*/ diag::Severity::Ignored, Loc);
4855 }
4856 }
4857 ~DiagsUninitializedSeveretyRAII() {
4858 if (!IsIgnored)
4859 Diags.popMappings(SavedLoc);
4860 }
4861};
4862}
4863
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004864OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4865 SourceLocation StartLoc,
4866 SourceLocation LParenLoc,
4867 SourceLocation EndLoc) {
4868 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004869 SmallVector<Expr *, 8> PrivateCopies;
4870 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004871 bool IsImplicitClause =
4872 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4873 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4874
Alexey Bataeved09d242014-05-28 05:53:51 +00004875 for (auto &RefExpr : VarList) {
4876 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4877 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004878 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004879 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004880 PrivateCopies.push_back(nullptr);
4881 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004882 continue;
4883 }
4884
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004885 SourceLocation ELoc =
4886 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004887 // OpenMP [2.1, C/C++]
4888 // A list item is a variable name.
4889 // OpenMP [2.9.3.3, Restrictions, p.1]
4890 // A variable that is part of another variable (as an array or
4891 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004892 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004893 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004894 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004895 continue;
4896 }
4897 Decl *D = DE->getDecl();
4898 VarDecl *VD = cast<VarDecl>(D);
4899
4900 QualType Type = VD->getType();
4901 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4902 // It will be analyzed later.
4903 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004904 PrivateCopies.push_back(nullptr);
4905 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004906 continue;
4907 }
4908
4909 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4910 // A variable that appears in a private clause must not have an incomplete
4911 // type or a reference type.
4912 if (RequireCompleteType(ELoc, Type,
4913 diag::err_omp_firstprivate_incomplete_type)) {
4914 continue;
4915 }
4916 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004917 if (IsImplicitClause) {
4918 Diag(ImplicitClauseLoc,
4919 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4920 << Type;
4921 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4922 } else {
4923 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4924 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4925 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004926 bool IsDecl =
4927 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4928 Diag(VD->getLocation(),
4929 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4930 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004931 continue;
4932 }
4933
4934 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4935 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004936 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004937 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004938 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004939
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004940 // If an implicit firstprivate variable found it was checked already.
4941 if (!IsImplicitClause) {
4942 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00004943 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004944 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4945 // A list item that specifies a given variable may not appear in more
4946 // than one clause on the same directive, except that a variable may be
4947 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004948 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004949 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004950 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004951 << getOpenMPClauseName(DVar.CKind)
4952 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004953 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004954 continue;
4955 }
4956
4957 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4958 // in a Construct]
4959 // Variables with the predetermined data-sharing attributes may not be
4960 // listed in data-sharing attributes clauses, except for the cases
4961 // listed below. For these exceptions only, listing a predetermined
4962 // variable in a data-sharing attribute clause is allowed and overrides
4963 // the variable's predetermined data-sharing attributes.
4964 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4965 // in a Construct, C/C++, p.2]
4966 // Variables with const-qualified type having no mutable member may be
4967 // listed in a firstprivate clause, even if they are static data members.
4968 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4969 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4970 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004971 << getOpenMPClauseName(DVar.CKind)
4972 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004973 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004974 continue;
4975 }
4976
Alexey Bataevf29276e2014-06-18 04:14:57 +00004977 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004978 // OpenMP [2.9.3.4, Restrictions, p.2]
4979 // A list item that is private within a parallel region must not appear
4980 // in a firstprivate clause on a worksharing construct if any of the
4981 // worksharing regions arising from the worksharing construct ever bind
4982 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004983 if (isOpenMPWorksharingDirective(CurrDir) &&
4984 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004985 DVar = DSAStack->getImplicitDSA(VD, true);
4986 if (DVar.CKind != OMPC_shared &&
4987 (isOpenMPParallelDirective(DVar.DKind) ||
4988 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004989 Diag(ELoc, diag::err_omp_required_access)
4990 << getOpenMPClauseName(OMPC_firstprivate)
4991 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004992 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004993 continue;
4994 }
4995 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004996 // OpenMP [2.9.3.4, Restrictions, p.3]
4997 // A list item that appears in a reduction clause of a parallel construct
4998 // must not appear in a firstprivate clause on a worksharing or task
4999 // construct if any of the worksharing or task regions arising from the
5000 // worksharing or task construct ever bind to any of the parallel regions
5001 // arising from the parallel construct.
5002 // OpenMP [2.9.3.4, Restrictions, p.4]
5003 // A list item that appears in a reduction clause in worksharing
5004 // construct must not appear in a firstprivate clause in a task construct
5005 // encountered during execution of any of the worksharing regions arising
5006 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005007 if (CurrDir == OMPD_task) {
5008 DVar =
5009 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5010 [](OpenMPDirectiveKind K) -> bool {
5011 return isOpenMPParallelDirective(K) ||
5012 isOpenMPWorksharingDirective(K);
5013 },
5014 false);
5015 if (DVar.CKind == OMPC_reduction &&
5016 (isOpenMPParallelDirective(DVar.DKind) ||
5017 isOpenMPWorksharingDirective(DVar.DKind))) {
5018 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5019 << getOpenMPDirectiveName(DVar.DKind);
5020 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5021 continue;
5022 }
5023 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005024 }
5025
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005026 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005027 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005028 DSAStack->getCurrentDirective() == OMPD_task) {
5029 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5030 << getOpenMPClauseName(OMPC_firstprivate) << Type
5031 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5032 bool IsDecl =
5033 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5034 Diag(VD->getLocation(),
5035 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5036 << VD;
5037 continue;
5038 }
5039
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005040 Type = Type.getUnqualifiedType();
5041 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005042 // Generate helper private variable and initialize it with the value of the
5043 // original variable. The address of the original variable is replaced by
5044 // the address of the new private variable in the CodeGen. This new variable
5045 // is not added to IdResolver, so the code in the OpenMP region uses
5046 // original variable for proper diagnostics and variable capturing.
5047 Expr *VDInitRefExpr = nullptr;
5048 // For arrays generate initializer for single element and replace it by the
5049 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005050 if (Type->isArrayType()) {
5051 auto VDInit =
5052 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5053 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005054 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005055 ElemType = ElemType.getUnqualifiedType();
5056 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5057 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00005058 InitializedEntity Entity =
5059 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005060 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5061
5062 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5063 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5064 if (Result.isInvalid())
5065 VDPrivate->setInvalidDecl();
5066 else
5067 VDPrivate->setInit(Result.getAs<Expr>());
5068 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00005069 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005070 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005071 VDInitRefExpr =
5072 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00005073 AddInitializerToDecl(VDPrivate,
5074 DefaultLvalueConversion(VDInitRefExpr).get(),
5075 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005076 }
5077 if (VDPrivate->isInvalidDecl()) {
5078 if (IsImplicitClause) {
5079 Diag(DE->getExprLoc(),
5080 diag::note_omp_task_predetermined_firstprivate_here);
5081 }
5082 continue;
5083 }
5084 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005085 auto VDPrivateRefExpr = buildDeclRefExpr(
5086 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005087 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5088 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005089 PrivateCopies.push_back(VDPrivateRefExpr);
5090 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005091 }
5092
Alexey Bataeved09d242014-05-28 05:53:51 +00005093 if (Vars.empty())
5094 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005095
5096 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005097 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005098}
5099
Alexander Musman1bb328c2014-06-04 13:06:39 +00005100OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5101 SourceLocation StartLoc,
5102 SourceLocation LParenLoc,
5103 SourceLocation EndLoc) {
5104 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00005105 SmallVector<Expr *, 8> SrcExprs;
5106 SmallVector<Expr *, 8> DstExprs;
5107 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005108 for (auto &RefExpr : VarList) {
5109 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5110 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5111 // It will be analyzed later.
5112 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00005113 SrcExprs.push_back(nullptr);
5114 DstExprs.push_back(nullptr);
5115 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005116 continue;
5117 }
5118
5119 SourceLocation ELoc = RefExpr->getExprLoc();
5120 // OpenMP [2.1, C/C++]
5121 // A list item is a variable name.
5122 // OpenMP [2.14.3.5, Restrictions, p.1]
5123 // A variable that is part of another variable (as an array or structure
5124 // element) cannot appear in a lastprivate clause.
5125 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5126 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5127 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5128 continue;
5129 }
5130 Decl *D = DE->getDecl();
5131 VarDecl *VD = cast<VarDecl>(D);
5132
5133 QualType Type = VD->getType();
5134 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5135 // It will be analyzed later.
5136 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005137 SrcExprs.push_back(nullptr);
5138 DstExprs.push_back(nullptr);
5139 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005140 continue;
5141 }
5142
5143 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5144 // A variable that appears in a lastprivate clause must not have an
5145 // incomplete type or a reference type.
5146 if (RequireCompleteType(ELoc, Type,
5147 diag::err_omp_lastprivate_incomplete_type)) {
5148 continue;
5149 }
5150 if (Type->isReferenceType()) {
5151 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5152 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5153 bool IsDecl =
5154 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5155 Diag(VD->getLocation(),
5156 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5157 << VD;
5158 continue;
5159 }
5160
5161 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5162 // in a Construct]
5163 // Variables with the predetermined data-sharing attributes may not be
5164 // listed in data-sharing attributes clauses, except for the cases
5165 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005166 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005167 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5168 DVar.CKind != OMPC_firstprivate &&
5169 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5170 Diag(ELoc, diag::err_omp_wrong_dsa)
5171 << getOpenMPClauseName(DVar.CKind)
5172 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005173 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005174 continue;
5175 }
5176
Alexey Bataevf29276e2014-06-18 04:14:57 +00005177 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5178 // OpenMP [2.14.3.5, Restrictions, p.2]
5179 // A list item that is private within a parallel region, or that appears in
5180 // the reduction clause of a parallel construct, must not appear in a
5181 // lastprivate clause on a worksharing construct if any of the corresponding
5182 // worksharing regions ever binds to any of the corresponding parallel
5183 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005184 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00005185 if (isOpenMPWorksharingDirective(CurrDir) &&
5186 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005187 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005188 if (DVar.CKind != OMPC_shared) {
5189 Diag(ELoc, diag::err_omp_required_access)
5190 << getOpenMPClauseName(OMPC_lastprivate)
5191 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005192 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005193 continue;
5194 }
5195 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005196 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005197 // A variable of class type (or array thereof) that appears in a
5198 // lastprivate clause requires an accessible, unambiguous default
5199 // constructor for the class type, unless the list item is also specified
5200 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005201 // A variable of class type (or array thereof) that appears in a
5202 // lastprivate clause requires an accessible, unambiguous copy assignment
5203 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005204 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005205 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev38e89532015-04-16 04:54:05 +00005206 Type.getUnqualifiedType(), ".lastprivate.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00005207 auto *PseudoSrcExpr = buildDeclRefExpr(
5208 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005209 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005210 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
Alexey Bataev38e89532015-04-16 04:54:05 +00005211 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005212 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00005213 // For arrays generate assignment operation for single element and replace
5214 // it by the original array element in CodeGen.
5215 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5216 PseudoDstExpr, PseudoSrcExpr);
5217 if (AssignmentOp.isInvalid())
5218 continue;
5219 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5220 /*DiscardedValue=*/true);
5221 if (AssignmentOp.isInvalid())
5222 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005223
Alexey Bataev39f915b82015-05-08 10:41:21 +00005224 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005225 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005226 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005227 SrcExprs.push_back(PseudoSrcExpr);
5228 DstExprs.push_back(PseudoDstExpr);
5229 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005230 }
5231
5232 if (Vars.empty())
5233 return nullptr;
5234
5235 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005236 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005237}
5238
Alexey Bataev758e55e2013-09-06 18:03:48 +00005239OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5240 SourceLocation StartLoc,
5241 SourceLocation LParenLoc,
5242 SourceLocation EndLoc) {
5243 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005244 for (auto &RefExpr : VarList) {
5245 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5246 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005247 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005248 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005249 continue;
5250 }
5251
Alexey Bataeved09d242014-05-28 05:53:51 +00005252 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005253 // OpenMP [2.1, C/C++]
5254 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005255 // OpenMP [2.14.3.2, Restrictions, p.1]
5256 // A variable that is part of another variable (as an array or structure
5257 // element) cannot appear in a shared unless it is a static data member
5258 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005259 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005260 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005261 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005262 continue;
5263 }
5264 Decl *D = DE->getDecl();
5265 VarDecl *VD = cast<VarDecl>(D);
5266
5267 QualType Type = VD->getType();
5268 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5269 // It will be analyzed later.
5270 Vars.push_back(DE);
5271 continue;
5272 }
5273
5274 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5275 // in a Construct]
5276 // Variables with the predetermined data-sharing attributes may not be
5277 // listed in data-sharing attributes clauses, except for the cases
5278 // listed below. For these exceptions only, listing a predetermined
5279 // variable in a data-sharing attribute clause is allowed and overrides
5280 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005281 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005282 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5283 DVar.RefExpr) {
5284 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5285 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005286 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005287 continue;
5288 }
5289
5290 DSAStack->addDSA(VD, DE, OMPC_shared);
5291 Vars.push_back(DE);
5292 }
5293
Alexey Bataeved09d242014-05-28 05:53:51 +00005294 if (Vars.empty())
5295 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005296
5297 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5298}
5299
Alexey Bataevc5e02582014-06-16 07:08:35 +00005300namespace {
5301class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5302 DSAStackTy *Stack;
5303
5304public:
5305 bool VisitDeclRefExpr(DeclRefExpr *E) {
5306 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005307 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005308 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5309 return false;
5310 if (DVar.CKind != OMPC_unknown)
5311 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005312 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005313 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005314 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005315 return true;
5316 return false;
5317 }
5318 return false;
5319 }
5320 bool VisitStmt(Stmt *S) {
5321 for (auto Child : S->children()) {
5322 if (Child && Visit(Child))
5323 return true;
5324 }
5325 return false;
5326 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005327 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005328};
Alexey Bataev23b69422014-06-18 07:08:49 +00005329} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005330
5331OMPClause *Sema::ActOnOpenMPReductionClause(
5332 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5333 SourceLocation ColonLoc, SourceLocation EndLoc,
5334 CXXScopeSpec &ReductionIdScopeSpec,
5335 const DeclarationNameInfo &ReductionId) {
5336 // TODO: Allow scope specification search when 'declare reduction' is
5337 // supported.
5338 assert(ReductionIdScopeSpec.isEmpty() &&
5339 "No support for scoped reduction identifiers yet.");
5340
5341 auto DN = ReductionId.getName();
5342 auto OOK = DN.getCXXOverloadedOperator();
5343 BinaryOperatorKind BOK = BO_Comma;
5344
5345 // OpenMP [2.14.3.6, reduction clause]
5346 // C
5347 // reduction-identifier is either an identifier or one of the following
5348 // operators: +, -, *, &, |, ^, && and ||
5349 // C++
5350 // reduction-identifier is either an id-expression or one of the following
5351 // operators: +, -, *, &, |, ^, && and ||
5352 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5353 switch (OOK) {
5354 case OO_Plus:
5355 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005356 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005357 break;
5358 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005359 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005360 break;
5361 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005362 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005363 break;
5364 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005365 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005366 break;
5367 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005368 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005369 break;
5370 case OO_AmpAmp:
5371 BOK = BO_LAnd;
5372 break;
5373 case OO_PipePipe:
5374 BOK = BO_LOr;
5375 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005376 case OO_New:
5377 case OO_Delete:
5378 case OO_Array_New:
5379 case OO_Array_Delete:
5380 case OO_Slash:
5381 case OO_Percent:
5382 case OO_Tilde:
5383 case OO_Exclaim:
5384 case OO_Equal:
5385 case OO_Less:
5386 case OO_Greater:
5387 case OO_LessEqual:
5388 case OO_GreaterEqual:
5389 case OO_PlusEqual:
5390 case OO_MinusEqual:
5391 case OO_StarEqual:
5392 case OO_SlashEqual:
5393 case OO_PercentEqual:
5394 case OO_CaretEqual:
5395 case OO_AmpEqual:
5396 case OO_PipeEqual:
5397 case OO_LessLess:
5398 case OO_GreaterGreater:
5399 case OO_LessLessEqual:
5400 case OO_GreaterGreaterEqual:
5401 case OO_EqualEqual:
5402 case OO_ExclaimEqual:
5403 case OO_PlusPlus:
5404 case OO_MinusMinus:
5405 case OO_Comma:
5406 case OO_ArrowStar:
5407 case OO_Arrow:
5408 case OO_Call:
5409 case OO_Subscript:
5410 case OO_Conditional:
5411 case NUM_OVERLOADED_OPERATORS:
5412 llvm_unreachable("Unexpected reduction identifier");
5413 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005414 if (auto II = DN.getAsIdentifierInfo()) {
5415 if (II->isStr("max"))
5416 BOK = BO_GT;
5417 else if (II->isStr("min"))
5418 BOK = BO_LT;
5419 }
5420 break;
5421 }
5422 SourceRange ReductionIdRange;
5423 if (ReductionIdScopeSpec.isValid()) {
5424 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5425 }
5426 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5427 if (BOK == BO_Comma) {
5428 // Not allowed reduction identifier is found.
5429 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5430 << ReductionIdRange;
5431 return nullptr;
5432 }
5433
5434 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005435 SmallVector<Expr *, 8> LHSs;
5436 SmallVector<Expr *, 8> RHSs;
5437 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005438 for (auto RefExpr : VarList) {
5439 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5440 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5441 // It will be analyzed later.
5442 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005443 LHSs.push_back(nullptr);
5444 RHSs.push_back(nullptr);
5445 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005446 continue;
5447 }
5448
5449 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5450 RefExpr->isInstantiationDependent() ||
5451 RefExpr->containsUnexpandedParameterPack()) {
5452 // It will be analyzed later.
5453 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005454 LHSs.push_back(nullptr);
5455 RHSs.push_back(nullptr);
5456 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005457 continue;
5458 }
5459
5460 auto ELoc = RefExpr->getExprLoc();
5461 auto ERange = RefExpr->getSourceRange();
5462 // OpenMP [2.1, C/C++]
5463 // A list item is a variable or array section, subject to the restrictions
5464 // specified in Section 2.4 on page 42 and in each of the sections
5465 // describing clauses and directives for which a list appears.
5466 // OpenMP [2.14.3.3, Restrictions, p.1]
5467 // A variable that is part of another variable (as an array or
5468 // structure element) cannot appear in a private clause.
5469 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5470 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5471 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5472 continue;
5473 }
5474 auto D = DE->getDecl();
5475 auto VD = cast<VarDecl>(D);
5476 auto Type = VD->getType();
5477 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5478 // A variable that appears in a private clause must not have an incomplete
5479 // type or a reference type.
5480 if (RequireCompleteType(ELoc, Type,
5481 diag::err_omp_reduction_incomplete_type))
5482 continue;
5483 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5484 // Arrays may not appear in a reduction clause.
5485 if (Type.getNonReferenceType()->isArrayType()) {
5486 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5487 bool IsDecl =
5488 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5489 Diag(VD->getLocation(),
5490 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5491 << VD;
5492 continue;
5493 }
5494 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5495 // A list item that appears in a reduction clause must not be
5496 // const-qualified.
5497 if (Type.getNonReferenceType().isConstant(Context)) {
5498 Diag(ELoc, diag::err_omp_const_variable)
5499 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5500 bool IsDecl =
5501 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5502 Diag(VD->getLocation(),
5503 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5504 << VD;
5505 continue;
5506 }
5507 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5508 // If a list-item is a reference type then it must bind to the same object
5509 // for all threads of the team.
5510 VarDecl *VDDef = VD->getDefinition();
5511 if (Type->isReferenceType() && VDDef) {
5512 DSARefChecker Check(DSAStack);
5513 if (Check.Visit(VDDef->getInit())) {
5514 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5515 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5516 continue;
5517 }
5518 }
5519 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5520 // The type of a list item that appears in a reduction clause must be valid
5521 // for the reduction-identifier. For a max or min reduction in C, the type
5522 // of the list item must be an allowed arithmetic data type: char, int,
5523 // float, double, or _Bool, possibly modified with long, short, signed, or
5524 // unsigned. For a max or min reduction in C++, the type of the list item
5525 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5526 // double, or bool, possibly modified with long, short, signed, or unsigned.
5527 if ((BOK == BO_GT || BOK == BO_LT) &&
5528 !(Type->isScalarType() ||
5529 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5530 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5531 << getLangOpts().CPlusPlus;
5532 bool IsDecl =
5533 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5534 Diag(VD->getLocation(),
5535 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5536 << VD;
5537 continue;
5538 }
5539 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5540 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5541 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5542 bool IsDecl =
5543 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5544 Diag(VD->getLocation(),
5545 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5546 << VD;
5547 continue;
5548 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005549 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5550 // in a Construct]
5551 // Variables with the predetermined data-sharing attributes may not be
5552 // listed in data-sharing attributes clauses, except for the cases
5553 // listed below. For these exceptions only, listing a predetermined
5554 // variable in a data-sharing attribute clause is allowed and overrides
5555 // the variable's predetermined data-sharing attributes.
5556 // OpenMP [2.14.3.6, Restrictions, p.3]
5557 // Any number of reduction clauses can be specified on the directive,
5558 // but a list item can appear only once in the reduction clauses for that
5559 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005560 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005561 if (DVar.CKind == OMPC_reduction) {
5562 Diag(ELoc, diag::err_omp_once_referenced)
5563 << getOpenMPClauseName(OMPC_reduction);
5564 if (DVar.RefExpr) {
5565 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5566 }
5567 } else if (DVar.CKind != OMPC_unknown) {
5568 Diag(ELoc, diag::err_omp_wrong_dsa)
5569 << getOpenMPClauseName(DVar.CKind)
5570 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005571 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005572 continue;
5573 }
5574
5575 // OpenMP [2.14.3.6, Restrictions, p.1]
5576 // A list item that appears in a reduction clause of a worksharing
5577 // construct must be shared in the parallel regions to which any of the
5578 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005579 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005580 if (isOpenMPWorksharingDirective(CurrDir) &&
5581 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005582 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005583 if (DVar.CKind != OMPC_shared) {
5584 Diag(ELoc, diag::err_omp_required_access)
5585 << getOpenMPClauseName(OMPC_reduction)
5586 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005587 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005588 continue;
5589 }
5590 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005591 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00005592 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5593 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005594 // Add initializer for private variable.
5595 Expr *Init = nullptr;
5596 switch (BOK) {
5597 case BO_Add:
5598 case BO_Xor:
5599 case BO_Or:
5600 case BO_LOr:
5601 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5602 if (Type->isScalarType() || Type->isAnyComplexType()) {
5603 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005604 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005605 break;
5606 case BO_Mul:
5607 case BO_LAnd:
5608 if (Type->isScalarType() || Type->isAnyComplexType()) {
5609 // '*' and '&&' reduction ops - initializer is '1'.
5610 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5611 }
5612 break;
5613 case BO_And: {
5614 // '&' reduction op - initializer is '~0'.
5615 QualType OrigType = Type;
5616 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5617 Type = ComplexTy->getElementType();
5618 }
5619 if (Type->isRealFloatingType()) {
5620 llvm::APFloat InitValue =
5621 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5622 /*isIEEE=*/true);
5623 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5624 Type, ELoc);
5625 } else if (Type->isScalarType()) {
5626 auto Size = Context.getTypeSize(Type);
5627 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5628 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5629 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5630 }
5631 if (Init && OrigType->isAnyComplexType()) {
5632 // Init = 0xFFFF + 0xFFFFi;
5633 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5634 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5635 }
5636 Type = OrigType;
5637 break;
5638 }
5639 case BO_LT:
5640 case BO_GT: {
5641 // 'min' reduction op - initializer is 'Largest representable number in
5642 // the reduction list item type'.
5643 // 'max' reduction op - initializer is 'Least representable number in
5644 // the reduction list item type'.
5645 if (Type->isIntegerType() || Type->isPointerType()) {
5646 bool IsSigned = Type->hasSignedIntegerRepresentation();
5647 auto Size = Context.getTypeSize(Type);
5648 QualType IntTy =
5649 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5650 llvm::APInt InitValue =
5651 (BOK != BO_LT)
5652 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5653 : llvm::APInt::getMinValue(Size)
5654 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5655 : llvm::APInt::getMaxValue(Size);
5656 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5657 if (Type->isPointerType()) {
5658 // Cast to pointer type.
5659 auto CastExpr = BuildCStyleCastExpr(
5660 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5661 SourceLocation(), Init);
5662 if (CastExpr.isInvalid())
5663 continue;
5664 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005665 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005666 } else if (Type->isRealFloatingType()) {
5667 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5668 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5669 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5670 Type, ELoc);
5671 }
5672 break;
5673 }
5674 case BO_PtrMemD:
5675 case BO_PtrMemI:
5676 case BO_MulAssign:
5677 case BO_Div:
5678 case BO_Rem:
5679 case BO_Sub:
5680 case BO_Shl:
5681 case BO_Shr:
5682 case BO_LE:
5683 case BO_GE:
5684 case BO_EQ:
5685 case BO_NE:
5686 case BO_AndAssign:
5687 case BO_XorAssign:
5688 case BO_OrAssign:
5689 case BO_Assign:
5690 case BO_AddAssign:
5691 case BO_SubAssign:
5692 case BO_DivAssign:
5693 case BO_RemAssign:
5694 case BO_ShlAssign:
5695 case BO_ShrAssign:
5696 case BO_Comma:
5697 llvm_unreachable("Unexpected reduction operation");
5698 }
5699 if (Init) {
5700 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5701 /*TypeMayContainAuto=*/false);
5702 } else {
5703 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5704 }
5705 if (!RHSVD->hasInit()) {
5706 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5707 << ReductionIdRange;
5708 bool IsDecl =
5709 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5710 Diag(VD->getLocation(),
5711 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5712 << VD;
5713 continue;
5714 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00005715 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5716 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005717 ExprResult ReductionOp =
5718 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5719 LHSDRE, RHSDRE);
5720 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00005721 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005722 ReductionOp =
5723 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5724 BO_Assign, LHSDRE, ReductionOp.get());
5725 } else {
5726 auto *ConditionalOp = new (Context) ConditionalOperator(
5727 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5728 RHSDRE, Type, VK_LValue, OK_Ordinary);
5729 ReductionOp =
5730 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5731 BO_Assign, LHSDRE, ConditionalOp);
5732 }
5733 if (ReductionOp.isUsable()) {
5734 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005735 }
5736 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005737 if (ReductionOp.isInvalid())
5738 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005739
5740 DSAStack->addDSA(VD, DE, OMPC_reduction);
5741 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005742 LHSs.push_back(LHSDRE);
5743 RHSs.push_back(RHSDRE);
5744 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005745 }
5746
5747 if (Vars.empty())
5748 return nullptr;
5749
5750 return OMPReductionClause::Create(
5751 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005752 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5753 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005754}
5755
Alexander Musman8dba6642014-04-22 13:09:42 +00005756OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5757 SourceLocation StartLoc,
5758 SourceLocation LParenLoc,
5759 SourceLocation ColonLoc,
5760 SourceLocation EndLoc) {
5761 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005762 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005763 for (auto &RefExpr : VarList) {
5764 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5765 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005766 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005767 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005768 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005769 continue;
5770 }
5771
5772 // OpenMP [2.14.3.7, linear clause]
5773 // A list item that appears in a linear clause is subject to the private
5774 // clause semantics described in Section 2.14.3.3 on page 159 except as
5775 // noted. In addition, the value of the new list item on each iteration
5776 // of the associated loop(s) corresponds to the value of the original
5777 // list item before entering the construct plus the logical number of
5778 // the iteration times linear-step.
5779
Alexey Bataeved09d242014-05-28 05:53:51 +00005780 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005781 // OpenMP [2.1, C/C++]
5782 // A list item is a variable name.
5783 // OpenMP [2.14.3.3, Restrictions, p.1]
5784 // A variable that is part of another variable (as an array or
5785 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005786 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005787 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005788 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005789 continue;
5790 }
5791
5792 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5793
5794 // OpenMP [2.14.3.7, linear clause]
5795 // A list-item cannot appear in more than one linear clause.
5796 // A list-item that appears in a linear clause cannot appear in any
5797 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005798 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005799 if (DVar.RefExpr) {
5800 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5801 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005802 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005803 continue;
5804 }
5805
5806 QualType QType = VD->getType();
5807 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5808 // It will be analyzed later.
5809 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005810 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005811 continue;
5812 }
5813
5814 // A variable must not have an incomplete type or a reference type.
5815 if (RequireCompleteType(ELoc, QType,
5816 diag::err_omp_linear_incomplete_type)) {
5817 continue;
5818 }
5819 if (QType->isReferenceType()) {
5820 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5821 << getOpenMPClauseName(OMPC_linear) << QType;
5822 bool IsDecl =
5823 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5824 Diag(VD->getLocation(),
5825 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5826 << VD;
5827 continue;
5828 }
5829
5830 // A list item must not be const-qualified.
5831 if (QType.isConstant(Context)) {
5832 Diag(ELoc, diag::err_omp_const_variable)
5833 << getOpenMPClauseName(OMPC_linear);
5834 bool IsDecl =
5835 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5836 Diag(VD->getLocation(),
5837 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5838 << VD;
5839 continue;
5840 }
5841
5842 // A list item must be of integral or pointer type.
5843 QType = QType.getUnqualifiedType().getCanonicalType();
5844 const Type *Ty = QType.getTypePtrOrNull();
5845 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5846 !Ty->isPointerType())) {
5847 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5848 bool IsDecl =
5849 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5850 Diag(VD->getLocation(),
5851 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5852 << VD;
5853 continue;
5854 }
5855
Alexander Musman3276a272015-03-21 10:12:56 +00005856 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005857 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexander Musman3276a272015-03-21 10:12:56 +00005858 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5859 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005860 auto InitRef = buildDeclRefExpr(
5861 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00005862 DSAStack->addDSA(VD, DE, OMPC_linear);
5863 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005864 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005865 }
5866
5867 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005868 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005869
5870 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005871 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005872 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5873 !Step->isInstantiationDependent() &&
5874 !Step->containsUnexpandedParameterPack()) {
5875 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005876 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005877 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005878 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005879 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005880
Alexander Musman3276a272015-03-21 10:12:56 +00005881 // Build var to save the step value.
5882 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005883 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00005884 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005885 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00005886 ExprResult CalcStep =
5887 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5888
Alexander Musman8dba6642014-04-22 13:09:42 +00005889 // Warn about zero linear step (it would be probably better specified as
5890 // making corresponding variables 'const').
5891 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005892 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5893 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005894 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5895 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005896 if (!IsConstant && CalcStep.isUsable()) {
5897 // Calculate the step beforehand instead of doing this on each iteration.
5898 // (This is not used if the number of iterations may be kfold-ed).
5899 CalcStepExpr = CalcStep.get();
5900 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005901 }
5902
5903 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005904 Vars, Inits, StepExpr, CalcStepExpr);
5905}
5906
5907static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5908 Expr *NumIterations, Sema &SemaRef,
5909 Scope *S) {
5910 // Walk the vars and build update/final expressions for the CodeGen.
5911 SmallVector<Expr *, 8> Updates;
5912 SmallVector<Expr *, 8> Finals;
5913 Expr *Step = Clause.getStep();
5914 Expr *CalcStep = Clause.getCalcStep();
5915 // OpenMP [2.14.3.7, linear clause]
5916 // If linear-step is not specified it is assumed to be 1.
5917 if (Step == nullptr)
5918 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5919 else if (CalcStep)
5920 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5921 bool HasErrors = false;
5922 auto CurInit = Clause.inits().begin();
5923 for (auto &RefExpr : Clause.varlists()) {
5924 Expr *InitExpr = *CurInit;
5925
5926 // Build privatized reference to the current linear var.
5927 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005928 auto PrivateRef =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005929 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
5930 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
5931 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00005932
5933 // Build update: Var = InitExpr + IV * Step
5934 ExprResult Update =
5935 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5936 InitExpr, IV, Step, /* Subtract */ false);
5937 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5938
5939 // Build final: Var = InitExpr + NumIterations * Step
5940 ExprResult Final =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005941 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5942 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexander Musman3276a272015-03-21 10:12:56 +00005943 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5944 if (!Update.isUsable() || !Final.isUsable()) {
5945 Updates.push_back(nullptr);
5946 Finals.push_back(nullptr);
5947 HasErrors = true;
5948 } else {
5949 Updates.push_back(Update.get());
5950 Finals.push_back(Final.get());
5951 }
5952 ++CurInit;
5953 }
5954 Clause.setUpdates(Updates);
5955 Clause.setFinals(Finals);
5956 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005957}
5958
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005959OMPClause *Sema::ActOnOpenMPAlignedClause(
5960 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5961 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5962
5963 SmallVector<Expr *, 8> Vars;
5964 for (auto &RefExpr : VarList) {
5965 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5966 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5967 // It will be analyzed later.
5968 Vars.push_back(RefExpr);
5969 continue;
5970 }
5971
5972 SourceLocation ELoc = RefExpr->getExprLoc();
5973 // OpenMP [2.1, C/C++]
5974 // A list item is a variable name.
5975 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5976 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5977 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5978 continue;
5979 }
5980
5981 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5982
5983 // OpenMP [2.8.1, simd construct, Restrictions]
5984 // The type of list items appearing in the aligned clause must be
5985 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005986 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005987 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005988 const Type *Ty = QType.getTypePtrOrNull();
5989 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5990 !Ty->isPointerType())) {
5991 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5992 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5993 bool IsDecl =
5994 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5995 Diag(VD->getLocation(),
5996 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5997 << VD;
5998 continue;
5999 }
6000
6001 // OpenMP [2.8.1, simd construct, Restrictions]
6002 // A list-item cannot appear in more than one aligned clause.
6003 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6004 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6005 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6006 << getOpenMPClauseName(OMPC_aligned);
6007 continue;
6008 }
6009
6010 Vars.push_back(DE);
6011 }
6012
6013 // OpenMP [2.8.1, simd construct, Description]
6014 // The parameter of the aligned clause, alignment, must be a constant
6015 // positive integer expression.
6016 // If no optional parameter is specified, implementation-defined default
6017 // alignments for SIMD instructions on the target platforms are assumed.
6018 if (Alignment != nullptr) {
6019 ExprResult AlignResult =
6020 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6021 if (AlignResult.isInvalid())
6022 return nullptr;
6023 Alignment = AlignResult.get();
6024 }
6025 if (Vars.empty())
6026 return nullptr;
6027
6028 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6029 EndLoc, Vars, Alignment);
6030}
6031
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006032OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6033 SourceLocation StartLoc,
6034 SourceLocation LParenLoc,
6035 SourceLocation EndLoc) {
6036 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006037 SmallVector<Expr *, 8> SrcExprs;
6038 SmallVector<Expr *, 8> DstExprs;
6039 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00006040 for (auto &RefExpr : VarList) {
6041 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6042 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006043 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006044 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006045 SrcExprs.push_back(nullptr);
6046 DstExprs.push_back(nullptr);
6047 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006048 continue;
6049 }
6050
Alexey Bataeved09d242014-05-28 05:53:51 +00006051 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006052 // OpenMP [2.1, C/C++]
6053 // A list item is a variable name.
6054 // OpenMP [2.14.4.1, Restrictions, p.1]
6055 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00006056 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006057 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006058 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006059 continue;
6060 }
6061
6062 Decl *D = DE->getDecl();
6063 VarDecl *VD = cast<VarDecl>(D);
6064
6065 QualType Type = VD->getType();
6066 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6067 // It will be analyzed later.
6068 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006069 SrcExprs.push_back(nullptr);
6070 DstExprs.push_back(nullptr);
6071 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006072 continue;
6073 }
6074
6075 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6076 // A list item that appears in a copyin clause must be threadprivate.
6077 if (!DSAStack->isThreadPrivate(VD)) {
6078 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00006079 << getOpenMPClauseName(OMPC_copyin)
6080 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006081 continue;
6082 }
6083
6084 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6085 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00006086 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006087 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006088 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006089 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006090 ElemType.getUnqualifiedType(), ".copyin.src");
Alexey Bataev39f915b82015-05-08 10:41:21 +00006091 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006092 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6093 auto *DstVD =
6094 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006095 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006096 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006097 // For arrays generate assignment operation for single element and replace
6098 // it by the original array element in CodeGen.
6099 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6100 PseudoDstExpr, PseudoSrcExpr);
6101 if (AssignmentOp.isInvalid())
6102 continue;
6103 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6104 /*DiscardedValue=*/true);
6105 if (AssignmentOp.isInvalid())
6106 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006107
6108 DSAStack->addDSA(VD, DE, OMPC_copyin);
6109 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006110 SrcExprs.push_back(PseudoSrcExpr);
6111 DstExprs.push_back(PseudoDstExpr);
6112 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006113 }
6114
Alexey Bataeved09d242014-05-28 05:53:51 +00006115 if (Vars.empty())
6116 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006117
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006118 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6119 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006120}
6121
Alexey Bataevbae9a792014-06-27 10:37:06 +00006122OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6123 SourceLocation StartLoc,
6124 SourceLocation LParenLoc,
6125 SourceLocation EndLoc) {
6126 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006127 SmallVector<Expr *, 8> SrcExprs;
6128 SmallVector<Expr *, 8> DstExprs;
6129 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006130 for (auto &RefExpr : VarList) {
6131 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6132 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6133 // It will be analyzed later.
6134 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006135 SrcExprs.push_back(nullptr);
6136 DstExprs.push_back(nullptr);
6137 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006138 continue;
6139 }
6140
6141 SourceLocation ELoc = RefExpr->getExprLoc();
6142 // OpenMP [2.1, C/C++]
6143 // A list item is a variable name.
6144 // OpenMP [2.14.4.1, Restrictions, p.1]
6145 // A list item that appears in a copyin clause must be threadprivate.
6146 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6147 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6148 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6149 continue;
6150 }
6151
6152 Decl *D = DE->getDecl();
6153 VarDecl *VD = cast<VarDecl>(D);
6154
6155 QualType Type = VD->getType();
6156 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6157 // It will be analyzed later.
6158 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006159 SrcExprs.push_back(nullptr);
6160 DstExprs.push_back(nullptr);
6161 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006162 continue;
6163 }
6164
6165 // OpenMP [2.14.4.2, Restrictions, p.2]
6166 // A list item that appears in a copyprivate clause may not appear in a
6167 // private or firstprivate clause on the single construct.
6168 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006169 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006170 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6171 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006172 Diag(ELoc, diag::err_omp_wrong_dsa)
6173 << getOpenMPClauseName(DVar.CKind)
6174 << getOpenMPClauseName(OMPC_copyprivate);
6175 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6176 continue;
6177 }
6178
6179 // OpenMP [2.11.4.2, Restrictions, p.1]
6180 // All list items that appear in a copyprivate clause must be either
6181 // threadprivate or private in the enclosing context.
6182 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006183 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006184 if (DVar.CKind == OMPC_shared) {
6185 Diag(ELoc, diag::err_omp_required_access)
6186 << getOpenMPClauseName(OMPC_copyprivate)
6187 << "threadprivate or private in the enclosing context";
6188 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6189 continue;
6190 }
6191 }
6192 }
6193
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006194 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00006195 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006196 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006197 << getOpenMPClauseName(OMPC_copyprivate) << Type
6198 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00006199 bool IsDecl =
6200 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6201 Diag(VD->getLocation(),
6202 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6203 << VD;
6204 continue;
6205 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006206
Alexey Bataevbae9a792014-06-27 10:37:06 +00006207 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6208 // A variable of class type (or array thereof) that appears in a
6209 // copyin clause requires an accessible, unambiguous copy assignment
6210 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006211 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6212 auto *SrcVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006213 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006214 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006215 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00006216 auto *DstVD =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006217 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
Alexey Bataev420d45b2015-04-14 05:11:24 +00006218 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006219 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00006220 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6221 PseudoDstExpr, PseudoSrcExpr);
6222 if (AssignmentOp.isInvalid())
6223 continue;
6224 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6225 /*DiscardedValue=*/true);
6226 if (AssignmentOp.isInvalid())
6227 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006228
6229 // No need to mark vars as copyprivate, they are already threadprivate or
6230 // implicitly private.
6231 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006232 SrcExprs.push_back(PseudoSrcExpr);
6233 DstExprs.push_back(PseudoDstExpr);
6234 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006235 }
6236
6237 if (Vars.empty())
6238 return nullptr;
6239
Alexey Bataeva63048e2015-03-23 06:18:07 +00006240 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6241 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006242}
6243
Alexey Bataev6125da92014-07-21 11:26:11 +00006244OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6245 SourceLocation StartLoc,
6246 SourceLocation LParenLoc,
6247 SourceLocation EndLoc) {
6248 if (VarList.empty())
6249 return nullptr;
6250
6251 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6252}
Alexey Bataevdea47612014-07-23 07:46:59 +00006253