blob: 67fa678db3e12e1d99edd3c31624c5bce8cf45ba [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 Bataev7ff55242014-06-19 09:13:45 +0000117 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
119 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
120
121 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000122
123 /// \brief Checks if the variable is a local for OpenMP region.
124 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000125
Alexey Bataev758e55e2013-09-06 18:03:48 +0000126public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000127 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000130 Scope *CurScope, SourceLocation Loc) {
131 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
132 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000133 }
134
135 void pop() {
136 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
137 Stack.pop_back();
138 }
139
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000140 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000141 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000142 /// for diagnostics.
143 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
144
Alexey Bataev9c821032015-04-30 04:23:23 +0000145 /// \brief Register specified variable as loop control variable.
146 void addLoopControlVariable(VarDecl *D);
147 /// \brief Check if the specified variable is a loop control variable for
148 /// current region.
149 bool isLoopControlVariable(VarDecl *D);
150
Alexey Bataev758e55e2013-09-06 18:03:48 +0000151 /// \brief Adds explicit data sharing attribute to the specified declaration.
152 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
153
Alexey Bataev758e55e2013-09-06 18:03:48 +0000154 /// \brief Returns data sharing attributes from top of the stack for the
155 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000156 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000157 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000158 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000159 /// \brief Checks if the specified variables has data-sharing attributes which
160 /// match specified \a CPred predicate in any directive which matches \a DPred
161 /// predicate.
162 template <class ClausesPredicate, class DirectivesPredicate>
163 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000164 DirectivesPredicate DPred, 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 innermost directive which
167 /// matches \a DPred predicate.
168 template <class ClausesPredicate, class DirectivesPredicate>
169 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000170 DirectivesPredicate DPred,
171 bool FromParent);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000172 /// \brief Finds a directive which matches specified \a DPred predicate.
173 template <class NamedDirectivesPredicate>
174 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000175
Alexey Bataev758e55e2013-09-06 18:03:48 +0000176 /// \brief Returns currently analyzed directive.
177 OpenMPDirectiveKind getCurrentDirective() const {
178 return Stack.back().Directive;
179 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000180 /// \brief Returns parent directive.
181 OpenMPDirectiveKind getParentDirective() const {
182 if (Stack.size() > 2)
183 return Stack[Stack.size() - 2].Directive;
184 return OMPD_unknown;
185 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186
187 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000188 void setDefaultDSANone(SourceLocation Loc) {
189 Stack.back().DefaultAttr = DSA_none;
190 Stack.back().DefaultAttrLoc = Loc;
191 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000192 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000193 void setDefaultDSAShared(SourceLocation Loc) {
194 Stack.back().DefaultAttr = DSA_shared;
195 Stack.back().DefaultAttrLoc = Loc;
196 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197
198 DefaultDataSharingAttributes getDefaultDSA() const {
199 return Stack.back().DefaultAttr;
200 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000201 SourceLocation getDefaultDSALocation() const {
202 return Stack.back().DefaultAttrLoc;
203 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000204
Alexey Bataevf29276e2014-06-18 04:14:57 +0000205 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000206 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000207 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000208 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000209 }
210
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000211 /// \brief Marks current region as ordered (it has an 'ordered' clause).
212 void setOrderedRegion(bool IsOrdered = true) {
213 Stack.back().OrderedRegion = IsOrdered;
214 }
215 /// \brief Returns true, if parent region is ordered (has associated
216 /// 'ordered' clause), false - otherwise.
217 bool isParentOrderedRegion() const {
218 if (Stack.size() > 2)
219 return Stack[Stack.size() - 2].OrderedRegion;
220 return false;
221 }
222
Alexey Bataev9c821032015-04-30 04:23:23 +0000223 /// \brief Set collapse value for the region.
224 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
225 /// \brief Return collapse value for region.
226 unsigned getCollapseNumber() const {
227 return Stack.back().CollapseNumber;
228 }
229
Alexey Bataev13314bf2014-10-09 04:18:56 +0000230 /// \brief Marks current target region as one with closely nested teams
231 /// region.
232 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
233 if (Stack.size() > 2)
234 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
235 }
236 /// \brief Returns true, if current region has closely nested teams region.
237 bool hasInnerTeamsRegion() const {
238 return getInnerTeamsRegionLoc().isValid();
239 }
240 /// \brief Returns location of the nested teams region (if any).
241 SourceLocation getInnerTeamsRegionLoc() const {
242 if (Stack.size() > 1)
243 return Stack.back().InnerTeamsRegionLoc;
244 return SourceLocation();
245 }
246
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000247 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000248 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000249 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000250};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000251bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
252 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000253 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000254}
Alexey Bataeved09d242014-05-28 05:53:51 +0000255} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000256
257DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
258 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000259 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000260 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000261 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000262 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
263 // in a region but not in construct]
264 // File-scope or namespace-scope variables referenced in called routines
265 // in the region are shared unless they appear in a threadprivate
266 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000267 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000268 DVar.CKind = OMPC_shared;
269
270 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
271 // in a region but not in construct]
272 // Variables with static storage duration that are declared in called
273 // routines in the region are shared.
274 if (D->hasGlobalStorage())
275 DVar.CKind = OMPC_shared;
276
Alexey Bataev758e55e2013-09-06 18:03:48 +0000277 return DVar;
278 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000279
Alexey Bataev758e55e2013-09-06 18:03:48 +0000280 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000281 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
282 // in a Construct, C/C++, predetermined, p.1]
283 // Variables with automatic storage duration that are declared in a scope
284 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000285 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
286 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
287 DVar.CKind = OMPC_private;
288 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000289 }
290
Alexey Bataev758e55e2013-09-06 18:03:48 +0000291 // Explicitly specified attributes and local variables with predetermined
292 // attributes.
293 if (Iter->SharingMap.count(D)) {
294 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
295 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000296 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000297 return DVar;
298 }
299
300 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
301 // in a Construct, C/C++, implicitly determined, p.1]
302 // In a parallel or task construct, the data-sharing attributes of these
303 // variables are determined by the default clause, if present.
304 switch (Iter->DefaultAttr) {
305 case DSA_shared:
306 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000307 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000308 return DVar;
309 case DSA_none:
310 return DVar;
311 case DSA_unspecified:
312 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
313 // in a Construct, implicitly determined, p.2]
314 // In a parallel construct, if no default clause is present, these
315 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000316 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000317 if (isOpenMPParallelDirective(DVar.DKind) ||
318 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000319 DVar.CKind = OMPC_shared;
320 return DVar;
321 }
322
323 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
324 // in a Construct, implicitly determined, p.4]
325 // In a task construct, if no default clause is present, a variable that in
326 // the enclosing context is determined to be shared by all implicit tasks
327 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000328 if (DVar.DKind == OMPD_task) {
329 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000330 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000331 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000332 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
333 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000334 // in a Construct, implicitly determined, p.6]
335 // In a task construct, if no default clause is present, a variable
336 // whose data-sharing attribute is not determined by the rules above is
337 // firstprivate.
338 DVarTemp = getDSA(I, D);
339 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000340 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000341 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000342 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000343 return DVar;
344 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000345 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000346 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000347 }
348 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000349 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000350 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000351 return DVar;
352 }
353 }
354 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
355 // in a Construct, implicitly determined, p.3]
356 // For constructs other than task, if no default clause is present, these
357 // variables inherit their data-sharing attributes from the enclosing
358 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000359 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000360}
361
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000362DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
363 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000364 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000365 auto It = Stack.back().AlignedMap.find(D);
366 if (It == Stack.back().AlignedMap.end()) {
367 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
368 Stack.back().AlignedMap[D] = NewDE;
369 return nullptr;
370 } else {
371 assert(It->second && "Unexpected nullptr expr in the aligned map");
372 return It->second;
373 }
374 return nullptr;
375}
376
Alexey Bataev9c821032015-04-30 04:23:23 +0000377void DSAStackTy::addLoopControlVariable(VarDecl *D) {
378 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
379 D = D->getCanonicalDecl();
380 Stack.back().LCVSet.insert(D);
381}
382
383bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
384 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
385 D = D->getCanonicalDecl();
386 return Stack.back().LCVSet.count(D) > 0;
387}
388
Alexey Bataev758e55e2013-09-06 18:03:48 +0000389void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000390 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000391 if (A == OMPC_threadprivate) {
392 Stack[0].SharingMap[D].Attributes = A;
393 Stack[0].SharingMap[D].RefExpr = E;
394 } else {
395 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
396 Stack.back().SharingMap[D].Attributes = A;
397 Stack.back().SharingMap[D].RefExpr = E;
398 }
399}
400
Alexey Bataeved09d242014-05-28 05:53:51 +0000401bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000402 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000403 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000404 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000405 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000406 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000407 ++I;
408 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000409 if (I == E)
410 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000411 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000412 Scope *CurScope = getCurScope();
413 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000414 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000415 }
416 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000417 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000418 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000419}
420
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000421DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000422 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000423 DSAVarData DVar;
424
425 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
426 // in a Construct, C/C++, predetermined, p.1]
427 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev26a39242015-01-13 03:35:30 +0000428 if (D->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000429 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
430 !D->isLocalVarDecl())) {
Alexey Bataevf2453a02015-05-06 07:25:08 +0000431 addDSA(D,
432 DeclRefExpr::Create(SemaRef.getASTContext(),
433 NestedNameSpecifierLoc(), SourceLocation(), D,
434 /*RefersToEnclosingVariableOrCapture=*/false,
435 D->getLocation(),
436 D->getType().getNonReferenceType(), VK_LValue),
437 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000438 }
439 if (Stack[0].SharingMap.count(D)) {
440 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
441 DVar.CKind = OMPC_threadprivate;
442 return DVar;
443 }
444
445 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
446 // in a Construct, C/C++, predetermined, p.1]
447 // Variables with automatic storage duration that are declared in a scope
448 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000449 OpenMPDirectiveKind Kind =
450 FromParent ? getParentDirective() : getCurrentDirective();
451 auto StartI = std::next(Stack.rbegin());
452 auto EndI = std::prev(Stack.rend());
453 if (FromParent && StartI != EndI) {
454 StartI = std::next(StartI);
455 }
456 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000457 if (isOpenMPLocal(D, StartI) &&
458 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
459 D->getStorageClass() == SC_None)) ||
460 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000461 DVar.CKind = OMPC_private;
462 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000463 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000464
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000465 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
466 // in a Construct, C/C++, predetermined, p.4]
467 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000468 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
469 // in a Construct, C/C++, predetermined, p.7]
470 // Variables with static storage duration that are declared in a scope
471 // inside the construct are shared.
Alexey Bataev42971a32015-01-20 07:03:46 +0000472 if (D->isStaticDataMember() || D->isStaticLocal()) {
473 DSAVarData DVarTemp =
474 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
475 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
476 return DVar;
477
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000478 DVar.CKind = OMPC_shared;
479 return DVar;
480 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000481 }
482
483 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000484 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
Alexey Bataev758e55e2013-09-06 18:03:48 +0000485 while (Type->isArrayType()) {
486 QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
487 Type = ElemType.getNonReferenceType().getCanonicalType();
488 }
489 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
490 // in a Construct, C/C++, predetermined, p.6]
491 // Variables with const qualified type having no mutable member are
492 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000493 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000494 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000495 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000496 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // Variables with const-qualified type having no mutable member may be
498 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000499 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
500 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000501 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
502 return DVar;
503
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 DVar.CKind = OMPC_shared;
505 return DVar;
506 }
507
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 // Explicitly specified attributes and local variables with predetermined
509 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000510 auto I = std::prev(StartI);
511 if (I->SharingMap.count(D)) {
512 DVar.RefExpr = I->SharingMap[D].RefExpr;
513 DVar.CKind = I->SharingMap[D].Attributes;
514 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000515 }
516
517 return DVar;
518}
519
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000520DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000521 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000522 auto StartI = Stack.rbegin();
523 auto EndI = std::prev(Stack.rend());
524 if (FromParent && StartI != EndI) {
525 StartI = std::next(StartI);
526 }
527 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000528}
529
Alexey Bataevf29276e2014-06-18 04:14:57 +0000530template <class ClausesPredicate, class DirectivesPredicate>
531DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000532 DirectivesPredicate DPred,
533 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000534 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000535 auto StartI = std::next(Stack.rbegin());
536 auto EndI = std::prev(Stack.rend());
537 if (FromParent && StartI != EndI) {
538 StartI = std::next(StartI);
539 }
540 for (auto I = StartI, EE = EndI; I != EE; ++I) {
541 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000542 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000543 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000544 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000545 return DVar;
546 }
547 return DSAVarData();
548}
549
Alexey Bataevf29276e2014-06-18 04:14:57 +0000550template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000551DSAStackTy::DSAVarData
552DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
553 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000554 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000555 auto StartI = std::next(Stack.rbegin());
556 auto EndI = std::prev(Stack.rend());
557 if (FromParent && StartI != EndI) {
558 StartI = std::next(StartI);
559 }
560 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000561 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000562 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000563 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000564 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000565 return DVar;
566 return DSAVarData();
567 }
568 return DSAVarData();
569}
570
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000571template <class NamedDirectivesPredicate>
572bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
573 auto StartI = std::next(Stack.rbegin());
574 auto EndI = std::prev(Stack.rend());
575 if (FromParent && StartI != EndI) {
576 StartI = std::next(StartI);
577 }
578 for (auto I = StartI, EE = EndI; I != EE; ++I) {
579 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
580 return true;
581 }
582 return false;
583}
584
Alexey Bataev758e55e2013-09-06 18:03:48 +0000585void Sema::InitDataSharingAttributesStack() {
586 VarDataSharingAttributesStack = new DSAStackTy(*this);
587}
588
589#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
590
Alexey Bataevf841bd92014-12-16 07:00:22 +0000591bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
592 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000593 VD = VD->getCanonicalDecl();
Alexey Bataevf841bd92014-12-16 07:00:22 +0000594 if (DSAStack->getCurrentDirective() != OMPD_unknown) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000595 if (DSAStack->isLoopControlVariable(VD))
596 return true;
Alexey Bataevf841bd92014-12-16 07:00:22 +0000597 auto DVarPrivate = DSAStack->getTopDSA(VD, /*FromParent=*/false);
598 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
599 return true;
600 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
601 /*FromParent=*/false);
602 return DVarPrivate.CKind != OMPC_unknown;
603 }
604 return false;
605}
606
Alexey Bataeved09d242014-05-28 05:53:51 +0000607void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000608
609void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
610 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000611 Scope *CurScope, SourceLocation Loc) {
612 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000613 PushExpressionEvaluationContext(PotentiallyEvaluated);
614}
615
616void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000617 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
618 // A variable of class type (or array thereof) that appears in a lastprivate
619 // clause requires an accessible, unambiguous default constructor for the
620 // class type, unless the list item is also specified in a firstprivate
621 // clause.
622 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000623 for (auto *C : D->clauses()) {
624 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
625 SmallVector<Expr *, 8> PrivateCopies;
626 for (auto *DE : Clause->varlists()) {
627 if (DE->isValueDependent() || DE->isTypeDependent()) {
628 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000629 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000630 }
631 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000632 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000633 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000634 // Generate helper private variable and initialize it with the
635 // default value. The address of the original variable is replaced
636 // by the address of the new private variable in CodeGen. This new
637 // variable is not added to IdResolver, so the code in the OpenMP
638 // region uses original variable for proper diagnostics.
639 auto *VDPrivate = VarDecl::Create(
640 Context, CurContext, DE->getLocStart(), DE->getExprLoc(),
641 VD->getIdentifier(), VD->getType(), VD->getTypeSourceInfo(),
642 SC_Auto);
643 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
644 if (VDPrivate->isInvalidDecl())
645 continue;
646 CurContext->addDecl(VDPrivate);
647 PrivateCopies.push_back(DeclRefExpr::Create(
648 Context, NestedNameSpecifierLoc(), SourceLocation(), VDPrivate,
649 /*RefersToEnclosingVariableOrCapture=*/false, SourceLocation(),
650 DE->getType(), VK_LValue));
651 } else {
652 // The variable is also a firstprivate, so initialization sequence
653 // for private copy is generated already.
654 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000655 }
656 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000657 // Set initializers to private copies if no errors were found.
658 if (PrivateCopies.size() == Clause->varlist_size()) {
659 Clause->setPrivateCopies(PrivateCopies);
660 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000661 }
662 }
663 }
664
Alexey Bataev758e55e2013-09-06 18:03:48 +0000665 DSAStack->pop();
666 DiscardCleanupsInEvaluationContext();
667 PopExpressionEvaluationContext();
668}
669
Alexander Musman3276a272015-03-21 10:12:56 +0000670static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
671 Expr *NumIterations, Sema &SemaRef,
672 Scope *S);
673
Alexey Bataeva769e072013-03-22 06:34:35 +0000674namespace {
675
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000676class VarDeclFilterCCC : public CorrectionCandidateCallback {
677private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000678 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000679
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000680public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000681 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000682 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000683 NamedDecl *ND = Candidate.getCorrectionDecl();
684 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
685 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000686 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
687 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000688 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000689 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000690 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000691};
Alexey Bataeved09d242014-05-28 05:53:51 +0000692} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000693
694ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
695 CXXScopeSpec &ScopeSpec,
696 const DeclarationNameInfo &Id) {
697 LookupResult Lookup(*this, Id, LookupOrdinaryName);
698 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
699
700 if (Lookup.isAmbiguous())
701 return ExprError();
702
703 VarDecl *VD;
704 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000705 if (TypoCorrection Corrected = CorrectTypo(
706 Id, LookupOrdinaryName, CurScope, nullptr,
707 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000708 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000709 PDiag(Lookup.empty()
710 ? diag::err_undeclared_var_use_suggest
711 : diag::err_omp_expected_var_arg_suggest)
712 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000713 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000714 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000715 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
716 : diag::err_omp_expected_var_arg)
717 << Id.getName();
718 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000719 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000720 } else {
721 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000722 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000723 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
724 return ExprError();
725 }
726 }
727 Lookup.suppressDiagnostics();
728
729 // OpenMP [2.9.2, Syntax, C/C++]
730 // Variables must be file-scope, namespace-scope, or static block-scope.
731 if (!VD->hasGlobalStorage()) {
732 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000733 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
734 bool IsDecl =
735 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000736 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000737 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
738 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000739 return ExprError();
740 }
741
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000742 VarDecl *CanonicalVD = VD->getCanonicalDecl();
743 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000744 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
745 // A threadprivate directive for file-scope variables must appear outside
746 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000747 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
748 !getCurLexicalContext()->isTranslationUnit()) {
749 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000750 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
751 bool IsDecl =
752 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
753 Diag(VD->getLocation(),
754 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
755 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000756 return ExprError();
757 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000758 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
759 // A threadprivate directive for static class member variables must appear
760 // in the class definition, in the same scope in which the member
761 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000762 if (CanonicalVD->isStaticDataMember() &&
763 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
764 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
766 bool IsDecl =
767 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
768 Diag(VD->getLocation(),
769 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
770 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000771 return ExprError();
772 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000773 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
774 // A threadprivate directive for namespace-scope variables must appear
775 // outside any definition or declaration other than the namespace
776 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000777 if (CanonicalVD->getDeclContext()->isNamespace() &&
778 (!getCurLexicalContext()->isFileContext() ||
779 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
780 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000781 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
782 bool IsDecl =
783 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
784 Diag(VD->getLocation(),
785 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
786 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000787 return ExprError();
788 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000789 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
790 // A threadprivate directive for static block-scope variables must appear
791 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000792 if (CanonicalVD->isStaticLocal() && CurScope &&
793 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000794 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000795 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
796 bool IsDecl =
797 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
798 Diag(VD->getLocation(),
799 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
800 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000801 return ExprError();
802 }
803
804 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
805 // A threadprivate directive must lexically precede all references to any
806 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000807 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000808 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000809 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000810 return ExprError();
811 }
812
813 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataevd178ad42014-03-07 08:03:37 +0000814 ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000815 return DE;
816}
817
Alexey Bataeved09d242014-05-28 05:53:51 +0000818Sema::DeclGroupPtrTy
819Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
820 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000821 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000822 CurContext->addDecl(D);
823 return DeclGroupPtrTy::make(DeclGroupRef(D));
824 }
825 return DeclGroupPtrTy();
826}
827
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000828namespace {
829class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
830 Sema &SemaRef;
831
832public:
833 bool VisitDeclRefExpr(const DeclRefExpr *E) {
834 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
835 if (VD->hasLocalStorage()) {
836 SemaRef.Diag(E->getLocStart(),
837 diag::err_omp_local_var_in_threadprivate_init)
838 << E->getSourceRange();
839 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
840 << VD << VD->getSourceRange();
841 return true;
842 }
843 }
844 return false;
845 }
846 bool VisitStmt(const Stmt *S) {
847 for (auto Child : S->children()) {
848 if (Child && Visit(Child))
849 return true;
850 }
851 return false;
852 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000853 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000854};
855} // namespace
856
Alexey Bataeved09d242014-05-28 05:53:51 +0000857OMPThreadPrivateDecl *
858Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000859 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000860 for (auto &RefExpr : VarList) {
861 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000862 VarDecl *VD = cast<VarDecl>(DE->getDecl());
863 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000864
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000865 QualType QType = VD->getType();
866 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
867 // It will be analyzed later.
868 Vars.push_back(DE);
869 continue;
870 }
871
Alexey Bataeva769e072013-03-22 06:34:35 +0000872 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
873 // A threadprivate variable must not have an incomplete type.
874 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000875 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000876 continue;
877 }
878
879 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
880 // A threadprivate variable must not have a reference type.
881 if (VD->getType()->isReferenceType()) {
882 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000883 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
884 bool IsDecl =
885 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
886 Diag(VD->getLocation(),
887 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
888 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000889 continue;
890 }
891
Richard Smithfd3834f2013-04-13 02:43:54 +0000892 // Check if this is a TLS variable.
Alexey Bataev26a39242015-01-13 03:35:30 +0000893 if (VD->getTLSKind() != VarDecl::TLS_None ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000894 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
895 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +0000896 Diag(ILoc, diag::err_omp_var_thread_local)
897 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +0000898 bool IsDecl =
899 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
900 Diag(VD->getLocation(),
901 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
902 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000903 continue;
904 }
905
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000906 // Check if initial value of threadprivate variable reference variable with
907 // local storage (it is not supported by runtime).
908 if (auto Init = VD->getAnyInitializer()) {
909 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000910 if (Checker.Visit(Init))
911 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000912 }
913
Alexey Bataeved09d242014-05-28 05:53:51 +0000914 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +0000915 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +0000916 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
917 Context, SourceRange(Loc, Loc)));
918 if (auto *ML = Context.getASTMutationListener())
919 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +0000920 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000921 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000922 if (!Vars.empty()) {
923 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
924 Vars);
925 D->setAccess(AS_public);
926 }
927 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +0000928}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000929
Alexey Bataev7ff55242014-06-19 09:13:45 +0000930static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
931 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
932 bool IsLoopIterVar = false) {
933 if (DVar.RefExpr) {
934 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
935 << getOpenMPClauseName(DVar.CKind);
936 return;
937 }
938 enum {
939 PDSA_StaticMemberShared,
940 PDSA_StaticLocalVarShared,
941 PDSA_LoopIterVarPrivate,
942 PDSA_LoopIterVarLinear,
943 PDSA_LoopIterVarLastprivate,
944 PDSA_ConstVarShared,
945 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000946 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000947 PDSA_LocalVarPrivate,
948 PDSA_Implicit
949 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000950 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000951 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +0000952 if (IsLoopIterVar) {
953 if (DVar.CKind == OMPC_private)
954 Reason = PDSA_LoopIterVarPrivate;
955 else if (DVar.CKind == OMPC_lastprivate)
956 Reason = PDSA_LoopIterVarLastprivate;
957 else
958 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000959 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
960 Reason = PDSA_TaskVarFirstprivate;
961 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000962 } else if (VD->isStaticLocal())
963 Reason = PDSA_StaticLocalVarShared;
964 else if (VD->isStaticDataMember())
965 Reason = PDSA_StaticMemberShared;
966 else if (VD->isFileVarDecl())
967 Reason = PDSA_GlobalVarShared;
968 else if (VD->getType().isConstant(SemaRef.getASTContext()))
969 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000970 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +0000971 ReportHint = true;
972 Reason = PDSA_LocalVarPrivate;
973 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000974 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000975 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +0000976 << Reason << ReportHint
977 << getOpenMPDirectiveName(Stack->getCurrentDirective());
978 } else if (DVar.ImplicitDSALoc.isValid()) {
979 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
980 << getOpenMPClauseName(DVar.CKind);
981 }
Alexey Bataev7ff55242014-06-19 09:13:45 +0000982}
983
Alexey Bataev758e55e2013-09-06 18:03:48 +0000984namespace {
985class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
986 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000987 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000988 bool ErrorFound;
989 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000990 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +0000991 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +0000992
Alexey Bataev758e55e2013-09-06 18:03:48 +0000993public:
994 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000995 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000996 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +0000997 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
998 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000999
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001000 auto DVar = Stack->getTopDSA(VD, false);
1001 // Check if the variable has explicit DSA set and stop analysis if it so.
1002 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001003
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001004 auto ELoc = E->getExprLoc();
1005 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001006 // The default(none) clause requires that each variable that is referenced
1007 // in the construct, and does not have a predetermined data-sharing
1008 // attribute, must have its data-sharing attribute explicitly determined
1009 // by being listed in a data-sharing attribute clause.
1010 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001011 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001012 VarsWithInheritedDSA.count(VD) == 0) {
1013 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001014 return;
1015 }
1016
1017 // OpenMP [2.9.3.6, Restrictions, p.2]
1018 // A list item that appears in a reduction clause of the innermost
1019 // enclosing worksharing or parallel construct may not be accessed in an
1020 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001021 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001022 [](OpenMPDirectiveKind K) -> bool {
1023 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001024 isOpenMPWorksharingDirective(K) ||
1025 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001026 },
1027 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001028 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1029 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001030 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1031 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001032 return;
1033 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034
1035 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001036 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001037 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001038 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001039 }
1040 }
1041 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001042 for (auto *C : S->clauses()) {
1043 // Skip analysis of arguments of implicitly defined firstprivate clause
1044 // for task directives.
1045 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1046 for (auto *CC : C->children()) {
1047 if (CC)
1048 Visit(CC);
1049 }
1050 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001051 }
1052 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001053 for (auto *C : S->children()) {
1054 if (C && !isa<OMPExecutableDirective>(C))
1055 Visit(C);
1056 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001057 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001058
1059 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001060 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001061 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1062 return VarsWithInheritedDSA;
1063 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064
Alexey Bataev7ff55242014-06-19 09:13:45 +00001065 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1066 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001067};
Alexey Bataeved09d242014-05-28 05:53:51 +00001068} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001069
Alexey Bataevbae9a792014-06-27 10:37:06 +00001070void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001071 switch (DKind) {
1072 case OMPD_parallel: {
1073 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1074 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001075 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001076 std::make_pair(".global_tid.", KmpInt32PtrTy),
1077 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1078 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001079 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001080 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1081 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001082 break;
1083 }
1084 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001085 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001086 std::make_pair(StringRef(), QualType()) // __context with shared vars
1087 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001088 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1089 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001090 break;
1091 }
1092 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001093 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001094 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001095 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001096 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1097 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001098 break;
1099 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001100 case OMPD_for_simd: {
1101 Sema::CapturedParamNameType Params[] = {
1102 std::make_pair(StringRef(), QualType()) // __context with shared vars
1103 };
1104 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1105 Params);
1106 break;
1107 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001108 case OMPD_sections: {
1109 Sema::CapturedParamNameType Params[] = {
1110 std::make_pair(StringRef(), QualType()) // __context with shared vars
1111 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001112 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1113 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001114 break;
1115 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001116 case OMPD_section: {
1117 Sema::CapturedParamNameType Params[] = {
1118 std::make_pair(StringRef(), QualType()) // __context with shared vars
1119 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001120 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1121 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001122 break;
1123 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001124 case OMPD_single: {
1125 Sema::CapturedParamNameType Params[] = {
1126 std::make_pair(StringRef(), QualType()) // __context with shared vars
1127 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001128 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1129 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001130 break;
1131 }
Alexander Musman80c22892014-07-17 08:54:58 +00001132 case OMPD_master: {
1133 Sema::CapturedParamNameType Params[] = {
1134 std::make_pair(StringRef(), QualType()) // __context with shared vars
1135 };
1136 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1137 Params);
1138 break;
1139 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001140 case OMPD_critical: {
1141 Sema::CapturedParamNameType Params[] = {
1142 std::make_pair(StringRef(), QualType()) // __context with shared vars
1143 };
1144 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1145 Params);
1146 break;
1147 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001148 case OMPD_parallel_for: {
1149 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1150 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1151 Sema::CapturedParamNameType Params[] = {
1152 std::make_pair(".global_tid.", KmpInt32PtrTy),
1153 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1154 std::make_pair(StringRef(), QualType()) // __context with shared vars
1155 };
1156 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1157 Params);
1158 break;
1159 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001160 case OMPD_parallel_for_simd: {
1161 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1162 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1163 Sema::CapturedParamNameType Params[] = {
1164 std::make_pair(".global_tid.", KmpInt32PtrTy),
1165 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1166 std::make_pair(StringRef(), QualType()) // __context with shared vars
1167 };
1168 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1169 Params);
1170 break;
1171 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001172 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001173 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1174 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001175 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001176 std::make_pair(".global_tid.", KmpInt32PtrTy),
1177 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001178 std::make_pair(StringRef(), QualType()) // __context with shared vars
1179 };
1180 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1181 Params);
1182 break;
1183 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001184 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001185 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001186 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001187 std::make_pair(".global_tid.", KmpInt32Ty),
1188 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001189 std::make_pair(StringRef(), QualType()) // __context with shared vars
1190 };
1191 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1192 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001193 // Mark this captured region as inlined, because we don't use outlined
1194 // function directly.
1195 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1196 AlwaysInlineAttr::CreateImplicit(
1197 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001198 break;
1199 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001200 case OMPD_ordered: {
1201 Sema::CapturedParamNameType Params[] = {
1202 std::make_pair(StringRef(), QualType()) // __context with shared vars
1203 };
1204 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1205 Params);
1206 break;
1207 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001208 case OMPD_atomic: {
1209 Sema::CapturedParamNameType Params[] = {
1210 std::make_pair(StringRef(), QualType()) // __context with shared vars
1211 };
1212 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1213 Params);
1214 break;
1215 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001216 case OMPD_target: {
1217 Sema::CapturedParamNameType Params[] = {
1218 std::make_pair(StringRef(), QualType()) // __context with shared vars
1219 };
1220 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1221 Params);
1222 break;
1223 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001224 case OMPD_teams: {
1225 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1226 QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1227 Sema::CapturedParamNameType Params[] = {
1228 std::make_pair(".global_tid.", KmpInt32PtrTy),
1229 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1230 std::make_pair(StringRef(), QualType()) // __context with shared vars
1231 };
1232 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1233 Params);
1234 break;
1235 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001236 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001237 case OMPD_taskyield:
1238 case OMPD_barrier:
1239 case OMPD_taskwait:
1240 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001241 llvm_unreachable("OpenMP Directive is not allowed");
1242 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001243 llvm_unreachable("Unknown OpenMP directive");
1244 }
1245}
1246
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001247StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1248 ArrayRef<OMPClause *> Clauses) {
1249 if (!S.isUsable()) {
1250 ActOnCapturedRegionError();
1251 return StmtError();
1252 }
1253 // Mark all variables in private list clauses as used in inner region. This is
1254 // required for proper codegen.
1255 for (auto *Clause : Clauses) {
1256 if (isOpenMPPrivate(Clause->getClauseKind())) {
1257 for (auto *VarRef : Clause->children()) {
1258 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001259 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001260 }
1261 }
1262 }
1263 }
1264 return ActOnCapturedRegionEnd(S.get());
1265}
1266
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001267static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1268 OpenMPDirectiveKind CurrentRegion,
1269 const DeclarationNameInfo &CurrentName,
1270 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001271 // Allowed nesting of constructs
1272 // +------------------+-----------------+------------------------------------+
1273 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1274 // +------------------+-----------------+------------------------------------+
1275 // | parallel | parallel | * |
1276 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001277 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001278 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001279 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001280 // | parallel | simd | * |
1281 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001282 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001283 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001284 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001285 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001286 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001287 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001288 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001289 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001290 // | parallel | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001291 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001292 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001293 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001294 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001295 // | parallel | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001296 // +------------------+-----------------+------------------------------------+
1297 // | for | parallel | * |
1298 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001299 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001300 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001301 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001302 // | for | simd | * |
1303 // | for | sections | + |
1304 // | for | section | + |
1305 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001306 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001307 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001308 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001309 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001310 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001311 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001312 // | for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001313 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001314 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001315 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001316 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001317 // | for | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001318 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001319 // | master | parallel | * |
1320 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001321 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001322 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001323 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001324 // | master | simd | * |
1325 // | master | sections | + |
1326 // | master | section | + |
1327 // | master | single | + |
1328 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001329 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001330 // | master |parallel sections| * |
1331 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001332 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001333 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001334 // | master | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001335 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001336 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001337 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001338 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001339 // | master | teams | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001340 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001341 // | critical | parallel | * |
1342 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001343 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001344 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001345 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001346 // | critical | simd | * |
1347 // | critical | sections | + |
1348 // | critical | section | + |
1349 // | critical | single | + |
1350 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001351 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001352 // | critical |parallel sections| * |
1353 // | critical | task | * |
1354 // | critical | taskyield | * |
1355 // | critical | barrier | + |
1356 // | critical | taskwait | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001357 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001358 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001359 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001360 // | critical | teams | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001361 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001362 // | simd | parallel | |
1363 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001364 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001365 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001366 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001367 // | simd | simd | |
1368 // | simd | sections | |
1369 // | simd | section | |
1370 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001371 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001372 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001373 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001374 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001375 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001376 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001377 // | simd | taskwait | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001378 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001379 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001380 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001381 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001382 // | simd | teams | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001383 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001384 // | for simd | parallel | |
1385 // | for simd | for | |
1386 // | for simd | for simd | |
1387 // | for simd | master | |
1388 // | for simd | critical | |
1389 // | for simd | simd | |
1390 // | for simd | sections | |
1391 // | for simd | section | |
1392 // | for simd | single | |
1393 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001394 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001395 // | for simd |parallel sections| |
1396 // | for simd | task | |
1397 // | for simd | taskyield | |
1398 // | for simd | barrier | |
1399 // | for simd | taskwait | |
1400 // | for simd | flush | |
1401 // | for simd | ordered | |
1402 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001403 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001404 // | for simd | teams | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001405 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001406 // | parallel for simd| parallel | |
1407 // | parallel for simd| for | |
1408 // | parallel for simd| for simd | |
1409 // | parallel for simd| master | |
1410 // | parallel for simd| critical | |
1411 // | parallel for simd| simd | |
1412 // | parallel for simd| sections | |
1413 // | parallel for simd| section | |
1414 // | parallel for simd| single | |
1415 // | parallel for simd| parallel for | |
1416 // | parallel for simd|parallel for simd| |
1417 // | parallel for simd|parallel sections| |
1418 // | parallel for simd| task | |
1419 // | parallel for simd| taskyield | |
1420 // | parallel for simd| barrier | |
1421 // | parallel for simd| taskwait | |
1422 // | parallel for simd| flush | |
1423 // | parallel for simd| ordered | |
1424 // | parallel for simd| atomic | |
1425 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001426 // | parallel for simd| teams | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001427 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001428 // | sections | parallel | * |
1429 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001430 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001431 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001432 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001433 // | sections | simd | * |
1434 // | sections | sections | + |
1435 // | sections | section | * |
1436 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001437 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001438 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001439 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001440 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001441 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001442 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001443 // | sections | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001444 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001445 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001446 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001447 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001448 // | sections | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001449 // +------------------+-----------------+------------------------------------+
1450 // | section | parallel | * |
1451 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001452 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001453 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001454 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001455 // | section | simd | * |
1456 // | section | sections | + |
1457 // | section | section | + |
1458 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001459 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001460 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001461 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001462 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001463 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001464 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001465 // | section | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001466 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001467 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001468 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001469 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001470 // | section | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001471 // +------------------+-----------------+------------------------------------+
1472 // | single | parallel | * |
1473 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001474 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001475 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001476 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001477 // | single | simd | * |
1478 // | single | sections | + |
1479 // | single | section | + |
1480 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001481 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001482 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001483 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001484 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001485 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001486 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001487 // | single | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001488 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001489 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001490 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001491 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001492 // | single | teams | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001493 // +------------------+-----------------+------------------------------------+
1494 // | parallel for | parallel | * |
1495 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001496 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001497 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001498 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001499 // | parallel for | simd | * |
1500 // | parallel for | sections | + |
1501 // | parallel for | section | + |
1502 // | parallel for | single | + |
1503 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001504 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001505 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001506 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001507 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001508 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001509 // | parallel for | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001510 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001511 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001512 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001513 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001514 // | parallel for | teams | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001515 // +------------------+-----------------+------------------------------------+
1516 // | parallel sections| parallel | * |
1517 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001518 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001519 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001520 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001521 // | parallel sections| simd | * |
1522 // | parallel sections| sections | + |
1523 // | parallel sections| section | * |
1524 // | parallel sections| single | + |
1525 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001526 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001527 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001528 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001529 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001530 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001531 // | parallel sections| taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001532 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001533 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001534 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001535 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001536 // | parallel sections| teams | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001537 // +------------------+-----------------+------------------------------------+
1538 // | task | parallel | * |
1539 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001540 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001541 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001542 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001543 // | task | simd | * |
1544 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001545 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001546 // | task | single | + |
1547 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001548 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001549 // | task |parallel sections| * |
1550 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001551 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001552 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001553 // | task | taskwait | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001554 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001555 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001556 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001557 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001558 // | task | teams | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001559 // +------------------+-----------------+------------------------------------+
1560 // | ordered | parallel | * |
1561 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001562 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001563 // | ordered | master | * |
1564 // | ordered | critical | * |
1565 // | ordered | simd | * |
1566 // | ordered | sections | + |
1567 // | ordered | section | + |
1568 // | ordered | single | + |
1569 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001570 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001571 // | ordered |parallel sections| * |
1572 // | ordered | task | * |
1573 // | ordered | taskyield | * |
1574 // | ordered | barrier | + |
1575 // | ordered | taskwait | * |
1576 // | ordered | flush | * |
1577 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001578 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001579 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001580 // | ordered | teams | + |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001581 // +------------------+-----------------+------------------------------------+
1582 // | atomic | parallel | |
1583 // | atomic | for | |
1584 // | atomic | for simd | |
1585 // | atomic | master | |
1586 // | atomic | critical | |
1587 // | atomic | simd | |
1588 // | atomic | sections | |
1589 // | atomic | section | |
1590 // | atomic | single | |
1591 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001592 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001593 // | atomic |parallel sections| |
1594 // | atomic | task | |
1595 // | atomic | taskyield | |
1596 // | atomic | barrier | |
1597 // | atomic | taskwait | |
1598 // | atomic | flush | |
1599 // | atomic | ordered | |
1600 // | atomic | atomic | |
1601 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001602 // | atomic | teams | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001603 // +------------------+-----------------+------------------------------------+
1604 // | target | parallel | * |
1605 // | target | for | * |
1606 // | target | for simd | * |
1607 // | target | master | * |
1608 // | target | critical | * |
1609 // | target | simd | * |
1610 // | target | sections | * |
1611 // | target | section | * |
1612 // | target | single | * |
1613 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001614 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001615 // | target |parallel sections| * |
1616 // | target | task | * |
1617 // | target | taskyield | * |
1618 // | target | barrier | * |
1619 // | target | taskwait | * |
1620 // | target | flush | * |
1621 // | target | ordered | * |
1622 // | target | atomic | * |
1623 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001624 // | target | teams | * |
1625 // +------------------+-----------------+------------------------------------+
1626 // | teams | parallel | * |
1627 // | teams | for | + |
1628 // | teams | for simd | + |
1629 // | teams | master | + |
1630 // | teams | critical | + |
1631 // | teams | simd | + |
1632 // | teams | sections | + |
1633 // | teams | section | + |
1634 // | teams | single | + |
1635 // | teams | parallel for | * |
1636 // | teams |parallel for simd| * |
1637 // | teams |parallel sections| * |
1638 // | teams | task | + |
1639 // | teams | taskyield | + |
1640 // | teams | barrier | + |
1641 // | teams | taskwait | + |
1642 // | teams | flush | + |
1643 // | teams | ordered | + |
1644 // | teams | atomic | + |
1645 // | teams | target | + |
1646 // | teams | teams | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001647 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001648 if (Stack->getCurScope()) {
1649 auto ParentRegion = Stack->getParentDirective();
1650 bool NestingProhibited = false;
1651 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001652 enum {
1653 NoRecommend,
1654 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001655 ShouldBeInOrderedRegion,
1656 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001657 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001658 if (isOpenMPSimdDirective(ParentRegion)) {
1659 // OpenMP [2.16, Nesting of Regions]
1660 // OpenMP constructs may not be nested inside a simd region.
1661 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1662 return true;
1663 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001664 if (ParentRegion == OMPD_atomic) {
1665 // OpenMP [2.16, Nesting of Regions]
1666 // OpenMP constructs may not be nested inside an atomic region.
1667 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1668 return true;
1669 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001670 if (CurrentRegion == OMPD_section) {
1671 // OpenMP [2.7.2, sections Construct, Restrictions]
1672 // Orphaned section directives are prohibited. That is, the section
1673 // directives must appear within the sections construct and must not be
1674 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001675 if (ParentRegion != OMPD_sections &&
1676 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001677 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1678 << (ParentRegion != OMPD_unknown)
1679 << getOpenMPDirectiveName(ParentRegion);
1680 return true;
1681 }
1682 return false;
1683 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001684 // Allow some constructs to be orphaned (they could be used in functions,
1685 // called from OpenMP regions with the required preconditions).
1686 if (ParentRegion == OMPD_unknown)
1687 return false;
Alexander Musman80c22892014-07-17 08:54:58 +00001688 if (CurrentRegion == OMPD_master) {
1689 // OpenMP [2.16, Nesting of Regions]
1690 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001691 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001692 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1693 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001694 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1695 // OpenMP [2.16, Nesting of Regions]
1696 // A critical region may not be nested (closely or otherwise) inside a
1697 // critical region with the same name. Note that this restriction is not
1698 // sufficient to prevent deadlock.
1699 SourceLocation PreviousCriticalLoc;
1700 bool DeadLock =
1701 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1702 OpenMPDirectiveKind K,
1703 const DeclarationNameInfo &DNI,
1704 SourceLocation Loc)
1705 ->bool {
1706 if (K == OMPD_critical &&
1707 DNI.getName() == CurrentName.getName()) {
1708 PreviousCriticalLoc = Loc;
1709 return true;
1710 } else
1711 return false;
1712 },
1713 false /* skip top directive */);
1714 if (DeadLock) {
1715 SemaRef.Diag(StartLoc,
1716 diag::err_omp_prohibited_region_critical_same_name)
1717 << CurrentName.getName();
1718 if (PreviousCriticalLoc.isValid())
1719 SemaRef.Diag(PreviousCriticalLoc,
1720 diag::note_omp_previous_critical_region);
1721 return true;
1722 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001723 } else if (CurrentRegion == OMPD_barrier) {
1724 // OpenMP [2.16, Nesting of Regions]
1725 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001726 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001727 NestingProhibited =
1728 isOpenMPWorksharingDirective(ParentRegion) ||
1729 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1730 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001731 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001732 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001733 // OpenMP [2.16, Nesting of Regions]
1734 // A worksharing region may not be closely nested inside a worksharing,
1735 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001736 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001737 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001738 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1739 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1740 Recommend = ShouldBeInParallelRegion;
1741 } else if (CurrentRegion == OMPD_ordered) {
1742 // OpenMP [2.16, Nesting of Regions]
1743 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001744 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001745 // An ordered region must be closely nested inside a loop region (or
1746 // parallel loop region) with an ordered clause.
1747 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001748 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001749 !Stack->isParentOrderedRegion();
1750 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001751 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1752 // OpenMP [2.16, Nesting of Regions]
1753 // If specified, a teams construct must be contained within a target
1754 // construct.
1755 NestingProhibited = ParentRegion != OMPD_target;
1756 Recommend = ShouldBeInTargetRegion;
1757 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1758 }
1759 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1760 // OpenMP [2.16, Nesting of Regions]
1761 // distribute, parallel, parallel sections, parallel workshare, and the
1762 // parallel loop and parallel loop SIMD constructs are the only OpenMP
1763 // constructs that can be closely nested in the teams region.
1764 // TODO: add distribute directive.
1765 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1766 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001767 }
1768 if (NestingProhibited) {
1769 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001770 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1771 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00001772 return true;
1773 }
1774 }
1775 return false;
1776}
1777
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001778StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001779 const DeclarationNameInfo &DirName,
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001780 ArrayRef<OMPClause *> Clauses,
1781 Stmt *AStmt,
1782 SourceLocation StartLoc,
1783 SourceLocation EndLoc) {
1784 StmtResult Res = StmtError();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001785 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00001786 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001787
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001788 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00001789 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001790 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00001791 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00001792 if (AStmt) {
1793 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1794
1795 // Check default data sharing attributes for referenced variables.
1796 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1797 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1798 if (DSAChecker.isErrorFound())
1799 return StmtError();
1800 // Generate list of implicitly defined firstprivate variables.
1801 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00001802
1803 if (!DSAChecker.getImplicitFirstprivate().empty()) {
1804 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1805 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1806 SourceLocation(), SourceLocation())) {
1807 ClausesWithImplicit.push_back(Implicit);
1808 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1809 DSAChecker.getImplicitFirstprivate().size();
1810 } else
1811 ErrorFound = true;
1812 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001813 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001814
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001815 switch (Kind) {
1816 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00001817 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1818 EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001819 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001820 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001821 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1822 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00001823 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00001824 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00001825 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1826 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001827 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00001828 case OMPD_for_simd:
1829 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
1830 EndLoc, VarsWithInheritedDSA);
1831 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001832 case OMPD_sections:
1833 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1834 EndLoc);
1835 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001836 case OMPD_section:
1837 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00001838 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001839 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1840 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001841 case OMPD_single:
1842 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1843 EndLoc);
1844 break;
Alexander Musman80c22892014-07-17 08:54:58 +00001845 case OMPD_master:
1846 assert(ClausesWithImplicit.empty() &&
1847 "No clauses are allowed for 'omp master' directive");
1848 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1849 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001850 case OMPD_critical:
1851 assert(ClausesWithImplicit.empty() &&
1852 "No clauses are allowed for 'omp critical' directive");
1853 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
1854 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001855 case OMPD_parallel_for:
1856 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1857 EndLoc, VarsWithInheritedDSA);
1858 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00001859 case OMPD_parallel_for_simd:
1860 Res = ActOnOpenMPParallelForSimdDirective(
1861 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
1862 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001863 case OMPD_parallel_sections:
1864 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1865 StartLoc, EndLoc);
1866 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001867 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001868 Res =
1869 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1870 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00001871 case OMPD_taskyield:
1872 assert(ClausesWithImplicit.empty() &&
1873 "No clauses are allowed for 'omp taskyield' directive");
1874 assert(AStmt == nullptr &&
1875 "No associated statement allowed for 'omp taskyield' directive");
1876 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1877 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001878 case OMPD_barrier:
1879 assert(ClausesWithImplicit.empty() &&
1880 "No clauses are allowed for 'omp barrier' directive");
1881 assert(AStmt == nullptr &&
1882 "No associated statement allowed for 'omp barrier' directive");
1883 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1884 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00001885 case OMPD_taskwait:
1886 assert(ClausesWithImplicit.empty() &&
1887 "No clauses are allowed for 'omp taskwait' directive");
1888 assert(AStmt == nullptr &&
1889 "No associated statement allowed for 'omp taskwait' directive");
1890 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1891 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00001892 case OMPD_flush:
1893 assert(AStmt == nullptr &&
1894 "No associated statement allowed for 'omp flush' directive");
1895 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
1896 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001897 case OMPD_ordered:
1898 assert(ClausesWithImplicit.empty() &&
1899 "No clauses are allowed for 'omp ordered' directive");
1900 Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
1901 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00001902 case OMPD_atomic:
1903 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
1904 EndLoc);
1905 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001906 case OMPD_teams:
1907 Res =
1908 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1909 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001910 case OMPD_target:
1911 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
1912 EndLoc);
1913 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001914 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001915 llvm_unreachable("OpenMP Directive is not allowed");
1916 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001917 llvm_unreachable("Unknown OpenMP directive");
1918 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001919
Alexey Bataev4acb8592014-07-07 13:01:15 +00001920 for (auto P : VarsWithInheritedDSA) {
1921 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1922 << P.first << P.second->getSourceRange();
1923 }
1924 if (!VarsWithInheritedDSA.empty())
1925 return StmtError();
1926
Alexey Bataeved09d242014-05-28 05:53:51 +00001927 if (ErrorFound)
1928 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001929 return Res;
1930}
1931
1932StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1933 Stmt *AStmt,
1934 SourceLocation StartLoc,
1935 SourceLocation EndLoc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001936 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1937 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1938 // 1.2.2 OpenMP Language Terminology
1939 // Structured block - An executable statement with a single entry at the
1940 // top and a single exit at the bottom.
1941 // The point of exit cannot be a branch out of the structured block.
1942 // longjmp() and throw() must not violate the entry/exit criteria.
1943 CS->getCapturedDecl()->setNothrow();
1944
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001945 getCurFunction()->setHasBranchProtectedScope();
1946
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001947 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1948 AStmt);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001949}
1950
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001951namespace {
1952/// \brief Helper class for checking canonical form of the OpenMP loops and
1953/// extracting iteration space of each loop in the loop nest, that will be used
1954/// for IR generation.
1955class OpenMPIterationSpaceChecker {
1956 /// \brief Reference to Sema.
1957 Sema &SemaRef;
1958 /// \brief A location for diagnostics (when there is no some better location).
1959 SourceLocation DefaultLoc;
1960 /// \brief A location for diagnostics (when increment is not compatible).
1961 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001962 /// \brief A source location for referring to loop init later.
1963 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001964 /// \brief A source location for referring to condition later.
1965 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00001966 /// \brief A source location for referring to increment later.
1967 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001968 /// \brief Loop variable.
1969 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001970 /// \brief Reference to loop variable.
1971 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001972 /// \brief Lower bound (initializer for the var).
1973 Expr *LB;
1974 /// \brief Upper bound.
1975 Expr *UB;
1976 /// \brief Loop step (increment).
1977 Expr *Step;
1978 /// \brief This flag is true when condition is one of:
1979 /// Var < UB
1980 /// Var <= UB
1981 /// UB > Var
1982 /// UB >= Var
1983 bool TestIsLessOp;
1984 /// \brief This flag is true when condition is strict ( < or > ).
1985 bool TestIsStrictOp;
1986 /// \brief This flag is true when step is subtracted on each iteration.
1987 bool SubtractStep;
1988
1989public:
1990 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1991 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00001992 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
1993 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00001994 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
1995 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001996 /// \brief Check init-expr for canonical loop form and save loop counter
1997 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00001998 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00001999 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2000 /// for less/greater and for strict/non-strict comparison.
2001 bool CheckCond(Expr *S);
2002 /// \brief Check incr-expr for canonical loop form and return true if it
2003 /// does not conform, otherwise save loop step (#Step).
2004 bool CheckInc(Expr *S);
2005 /// \brief Return the loop counter variable.
2006 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002007 /// \brief Return the reference expression to loop counter variable.
2008 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002009 /// \brief Source range of the loop init.
2010 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2011 /// \brief Source range of the loop condition.
2012 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2013 /// \brief Source range of the loop increment.
2014 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2015 /// \brief True if the step should be subtracted.
2016 bool ShouldSubtractStep() const { return SubtractStep; }
2017 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002018 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002019 /// \brief Build the precondition expression for the loops.
2020 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002021 /// \brief Build reference expression to the counter be used for codegen.
2022 Expr *BuildCounterVar() const;
2023 /// \brief Build initization of the counter be used for codegen.
2024 Expr *BuildCounterInit() const;
2025 /// \brief Build step of the counter be used for codegen.
2026 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002027 /// \brief Return true if any expression is dependent.
2028 bool Dependent() const;
2029
2030private:
2031 /// \brief Check the right-hand side of an assignment in the increment
2032 /// expression.
2033 bool CheckIncRHS(Expr *RHS);
2034 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002035 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002036 /// \brief Helper to set upper bound.
2037 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2038 const SourceLocation &SL);
2039 /// \brief Helper to set loop increment.
2040 bool SetStep(Expr *NewStep, bool Subtract);
2041};
2042
2043bool OpenMPIterationSpaceChecker::Dependent() const {
2044 if (!Var) {
2045 assert(!LB && !UB && !Step);
2046 return false;
2047 }
2048 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2049 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2050}
2051
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002052bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2053 DeclRefExpr *NewVarRefExpr,
2054 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002055 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002056 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2057 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002058 if (!NewVar || !NewLB)
2059 return true;
2060 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002061 VarRef = NewVarRefExpr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002062 LB = NewLB;
2063 return false;
2064}
2065
2066bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2067 const SourceRange &SR,
2068 const SourceLocation &SL) {
2069 // State consistency checking to ensure correct usage.
2070 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2071 !TestIsLessOp && !TestIsStrictOp);
2072 if (!NewUB)
2073 return true;
2074 UB = NewUB;
2075 TestIsLessOp = LessOp;
2076 TestIsStrictOp = StrictOp;
2077 ConditionSrcRange = SR;
2078 ConditionLoc = SL;
2079 return false;
2080}
2081
2082bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2083 // State consistency checking to ensure correct usage.
2084 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2085 if (!NewStep)
2086 return true;
2087 if (!NewStep->isValueDependent()) {
2088 // Check that the step is integer expression.
2089 SourceLocation StepLoc = NewStep->getLocStart();
2090 ExprResult Val =
2091 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2092 if (Val.isInvalid())
2093 return true;
2094 NewStep = Val.get();
2095
2096 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2097 // If test-expr is of form var relational-op b and relational-op is < or
2098 // <= then incr-expr must cause var to increase on each iteration of the
2099 // loop. If test-expr is of form var relational-op b and relational-op is
2100 // > or >= then incr-expr must cause var to decrease on each iteration of
2101 // the loop.
2102 // If test-expr is of form b relational-op var and relational-op is < or
2103 // <= then incr-expr must cause var to decrease on each iteration of the
2104 // loop. If test-expr is of form b relational-op var and relational-op is
2105 // > or >= then incr-expr must cause var to increase on each iteration of
2106 // the loop.
2107 llvm::APSInt Result;
2108 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2109 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2110 bool IsConstNeg =
2111 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002112 bool IsConstPos =
2113 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002114 bool IsConstZero = IsConstant && !Result.getBoolValue();
2115 if (UB && (IsConstZero ||
2116 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002117 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002118 SemaRef.Diag(NewStep->getExprLoc(),
2119 diag::err_omp_loop_incr_not_compatible)
2120 << Var << TestIsLessOp << NewStep->getSourceRange();
2121 SemaRef.Diag(ConditionLoc,
2122 diag::note_omp_loop_cond_requres_compatible_incr)
2123 << TestIsLessOp << ConditionSrcRange;
2124 return true;
2125 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002126 if (TestIsLessOp == Subtract) {
2127 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2128 NewStep).get();
2129 Subtract = !Subtract;
2130 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002131 }
2132
2133 Step = NewStep;
2134 SubtractStep = Subtract;
2135 return false;
2136}
2137
Alexey Bataev9c821032015-04-30 04:23:23 +00002138bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002139 // Check init-expr for canonical loop form and save loop counter
2140 // variable - #Var and its initialization value - #LB.
2141 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2142 // var = lb
2143 // integer-type var = lb
2144 // random-access-iterator-type var = lb
2145 // pointer-type var = lb
2146 //
2147 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002148 if (EmitDiags) {
2149 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2150 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002151 return true;
2152 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002153 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002154 if (Expr *E = dyn_cast<Expr>(S))
2155 S = E->IgnoreParens();
2156 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2157 if (BO->getOpcode() == BO_Assign)
2158 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002159 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002160 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002161 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2162 if (DS->isSingleDecl()) {
2163 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2164 if (Var->hasInit()) {
2165 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002166 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002167 SemaRef.Diag(S->getLocStart(),
2168 diag::ext_omp_loop_not_canonical_init)
2169 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002170 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002171 }
2172 }
2173 }
2174 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2175 if (CE->getOperator() == OO_Equal)
2176 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002177 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2178 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002179
Alexey Bataev9c821032015-04-30 04:23:23 +00002180 if (EmitDiags) {
2181 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2182 << S->getSourceRange();
2183 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002184 return true;
2185}
2186
Alexey Bataev23b69422014-06-18 07:08:49 +00002187/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002188/// variable (which may be the loop variable) if possible.
2189static const VarDecl *GetInitVarDecl(const Expr *E) {
2190 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002191 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002192 E = E->IgnoreParenImpCasts();
2193 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2194 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2195 if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
2196 CE->getArg(0) != nullptr)
2197 E = CE->getArg(0)->IgnoreParenImpCasts();
2198 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2199 if (!DRE)
2200 return nullptr;
2201 return dyn_cast<VarDecl>(DRE->getDecl());
2202}
2203
2204bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2205 // Check test-expr for canonical form, save upper-bound UB, flags for
2206 // less/greater and for strict/non-strict comparison.
2207 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2208 // var relational-op b
2209 // b relational-op var
2210 //
2211 if (!S) {
2212 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2213 return true;
2214 }
2215 S = S->IgnoreParenImpCasts();
2216 SourceLocation CondLoc = S->getLocStart();
2217 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2218 if (BO->isRelationalOp()) {
2219 if (GetInitVarDecl(BO->getLHS()) == Var)
2220 return SetUB(BO->getRHS(),
2221 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2222 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2223 BO->getSourceRange(), BO->getOperatorLoc());
2224 if (GetInitVarDecl(BO->getRHS()) == Var)
2225 return SetUB(BO->getLHS(),
2226 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2227 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2228 BO->getSourceRange(), BO->getOperatorLoc());
2229 }
2230 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2231 if (CE->getNumArgs() == 2) {
2232 auto Op = CE->getOperator();
2233 switch (Op) {
2234 case OO_Greater:
2235 case OO_GreaterEqual:
2236 case OO_Less:
2237 case OO_LessEqual:
2238 if (GetInitVarDecl(CE->getArg(0)) == Var)
2239 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2240 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2241 CE->getOperatorLoc());
2242 if (GetInitVarDecl(CE->getArg(1)) == Var)
2243 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2244 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2245 CE->getOperatorLoc());
2246 break;
2247 default:
2248 break;
2249 }
2250 }
2251 }
2252 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2253 << S->getSourceRange() << Var;
2254 return true;
2255}
2256
2257bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2258 // RHS of canonical loop form increment can be:
2259 // var + incr
2260 // incr + var
2261 // var - incr
2262 //
2263 RHS = RHS->IgnoreParenImpCasts();
2264 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2265 if (BO->isAdditiveOp()) {
2266 bool IsAdd = BO->getOpcode() == BO_Add;
2267 if (GetInitVarDecl(BO->getLHS()) == Var)
2268 return SetStep(BO->getRHS(), !IsAdd);
2269 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2270 return SetStep(BO->getLHS(), false);
2271 }
2272 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2273 bool IsAdd = CE->getOperator() == OO_Plus;
2274 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2275 if (GetInitVarDecl(CE->getArg(0)) == Var)
2276 return SetStep(CE->getArg(1), !IsAdd);
2277 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2278 return SetStep(CE->getArg(0), false);
2279 }
2280 }
2281 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2282 << RHS->getSourceRange() << Var;
2283 return true;
2284}
2285
2286bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2287 // Check incr-expr for canonical loop form and return true if it
2288 // does not conform.
2289 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2290 // ++var
2291 // var++
2292 // --var
2293 // var--
2294 // var += incr
2295 // var -= incr
2296 // var = var + incr
2297 // var = incr + var
2298 // var = var - incr
2299 //
2300 if (!S) {
2301 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2302 return true;
2303 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002304 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002305 S = S->IgnoreParens();
2306 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2307 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2308 return SetStep(
2309 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2310 (UO->isDecrementOp() ? -1 : 1)).get(),
2311 false);
2312 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2313 switch (BO->getOpcode()) {
2314 case BO_AddAssign:
2315 case BO_SubAssign:
2316 if (GetInitVarDecl(BO->getLHS()) == Var)
2317 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2318 break;
2319 case BO_Assign:
2320 if (GetInitVarDecl(BO->getLHS()) == Var)
2321 return CheckIncRHS(BO->getRHS());
2322 break;
2323 default:
2324 break;
2325 }
2326 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2327 switch (CE->getOperator()) {
2328 case OO_PlusPlus:
2329 case OO_MinusMinus:
2330 if (GetInitVarDecl(CE->getArg(0)) == Var)
2331 return SetStep(
2332 SemaRef.ActOnIntegerConstant(
2333 CE->getLocStart(),
2334 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2335 false);
2336 break;
2337 case OO_PlusEqual:
2338 case OO_MinusEqual:
2339 if (GetInitVarDecl(CE->getArg(0)) == Var)
2340 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2341 break;
2342 case OO_Equal:
2343 if (GetInitVarDecl(CE->getArg(0)) == Var)
2344 return CheckIncRHS(CE->getArg(1));
2345 break;
2346 default:
2347 break;
2348 }
2349 }
2350 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2351 << S->getSourceRange() << Var;
2352 return true;
2353}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002354
2355/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002356Expr *
2357OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2358 const bool LimitedType) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002359 ExprResult Diff;
2360 if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2361 SemaRef.getLangOpts().CPlusPlus) {
2362 // Upper - Lower
2363 Expr *Upper = TestIsLessOp ? UB : LB;
2364 Expr *Lower = TestIsLessOp ? LB : UB;
2365
2366 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2367
2368 if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2369 // BuildBinOp already emitted error, this one is to point user to upper
2370 // and lower bound, and to tell what is passed to 'operator-'.
2371 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2372 << Upper->getSourceRange() << Lower->getSourceRange();
2373 return nullptr;
2374 }
2375 }
2376
2377 if (!Diff.isUsable())
2378 return nullptr;
2379
2380 // Upper - Lower [- 1]
2381 if (TestIsStrictOp)
2382 Diff = SemaRef.BuildBinOp(
2383 S, DefaultLoc, BO_Sub, Diff.get(),
2384 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2385 if (!Diff.isUsable())
2386 return nullptr;
2387
2388 // Upper - Lower [- 1] + Step
2389 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2390 Step->IgnoreImplicit());
2391 if (!Diff.isUsable())
2392 return nullptr;
2393
2394 // Parentheses (for dumping/debugging purposes only).
2395 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2396 if (!Diff.isUsable())
2397 return nullptr;
2398
2399 // (Upper - Lower [- 1] + Step) / Step
2400 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2401 Step->IgnoreImplicit());
2402 if (!Diff.isUsable())
2403 return nullptr;
2404
Alexander Musman174b3ca2014-10-06 11:16:29 +00002405 // OpenMP runtime requires 32-bit or 64-bit loop variables.
2406 if (LimitedType) {
2407 auto &C = SemaRef.Context;
2408 QualType Type = Diff.get()->getType();
2409 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2410 if (NewSize != C.getTypeSize(Type)) {
2411 if (NewSize < C.getTypeSize(Type)) {
2412 assert(NewSize == 64 && "incorrect loop var size");
2413 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2414 << InitSrcRange << ConditionSrcRange;
2415 }
2416 QualType NewType = C.getIntTypeForBitwidth(
2417 NewSize, Type->hasSignedIntegerRepresentation());
2418 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2419 Sema::AA_Converting, true);
2420 if (!Diff.isUsable())
2421 return nullptr;
2422 }
2423 }
2424
Alexander Musmana5f070a2014-10-01 06:03:56 +00002425 return Diff.get();
2426}
2427
Alexey Bataev62dbb972015-04-22 11:59:37 +00002428Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2429 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2430 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2431 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2432 auto CondExpr = SemaRef.BuildBinOp(
2433 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2434 : (TestIsStrictOp ? BO_GT : BO_GE),
2435 LB, UB);
2436 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2437 // Otherwise use original loop conditon and evaluate it in runtime.
2438 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2439}
2440
Alexander Musmana5f070a2014-10-01 06:03:56 +00002441/// \brief Build reference expression to the counter be used for codegen.
2442Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2443 return DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
Alexey Bataev9c821032015-04-30 04:23:23 +00002444 GetIncrementSrcRange().getBegin(), Var,
2445 /*RefersToEnclosingVariableOrCapture=*/true,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002446 DefaultLoc, Var->getType(), VK_LValue);
2447}
2448
2449/// \brief Build initization of the counter be used for codegen.
2450Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2451
2452/// \brief Build step of the counter be used for codegen.
2453Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2454
2455/// \brief Iteration space of a single for loop.
2456struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002457 /// \brief Condition of the loop.
2458 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002459 /// \brief This expression calculates the number of iterations in the loop.
2460 /// It is always possible to calculate it before starting the loop.
2461 Expr *NumIterations;
2462 /// \brief The loop counter variable.
2463 Expr *CounterVar;
2464 /// \brief This is initializer for the initial value of #CounterVar.
2465 Expr *CounterInit;
2466 /// \brief This is step for the #CounterVar used to generate its update:
2467 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2468 Expr *CounterStep;
2469 /// \brief Should step be subtracted?
2470 bool Subtract;
2471 /// \brief Source range of the loop init.
2472 SourceRange InitSrcRange;
2473 /// \brief Source range of the loop condition.
2474 SourceRange CondSrcRange;
2475 /// \brief Source range of the loop increment.
2476 SourceRange IncSrcRange;
2477};
2478
Alexey Bataev23b69422014-06-18 07:08:49 +00002479} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002480
Alexey Bataev9c821032015-04-30 04:23:23 +00002481void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2482 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2483 assert(Init && "Expected loop in canonical form.");
2484 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2485 if (CollapseIteration > 0 &&
2486 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2487 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2488 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2489 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2490 }
2491 DSAStack->setCollapseNumber(CollapseIteration - 1);
2492 }
2493}
2494
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002495/// \brief Called on a for stmt to check and extract its iteration space
2496/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00002497static bool CheckOpenMPIterationSpace(
2498 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2499 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2500 Expr *NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002501 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2502 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002503 // OpenMP [2.6, Canonical Loop Form]
2504 // for (init-expr; test-expr; incr-expr) structured-block
2505 auto For = dyn_cast_or_null<ForStmt>(S);
2506 if (!For) {
2507 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002508 << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2509 << NestedLoopCount << (CurrentNestedLoopCount > 0)
2510 << CurrentNestedLoopCount;
2511 if (NestedLoopCount > 1)
2512 SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2513 diag::note_omp_collapse_expr)
2514 << NestedLoopCountExpr->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002515 return true;
2516 }
2517 assert(For->getBody());
2518
2519 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2520
2521 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002522 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002523 if (ISC.CheckInit(Init)) {
2524 return true;
2525 }
2526
2527 bool HasErrors = false;
2528
2529 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002530 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002531
2532 // OpenMP [2.6, Canonical Loop Form]
2533 // Var is one of the following:
2534 // A variable of signed or unsigned integer type.
2535 // For C++, a variable of a random access iterator type.
2536 // For C, a variable of a pointer type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002537 auto VarType = Var->getType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002538 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2539 !VarType->isPointerType() &&
2540 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2541 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2542 << SemaRef.getLangOpts().CPlusPlus;
2543 HasErrors = true;
2544 }
2545
Alexey Bataev4acb8592014-07-07 13:01:15 +00002546 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2547 // Construct
2548 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2549 // parallel for construct is (are) private.
2550 // The loop iteration variable in the associated for-loop of a simd construct
2551 // with just one associated for-loop is linear with a constant-linear-step
2552 // that is the increment of the associated for-loop.
2553 // Exclude loop var from the list of variables with implicitly defined data
2554 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00002555 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002556
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002557 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2558 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00002559 // The loop iteration variable in the associated for-loop of a simd construct
2560 // with just one associated for-loop may be listed in a linear clause with a
2561 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00002562 // The loop iteration variable(s) in the associated for-loop(s) of a for or
2563 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002564 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002565 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2566 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2567 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002568 auto PredeterminedCKind =
2569 isOpenMPSimdDirective(DKind)
2570 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2571 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002572 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002573 DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00002574 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2575 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2576 DVar.CKind != OMPC_lastprivate)) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00002577 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002578 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00002579 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2580 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00002581 if (DVar.RefExpr == nullptr)
2582 DVar.CKind = PredeterminedCKind;
2583 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002584 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002585 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002586 // Make the loop iteration variable private (for worksharing constructs),
2587 // linear (for simd directives with the only one associated loop) or
2588 // lastprivate (for simd directives with several collapsed loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00002589 if (DVar.CKind == OMPC_unknown)
2590 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2591 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00002592 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002593 }
2594
Alexey Bataev7ff55242014-06-19 09:13:45 +00002595 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00002596
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002597 // Check test-expr.
2598 HasErrors |= ISC.CheckCond(For->getCond());
2599
2600 // Check incr-expr.
2601 HasErrors |= ISC.CheckInc(For->getInc());
2602
Alexander Musmana5f070a2014-10-01 06:03:56 +00002603 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002604 return HasErrors;
2605
Alexander Musmana5f070a2014-10-01 06:03:56 +00002606 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002607 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00002608 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2609 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00002610 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2611 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2612 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2613 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2614 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2615 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2616 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2617
Alexey Bataev62dbb972015-04-22 11:59:37 +00002618 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2619 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002620 ResultIterSpace.CounterVar == nullptr ||
2621 ResultIterSpace.CounterInit == nullptr ||
2622 ResultIterSpace.CounterStep == nullptr);
2623
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002624 return HasErrors;
2625}
2626
Alexander Musmana5f070a2014-10-01 06:03:56 +00002627/// \brief Build a variable declaration for OpenMP loop iteration variable.
2628static VarDecl *BuildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
2629 StringRef Name) {
2630 DeclContext *DC = SemaRef.CurContext;
2631 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2632 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2633 VarDecl *Decl =
2634 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
2635 Decl->setImplicit();
2636 return Decl;
2637}
2638
2639/// \brief Build 'VarRef = Start + Iter * Step'.
2640static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2641 SourceLocation Loc, ExprResult VarRef,
2642 ExprResult Start, ExprResult Iter,
2643 ExprResult Step, bool Subtract) {
2644 // Add parentheses (for debugging purposes only).
2645 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2646 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2647 !Step.isUsable())
2648 return ExprError();
2649
2650 ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2651 Step.get()->IgnoreImplicit());
2652 if (!Update.isUsable())
2653 return ExprError();
2654
2655 // Build 'VarRef = Start + Iter * Step'.
2656 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2657 Start.get()->IgnoreImplicit(), Update.get());
2658 if (!Update.isUsable())
2659 return ExprError();
2660
2661 Update = SemaRef.PerformImplicitConversion(
2662 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2663 if (!Update.isUsable())
2664 return ExprError();
2665
2666 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2667 return Update;
2668}
2669
2670/// \brief Convert integer expression \a E to make it have at least \a Bits
2671/// bits.
2672static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2673 Sema &SemaRef) {
2674 if (E == nullptr)
2675 return ExprError();
2676 auto &C = SemaRef.Context;
2677 QualType OldType = E->getType();
2678 unsigned HasBits = C.getTypeSize(OldType);
2679 if (HasBits >= Bits)
2680 return ExprResult(E);
2681 // OK to convert to signed, because new type has more bits than old.
2682 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2683 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2684 true);
2685}
2686
2687/// \brief Check if the given expression \a E is a constant integer that fits
2688/// into \a Bits bits.
2689static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2690 if (E == nullptr)
2691 return false;
2692 llvm::APSInt Result;
2693 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2694 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2695 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002696}
2697
2698/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00002699/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2700/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00002701static unsigned
2702CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2703 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002704 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00002705 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002706 unsigned NestedLoopCount = 1;
2707 if (NestedLoopCountExpr) {
2708 // Found 'collapse' clause - calculate collapse number.
2709 llvm::APSInt Result;
2710 if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2711 NestedLoopCount = Result.getLimitedValue();
2712 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002713 // This is helper routine for loop directives (e.g., 'for', 'simd',
2714 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00002715 SmallVector<LoopIterationSpace, 4> IterSpaces;
2716 IterSpaces.resize(NestedLoopCount);
2717 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002718 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00002719 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev4acb8592014-07-07 13:01:15 +00002720 NestedLoopCount, NestedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002721 VarsWithImplicitDSA, IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00002722 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002723 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002724 // OpenMP [2.8.1, simd construct, Restrictions]
2725 // All loops associated with the construct must be perfectly nested; that
2726 // is, there must be no intervening code nor any OpenMP directive between
2727 // any two loops.
2728 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002729 }
2730
Alexander Musmana5f070a2014-10-01 06:03:56 +00002731 Built.clear(/* size */ NestedLoopCount);
2732
2733 if (SemaRef.CurContext->isDependentContext())
2734 return NestedLoopCount;
2735
2736 // An example of what is generated for the following code:
2737 //
2738 // #pragma omp simd collapse(2)
2739 // for (i = 0; i < NI; ++i)
2740 // for (j = J0; j < NJ; j+=2) {
2741 // <loop body>
2742 // }
2743 //
2744 // We generate the code below.
2745 // Note: the loop body may be outlined in CodeGen.
2746 // Note: some counters may be C++ classes, operator- is used to find number of
2747 // iterations and operator+= to calculate counter value.
2748 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2749 // or i64 is currently supported).
2750 //
2751 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2752 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2753 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2754 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2755 // // similar updates for vars in clauses (e.g. 'linear')
2756 // <loop body (using local i and j)>
2757 // }
2758 // i = NI; // assign final values of counters
2759 // j = NJ;
2760 //
2761
2762 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2763 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00002764 // Precondition tests if there is at least one iteration (all conditions are
2765 // true).
2766 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002767 auto N0 = IterSpaces[0].NumIterations;
2768 ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2769 ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2770
2771 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2772 return NestedLoopCount;
2773
2774 auto &C = SemaRef.Context;
2775 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
2776
2777 Scope *CurScope = DSA.getCurScope();
2778 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002779 if (PreCond.isUsable()) {
2780 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
2781 PreCond.get(), IterSpaces[Cnt].PreCond);
2782 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002783 auto N = IterSpaces[Cnt].NumIterations;
2784 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
2785 if (LastIteration32.isUsable())
2786 LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2787 LastIteration32.get(), N);
2788 if (LastIteration64.isUsable())
2789 LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
2790 LastIteration64.get(), N);
2791 }
2792
2793 // Choose either the 32-bit or 64-bit version.
2794 ExprResult LastIteration = LastIteration64;
2795 if (LastIteration32.isUsable() &&
2796 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
2797 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
2798 FitsInto(
2799 32 /* Bits */,
2800 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
2801 LastIteration64.get(), SemaRef)))
2802 LastIteration = LastIteration32;
2803
2804 if (!LastIteration.isUsable())
2805 return 0;
2806
2807 // Save the number of iterations.
2808 ExprResult NumIterations = LastIteration;
2809 {
2810 LastIteration = SemaRef.BuildBinOp(
2811 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
2812 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2813 if (!LastIteration.isUsable())
2814 return 0;
2815 }
2816
2817 // Calculate the last iteration number beforehand instead of doing this on
2818 // each iteration. Do not do this if the number of iterations may be kfold-ed.
2819 llvm::APSInt Result;
2820 bool IsConstant =
2821 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
2822 ExprResult CalcLastIteration;
2823 if (!IsConstant) {
2824 SourceLocation SaveLoc;
2825 VarDecl *SaveVar =
2826 BuildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
2827 ".omp.last.iteration");
2828 ExprResult SaveRef = SemaRef.BuildDeclRefExpr(
2829 SaveVar, LastIteration.get()->getType(), VK_LValue, SaveLoc);
2830 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
2831 SaveRef.get(), LastIteration.get());
2832 LastIteration = SaveRef;
2833
2834 // Prepare SaveRef + 1.
2835 NumIterations = SemaRef.BuildBinOp(
2836 CurScope, SaveLoc, BO_Add, SaveRef.get(),
2837 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2838 if (!NumIterations.isUsable())
2839 return 0;
2840 }
2841
2842 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
2843
Alexander Musmanc6388682014-12-15 07:07:06 +00002844 QualType VType = LastIteration.get()->getType();
2845 // Build variables passed into runtime, nesessary for worksharing directives.
2846 ExprResult LB, UB, IL, ST, EUB;
2847 if (isOpenMPWorksharingDirective(DKind)) {
2848 // Lower bound variable, initialized with zero.
2849 VarDecl *LBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
2850 LB = SemaRef.BuildDeclRefExpr(LBDecl, VType, VK_LValue, InitLoc);
2851 SemaRef.AddInitializerToDecl(
2852 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2853 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2854
2855 // Upper bound variable, initialized with last iteration number.
2856 VarDecl *UBDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
2857 UB = SemaRef.BuildDeclRefExpr(UBDecl, VType, VK_LValue, InitLoc);
2858 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
2859 /*DirectInit*/ false,
2860 /*TypeMayContainAuto*/ false);
2861
2862 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
2863 // This will be used to implement clause 'lastprivate'.
2864 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
2865 VarDecl *ILDecl = BuildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
2866 IL = SemaRef.BuildDeclRefExpr(ILDecl, Int32Ty, VK_LValue, InitLoc);
2867 SemaRef.AddInitializerToDecl(
2868 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
2869 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2870
2871 // Stride variable returned by runtime (we initialize it to 1 by default).
2872 VarDecl *STDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
2873 ST = SemaRef.BuildDeclRefExpr(STDecl, VType, VK_LValue, InitLoc);
2874 SemaRef.AddInitializerToDecl(
2875 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
2876 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
2877
2878 // Build expression: UB = min(UB, LastIteration)
2879 // It is nesessary for CodeGen of directives with static scheduling.
2880 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
2881 UB.get(), LastIteration.get());
2882 ExprResult CondOp = SemaRef.ActOnConditionalOp(
2883 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
2884 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
2885 CondOp.get());
2886 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
2887 }
2888
2889 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002890 ExprResult IV;
2891 ExprResult Init;
2892 {
Alexander Musmanc6388682014-12-15 07:07:06 +00002893 VarDecl *IVDecl = BuildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
2894 IV = SemaRef.BuildDeclRefExpr(IVDecl, VType, VK_LValue, InitLoc);
2895 Expr *RHS = isOpenMPWorksharingDirective(DKind)
2896 ? LB.get()
2897 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
2898 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
2899 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002900 }
2901
Alexander Musmanc6388682014-12-15 07:07:06 +00002902 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002903 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00002904 ExprResult Cond =
2905 isOpenMPWorksharingDirective(DKind)
2906 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
2907 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
2908 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002909 // Loop condition with 1 iteration separated (IV < LastIteration)
2910 ExprResult SeparatedCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
2911 IV.get(), LastIteration.get());
2912
2913 // Loop increment (IV = IV + 1)
2914 SourceLocation IncLoc;
2915 ExprResult Inc =
2916 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
2917 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
2918 if (!Inc.isUsable())
2919 return 0;
2920 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00002921 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
2922 if (!Inc.isUsable())
2923 return 0;
2924
2925 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
2926 // Used for directives with static scheduling.
2927 ExprResult NextLB, NextUB;
2928 if (isOpenMPWorksharingDirective(DKind)) {
2929 // LB + ST
2930 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
2931 if (!NextLB.isUsable())
2932 return 0;
2933 // LB = LB + ST
2934 NextLB =
2935 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
2936 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
2937 if (!NextLB.isUsable())
2938 return 0;
2939 // UB + ST
2940 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
2941 if (!NextUB.isUsable())
2942 return 0;
2943 // UB = UB + ST
2944 NextUB =
2945 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
2946 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
2947 if (!NextUB.isUsable())
2948 return 0;
2949 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002950
2951 // Build updates and final values of the loop counters.
2952 bool HasErrors = false;
2953 Built.Counters.resize(NestedLoopCount);
2954 Built.Updates.resize(NestedLoopCount);
2955 Built.Finals.resize(NestedLoopCount);
2956 {
2957 ExprResult Div;
2958 // Go from inner nested loop to outer.
2959 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
2960 LoopIterationSpace &IS = IterSpaces[Cnt];
2961 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
2962 // Build: Iter = (IV / Div) % IS.NumIters
2963 // where Div is product of previous iterations' IS.NumIters.
2964 ExprResult Iter;
2965 if (Div.isUsable()) {
2966 Iter =
2967 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
2968 } else {
2969 Iter = IV;
2970 assert((Cnt == (int)NestedLoopCount - 1) &&
2971 "unusable div expected on first iteration only");
2972 }
2973
2974 if (Cnt != 0 && Iter.isUsable())
2975 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
2976 IS.NumIterations);
2977 if (!Iter.isUsable()) {
2978 HasErrors = true;
2979 break;
2980 }
2981
2982 // Build update: IS.CounterVar = IS.Start + Iter * IS.Step
2983 ExprResult Update =
2984 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, IS.CounterVar,
2985 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
2986 if (!Update.isUsable()) {
2987 HasErrors = true;
2988 break;
2989 }
2990
2991 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
2992 ExprResult Final = BuildCounterUpdate(
2993 SemaRef, CurScope, UpdLoc, IS.CounterVar, IS.CounterInit,
2994 IS.NumIterations, IS.CounterStep, IS.Subtract);
2995 if (!Final.isUsable()) {
2996 HasErrors = true;
2997 break;
2998 }
2999
3000 // Build Div for the next iteration: Div <- Div * IS.NumIters
3001 if (Cnt != 0) {
3002 if (Div.isUnset())
3003 Div = IS.NumIterations;
3004 else
3005 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3006 IS.NumIterations);
3007
3008 // Add parentheses (for debugging purposes only).
3009 if (Div.isUsable())
3010 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3011 if (!Div.isUsable()) {
3012 HasErrors = true;
3013 break;
3014 }
3015 }
3016 if (!Update.isUsable() || !Final.isUsable()) {
3017 HasErrors = true;
3018 break;
3019 }
3020 // Save results
3021 Built.Counters[Cnt] = IS.CounterVar;
3022 Built.Updates[Cnt] = Update.get();
3023 Built.Finals[Cnt] = Final.get();
3024 }
3025 }
3026
3027 if (HasErrors)
3028 return 0;
3029
3030 // Save results
3031 Built.IterationVarRef = IV.get();
3032 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003033 Built.NumIterations = NumIterations.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003034 Built.CalcLastIteration = CalcLastIteration.get();
3035 Built.PreCond = PreCond.get();
3036 Built.Cond = Cond.get();
3037 Built.SeparatedCond = SeparatedCond.get();
3038 Built.Init = Init.get();
3039 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003040 Built.LB = LB.get();
3041 Built.UB = UB.get();
3042 Built.IL = IL.get();
3043 Built.ST = ST.get();
3044 Built.EUB = EUB.get();
3045 Built.NLB = NextLB.get();
3046 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003047
Alexey Bataevabfc0692014-06-25 06:52:00 +00003048 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003049}
3050
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003051static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Alexey Bataevc925aa32015-04-27 08:00:32 +00003052 auto &&CollapseFilter = [](const OMPClause *C) -> bool {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003053 return C->getClauseKind() == OMPC_collapse;
3054 };
3055 OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
Alexey Bataevc925aa32015-04-27 08:00:32 +00003056 Clauses, std::move(CollapseFilter));
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003057 if (I)
3058 return cast<OMPCollapseClause>(*I)->getNumForLoops();
3059 return nullptr;
3060}
3061
Alexey Bataev4acb8592014-07-07 13:01:15 +00003062StmtResult Sema::ActOnOpenMPSimdDirective(
3063 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3064 SourceLocation EndLoc,
3065 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003066 OMPLoopDirective::HelperExprs B;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003067 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003068 unsigned NestedLoopCount =
3069 CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003070 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003071 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003072 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003073
Alexander Musmana5f070a2014-10-01 06:03:56 +00003074 assert((CurContext->isDependentContext() || B.builtAll()) &&
3075 "omp simd loop exprs were not built");
3076
Alexander Musman3276a272015-03-21 10:12:56 +00003077 if (!CurContext->isDependentContext()) {
3078 // Finalize the clauses that need pre-built expressions for CodeGen.
3079 for (auto C : Clauses) {
3080 if (auto LC = dyn_cast<OMPLinearClause>(C))
3081 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3082 B.NumIterations, *this, CurScope))
3083 return StmtError();
3084 }
3085 }
3086
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003087 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003088 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3089 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003090}
3091
Alexey Bataev4acb8592014-07-07 13:01:15 +00003092StmtResult Sema::ActOnOpenMPForDirective(
3093 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3094 SourceLocation EndLoc,
3095 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003096 OMPLoopDirective::HelperExprs B;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003097 // In presence of clause 'collapse', it will define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003098 unsigned NestedLoopCount =
3099 CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003100 *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003101 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003102 return StmtError();
3103
Alexander Musmana5f070a2014-10-01 06:03:56 +00003104 assert((CurContext->isDependentContext() || B.builtAll()) &&
3105 "omp for loop exprs were not built");
3106
Alexey Bataevf29276e2014-06-18 04:14:57 +00003107 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003108 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3109 Clauses, AStmt, B);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003110}
3111
Alexander Musmanf82886e2014-09-18 05:12:34 +00003112StmtResult Sema::ActOnOpenMPForSimdDirective(
3113 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3114 SourceLocation EndLoc,
3115 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003116 OMPLoopDirective::HelperExprs B;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003117 // In presence of clause 'collapse', it will define the nested loops number.
3118 unsigned NestedLoopCount =
3119 CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003120 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003121 if (NestedLoopCount == 0)
3122 return StmtError();
3123
Alexander Musmanc6388682014-12-15 07:07:06 +00003124 assert((CurContext->isDependentContext() || B.builtAll()) &&
3125 "omp for simd loop exprs were not built");
3126
Alexander Musmanf82886e2014-09-18 05:12:34 +00003127 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003128 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3129 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003130}
3131
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003132StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3133 Stmt *AStmt,
3134 SourceLocation StartLoc,
3135 SourceLocation EndLoc) {
3136 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3137 auto BaseStmt = AStmt;
3138 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3139 BaseStmt = CS->getCapturedStmt();
3140 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3141 auto S = C->children();
3142 if (!S)
3143 return StmtError();
3144 // All associated statements must be '#pragma omp section' except for
3145 // the first one.
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003146 for (++S; S; ++S) {
3147 auto SectionStmt = *S;
3148 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3149 if (SectionStmt)
3150 Diag(SectionStmt->getLocStart(),
3151 diag::err_omp_sections_substmt_not_section);
3152 return StmtError();
3153 }
3154 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003155 } else {
3156 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3157 return StmtError();
3158 }
3159
3160 getCurFunction()->setHasBranchProtectedScope();
3161
3162 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3163 AStmt);
3164}
3165
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003166StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3167 SourceLocation StartLoc,
3168 SourceLocation EndLoc) {
3169 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3170
3171 getCurFunction()->setHasBranchProtectedScope();
3172
3173 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3174}
3175
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003176StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3177 Stmt *AStmt,
3178 SourceLocation StartLoc,
3179 SourceLocation EndLoc) {
Alexey Bataev74a05c92014-07-15 02:55:09 +00003180 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3181
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003182 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003183
Alexey Bataev3255bf32015-01-19 05:20:46 +00003184 // OpenMP [2.7.3, single Construct, Restrictions]
3185 // The copyprivate clause must not be used with the nowait clause.
3186 OMPClause *Nowait = nullptr;
3187 OMPClause *Copyprivate = nullptr;
3188 for (auto *Clause : Clauses) {
3189 if (Clause->getClauseKind() == OMPC_nowait)
3190 Nowait = Clause;
3191 else if (Clause->getClauseKind() == OMPC_copyprivate)
3192 Copyprivate = Clause;
3193 if (Copyprivate && Nowait) {
3194 Diag(Copyprivate->getLocStart(),
3195 diag::err_omp_single_copyprivate_with_nowait);
3196 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3197 return StmtError();
3198 }
3199 }
3200
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003201 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3202}
3203
Alexander Musman80c22892014-07-17 08:54:58 +00003204StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3205 SourceLocation StartLoc,
3206 SourceLocation EndLoc) {
3207 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3208
3209 getCurFunction()->setHasBranchProtectedScope();
3210
3211 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3212}
3213
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003214StmtResult
3215Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3216 Stmt *AStmt, SourceLocation StartLoc,
3217 SourceLocation EndLoc) {
3218 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3219
3220 getCurFunction()->setHasBranchProtectedScope();
3221
3222 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3223 AStmt);
3224}
3225
Alexey Bataev4acb8592014-07-07 13:01:15 +00003226StmtResult Sema::ActOnOpenMPParallelForDirective(
3227 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3228 SourceLocation EndLoc,
3229 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3230 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3231 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3232 // 1.2.2 OpenMP Language Terminology
3233 // Structured block - An executable statement with a single entry at the
3234 // top and a single exit at the bottom.
3235 // The point of exit cannot be a branch out of the structured block.
3236 // longjmp() and throw() must not violate the entry/exit criteria.
3237 CS->getCapturedDecl()->setNothrow();
3238
Alexander Musmanc6388682014-12-15 07:07:06 +00003239 OMPLoopDirective::HelperExprs B;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003240 // In presence of clause 'collapse', it will define the nested loops number.
3241 unsigned NestedLoopCount =
3242 CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003243 *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003244 if (NestedLoopCount == 0)
3245 return StmtError();
3246
Alexander Musmana5f070a2014-10-01 06:03:56 +00003247 assert((CurContext->isDependentContext() || B.builtAll()) &&
3248 "omp parallel for loop exprs were not built");
3249
Alexey Bataev4acb8592014-07-07 13:01:15 +00003250 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003251 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3252 NestedLoopCount, Clauses, AStmt, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003253}
3254
Alexander Musmane4e893b2014-09-23 09:33:00 +00003255StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3256 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3257 SourceLocation EndLoc,
3258 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3259 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3260 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3261 // 1.2.2 OpenMP Language Terminology
3262 // Structured block - An executable statement with a single entry at the
3263 // top and a single exit at the bottom.
3264 // The point of exit cannot be a branch out of the structured block.
3265 // longjmp() and throw() must not violate the entry/exit criteria.
3266 CS->getCapturedDecl()->setNothrow();
3267
Alexander Musmanc6388682014-12-15 07:07:06 +00003268 OMPLoopDirective::HelperExprs B;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003269 // In presence of clause 'collapse', it will define the nested loops number.
3270 unsigned NestedLoopCount =
3271 CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003272 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003273 if (NestedLoopCount == 0)
3274 return StmtError();
3275
3276 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003277 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00003278 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003279}
3280
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003281StmtResult
3282Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3283 Stmt *AStmt, SourceLocation StartLoc,
3284 SourceLocation EndLoc) {
3285 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3286 auto BaseStmt = AStmt;
3287 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3288 BaseStmt = CS->getCapturedStmt();
3289 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3290 auto S = C->children();
3291 if (!S)
3292 return StmtError();
3293 // All associated statements must be '#pragma omp section' except for
3294 // the first one.
3295 for (++S; S; ++S) {
3296 auto SectionStmt = *S;
3297 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3298 if (SectionStmt)
3299 Diag(SectionStmt->getLocStart(),
3300 diag::err_omp_parallel_sections_substmt_not_section);
3301 return StmtError();
3302 }
3303 }
3304 } else {
3305 Diag(AStmt->getLocStart(),
3306 diag::err_omp_parallel_sections_not_compound_stmt);
3307 return StmtError();
3308 }
3309
3310 getCurFunction()->setHasBranchProtectedScope();
3311
3312 return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3313 Clauses, AStmt);
3314}
3315
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003316StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3317 Stmt *AStmt, SourceLocation StartLoc,
3318 SourceLocation EndLoc) {
3319 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3320 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3321 // 1.2.2 OpenMP Language Terminology
3322 // Structured block - An executable statement with a single entry at the
3323 // top and a single exit at the bottom.
3324 // The point of exit cannot be a branch out of the structured block.
3325 // longjmp() and throw() must not violate the entry/exit criteria.
3326 CS->getCapturedDecl()->setNothrow();
3327
3328 getCurFunction()->setHasBranchProtectedScope();
3329
3330 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3331}
3332
Alexey Bataev68446b72014-07-18 07:47:19 +00003333StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3334 SourceLocation EndLoc) {
3335 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3336}
3337
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003338StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3339 SourceLocation EndLoc) {
3340 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3341}
3342
Alexey Bataev2df347a2014-07-18 10:17:07 +00003343StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3344 SourceLocation EndLoc) {
3345 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3346}
3347
Alexey Bataev6125da92014-07-21 11:26:11 +00003348StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3349 SourceLocation StartLoc,
3350 SourceLocation EndLoc) {
3351 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3352 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3353}
3354
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003355StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3356 SourceLocation StartLoc,
3357 SourceLocation EndLoc) {
3358 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3359
3360 getCurFunction()->setHasBranchProtectedScope();
3361
3362 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3363}
3364
Alexey Bataev1d160b12015-03-13 12:27:31 +00003365namespace {
3366/// \brief Helper class for checking expression in 'omp atomic [update]'
3367/// construct.
3368class OpenMPAtomicUpdateChecker {
3369 /// \brief Error results for atomic update expressions.
3370 enum ExprAnalysisErrorCode {
3371 /// \brief A statement is not an expression statement.
3372 NotAnExpression,
3373 /// \brief Expression is not builtin binary or unary operation.
3374 NotABinaryOrUnaryExpression,
3375 /// \brief Unary operation is not post-/pre- increment/decrement operation.
3376 NotAnUnaryIncDecExpression,
3377 /// \brief An expression is not of scalar type.
3378 NotAScalarType,
3379 /// \brief A binary operation is not an assignment operation.
3380 NotAnAssignmentOp,
3381 /// \brief RHS part of the binary operation is not a binary expression.
3382 NotABinaryExpression,
3383 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3384 /// expression.
3385 NotABinaryOperator,
3386 /// \brief RHS binary operation does not have reference to the updated LHS
3387 /// part.
3388 NotAnUpdateExpression,
3389 /// \brief No errors is found.
3390 NoError
3391 };
3392 /// \brief Reference to Sema.
3393 Sema &SemaRef;
3394 /// \brief A location for note diagnostics (when error is found).
3395 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003396 /// \brief 'x' lvalue part of the source atomic expression.
3397 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003398 /// \brief 'expr' rvalue part of the source atomic expression.
3399 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003400 /// \brief Helper expression of the form
3401 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3402 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3403 Expr *UpdateExpr;
3404 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3405 /// important for non-associative operations.
3406 bool IsXLHSInRHSPart;
3407 BinaryOperatorKind Op;
3408 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003409 /// \brief true if the source expression is a postfix unary operation, false
3410 /// if it is a prefix unary operation.
3411 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003412
3413public:
3414 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00003415 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00003416 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00003417 /// \brief Check specified statement that it is suitable for 'atomic update'
3418 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00003419 /// expression. If DiagId and NoteId == 0, then only check is performed
3420 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00003421 /// \param DiagId Diagnostic which should be emitted if error is found.
3422 /// \param NoteId Diagnostic note for the main error message.
3423 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00003424 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003425 /// \brief Return the 'x' lvalue part of the source atomic expression.
3426 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00003427 /// \brief Return the 'expr' rvalue part of the source atomic expression.
3428 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00003429 /// \brief Return the update expression used in calculation of the updated
3430 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3431 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3432 Expr *getUpdateExpr() const { return UpdateExpr; }
3433 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3434 /// false otherwise.
3435 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3436
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() const { return IsPostfixUpdate; }
3440
Alexey Bataev1d160b12015-03-13 12:27:31 +00003441private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00003442 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3443 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00003444};
3445} // namespace
3446
3447bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3448 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3449 ExprAnalysisErrorCode ErrorFound = NoError;
3450 SourceLocation ErrorLoc, NoteLoc;
3451 SourceRange ErrorRange, NoteRange;
3452 // Allowed constructs are:
3453 // x = x binop expr;
3454 // x = expr binop x;
3455 if (AtomicBinOp->getOpcode() == BO_Assign) {
3456 X = AtomicBinOp->getLHS();
3457 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3458 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3459 if (AtomicInnerBinOp->isMultiplicativeOp() ||
3460 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3461 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003462 Op = AtomicInnerBinOp->getOpcode();
3463 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003464 auto *LHS = AtomicInnerBinOp->getLHS();
3465 auto *RHS = AtomicInnerBinOp->getRHS();
3466 llvm::FoldingSetNodeID XId, LHSId, RHSId;
3467 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3468 /*Canonical=*/true);
3469 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3470 /*Canonical=*/true);
3471 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3472 /*Canonical=*/true);
3473 if (XId == LHSId) {
3474 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003475 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003476 } else if (XId == RHSId) {
3477 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003478 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003479 } else {
3480 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3481 ErrorRange = AtomicInnerBinOp->getSourceRange();
3482 NoteLoc = X->getExprLoc();
3483 NoteRange = X->getSourceRange();
3484 ErrorFound = NotAnUpdateExpression;
3485 }
3486 } else {
3487 ErrorLoc = AtomicInnerBinOp->getExprLoc();
3488 ErrorRange = AtomicInnerBinOp->getSourceRange();
3489 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3490 NoteRange = SourceRange(NoteLoc, NoteLoc);
3491 ErrorFound = NotABinaryOperator;
3492 }
3493 } else {
3494 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3495 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3496 ErrorFound = NotABinaryExpression;
3497 }
3498 } else {
3499 ErrorLoc = AtomicBinOp->getExprLoc();
3500 ErrorRange = AtomicBinOp->getSourceRange();
3501 NoteLoc = AtomicBinOp->getOperatorLoc();
3502 NoteRange = SourceRange(NoteLoc, NoteLoc);
3503 ErrorFound = NotAnAssignmentOp;
3504 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003505 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003506 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3507 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3508 return true;
3509 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003510 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003511 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003512}
3513
3514bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3515 unsigned NoteId) {
3516 ExprAnalysisErrorCode ErrorFound = NoError;
3517 SourceLocation ErrorLoc, NoteLoc;
3518 SourceRange ErrorRange, NoteRange;
3519 // Allowed constructs are:
3520 // x++;
3521 // x--;
3522 // ++x;
3523 // --x;
3524 // x binop= expr;
3525 // x = x binop expr;
3526 // x = expr binop x;
3527 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3528 AtomicBody = AtomicBody->IgnoreParenImpCasts();
3529 if (AtomicBody->getType()->isScalarType() ||
3530 AtomicBody->isInstantiationDependent()) {
3531 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3532 AtomicBody->IgnoreParenImpCasts())) {
3533 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003534 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00003535 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00003536 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003537 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003538 X = AtomicCompAssignOp->getLHS();
3539 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003540 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3541 AtomicBody->IgnoreParenImpCasts())) {
3542 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00003543 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3544 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003545 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00003546 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3547 // Check for Unary Operation
3548 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003549 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003550 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3551 OpLoc = AtomicUnaryOp->getOperatorLoc();
3552 X = AtomicUnaryOp->getSubExpr();
3553 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3554 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003555 } else {
3556 ErrorFound = NotAnUnaryIncDecExpression;
3557 ErrorLoc = AtomicUnaryOp->getExprLoc();
3558 ErrorRange = AtomicUnaryOp->getSourceRange();
3559 NoteLoc = AtomicUnaryOp->getOperatorLoc();
3560 NoteRange = SourceRange(NoteLoc, NoteLoc);
3561 }
3562 } else {
3563 ErrorFound = NotABinaryOrUnaryExpression;
3564 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3565 NoteRange = ErrorRange = AtomicBody->getSourceRange();
3566 }
3567 } else {
3568 ErrorFound = NotAScalarType;
3569 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3570 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3571 }
3572 } else {
3573 ErrorFound = NotAnExpression;
3574 NoteLoc = ErrorLoc = S->getLocStart();
3575 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3576 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00003577 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003578 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3579 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3580 return true;
3581 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00003582 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00003583 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00003584 // Build an update expression of form 'OpaqueValueExpr(x) binop
3585 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3586 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3587 auto *OVEX = new (SemaRef.getASTContext())
3588 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3589 auto *OVEExpr = new (SemaRef.getASTContext())
3590 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3591 auto Update =
3592 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3593 IsXLHSInRHSPart ? OVEExpr : OVEX);
3594 if (Update.isInvalid())
3595 return true;
3596 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3597 Sema::AA_Casting);
3598 if (Update.isInvalid())
3599 return true;
3600 UpdateExpr = Update.get();
3601 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00003602 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00003603}
3604
Alexey Bataev0162e452014-07-22 10:10:35 +00003605StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3606 Stmt *AStmt,
3607 SourceLocation StartLoc,
3608 SourceLocation EndLoc) {
3609 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003610 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00003611 // 1.2.2 OpenMP Language Terminology
3612 // Structured block - An executable statement with a single entry at the
3613 // top and a single exit at the bottom.
3614 // The point of exit cannot be a branch out of the structured block.
3615 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00003616 OpenMPClauseKind AtomicKind = OMPC_unknown;
3617 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003618 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00003619 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00003620 C->getClauseKind() == OMPC_update ||
3621 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00003622 if (AtomicKind != OMPC_unknown) {
3623 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3624 << SourceRange(C->getLocStart(), C->getLocEnd());
3625 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3626 << getOpenMPClauseName(AtomicKind);
3627 } else {
3628 AtomicKind = C->getClauseKind();
3629 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00003630 }
3631 }
3632 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003633
Alexey Bataev459dec02014-07-24 06:46:57 +00003634 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00003635 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3636 Body = EWC->getSubExpr();
3637
Alexey Bataev62cec442014-11-18 10:14:22 +00003638 Expr *X = nullptr;
3639 Expr *V = nullptr;
3640 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00003641 Expr *UE = nullptr;
3642 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003643 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00003644 // OpenMP [2.12.6, atomic Construct]
3645 // In the next expressions:
3646 // * x and v (as applicable) are both l-value expressions with scalar type.
3647 // * During the execution of an atomic region, multiple syntactic
3648 // occurrences of x must designate the same storage location.
3649 // * Neither of v and expr (as applicable) may access the storage location
3650 // designated by x.
3651 // * Neither of x and expr (as applicable) may access the storage location
3652 // designated by v.
3653 // * expr is an expression with scalar type.
3654 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3655 // * binop, binop=, ++, and -- are not overloaded operators.
3656 // * The expression x binop expr must be numerically equivalent to x binop
3657 // (expr). This requirement is satisfied if the operators in expr have
3658 // precedence greater than binop, or by using parentheses around expr or
3659 // subexpressions of expr.
3660 // * The expression expr binop x must be numerically equivalent to (expr)
3661 // binop x. This requirement is satisfied if the operators in expr have
3662 // precedence equal to or greater than binop, or by using parentheses around
3663 // expr or subexpressions of expr.
3664 // * For forms that allow multiple occurrences of x, the number of times
3665 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00003666 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003667 enum {
3668 NotAnExpression,
3669 NotAnAssignmentOp,
3670 NotAScalarType,
3671 NotAnLValue,
3672 NoError
3673 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00003674 SourceLocation ErrorLoc, NoteLoc;
3675 SourceRange ErrorRange, NoteRange;
3676 // If clause is read:
3677 // v = x;
3678 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3679 auto AtomicBinOp =
3680 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3681 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3682 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3683 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3684 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3685 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3686 if (!X->isLValue() || !V->isLValue()) {
3687 auto NotLValueExpr = X->isLValue() ? V : X;
3688 ErrorFound = NotAnLValue;
3689 ErrorLoc = AtomicBinOp->getExprLoc();
3690 ErrorRange = AtomicBinOp->getSourceRange();
3691 NoteLoc = NotLValueExpr->getExprLoc();
3692 NoteRange = NotLValueExpr->getSourceRange();
3693 }
3694 } else if (!X->isInstantiationDependent() ||
3695 !V->isInstantiationDependent()) {
3696 auto NotScalarExpr =
3697 (X->isInstantiationDependent() || X->getType()->isScalarType())
3698 ? V
3699 : X;
3700 ErrorFound = NotAScalarType;
3701 ErrorLoc = AtomicBinOp->getExprLoc();
3702 ErrorRange = AtomicBinOp->getSourceRange();
3703 NoteLoc = NotScalarExpr->getExprLoc();
3704 NoteRange = NotScalarExpr->getSourceRange();
3705 }
3706 } else {
3707 ErrorFound = NotAnAssignmentOp;
3708 ErrorLoc = AtomicBody->getExprLoc();
3709 ErrorRange = AtomicBody->getSourceRange();
3710 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3711 : AtomicBody->getExprLoc();
3712 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3713 : AtomicBody->getSourceRange();
3714 }
3715 } else {
3716 ErrorFound = NotAnExpression;
3717 NoteLoc = ErrorLoc = Body->getLocStart();
3718 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003719 }
Alexey Bataev62cec442014-11-18 10:14:22 +00003720 if (ErrorFound != NoError) {
3721 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3722 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003723 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3724 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00003725 return StmtError();
3726 } else if (CurContext->isDependentContext())
3727 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00003728 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003729 enum {
3730 NotAnExpression,
3731 NotAnAssignmentOp,
3732 NotAScalarType,
3733 NotAnLValue,
3734 NoError
3735 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00003736 SourceLocation ErrorLoc, NoteLoc;
3737 SourceRange ErrorRange, NoteRange;
3738 // If clause is write:
3739 // x = expr;
3740 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3741 auto AtomicBinOp =
3742 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3743 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00003744 X = AtomicBinOp->getLHS();
3745 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00003746 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3747 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
3748 if (!X->isLValue()) {
3749 ErrorFound = NotAnLValue;
3750 ErrorLoc = AtomicBinOp->getExprLoc();
3751 ErrorRange = AtomicBinOp->getSourceRange();
3752 NoteLoc = X->getExprLoc();
3753 NoteRange = X->getSourceRange();
3754 }
3755 } else if (!X->isInstantiationDependent() ||
3756 !E->isInstantiationDependent()) {
3757 auto NotScalarExpr =
3758 (X->isInstantiationDependent() || X->getType()->isScalarType())
3759 ? E
3760 : X;
3761 ErrorFound = NotAScalarType;
3762 ErrorLoc = AtomicBinOp->getExprLoc();
3763 ErrorRange = AtomicBinOp->getSourceRange();
3764 NoteLoc = NotScalarExpr->getExprLoc();
3765 NoteRange = NotScalarExpr->getSourceRange();
3766 }
3767 } else {
3768 ErrorFound = NotAnAssignmentOp;
3769 ErrorLoc = AtomicBody->getExprLoc();
3770 ErrorRange = AtomicBody->getSourceRange();
3771 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3772 : AtomicBody->getExprLoc();
3773 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3774 : AtomicBody->getSourceRange();
3775 }
3776 } else {
3777 ErrorFound = NotAnExpression;
3778 NoteLoc = ErrorLoc = Body->getLocStart();
3779 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00003780 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00003781 if (ErrorFound != NoError) {
3782 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
3783 << ErrorRange;
3784 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3785 << NoteRange;
3786 return StmtError();
3787 } else if (CurContext->isDependentContext())
3788 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00003789 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00003790 // If clause is update:
3791 // x++;
3792 // x--;
3793 // ++x;
3794 // --x;
3795 // x binop= expr;
3796 // x = x binop expr;
3797 // x = expr binop x;
3798 OpenMPAtomicUpdateChecker Checker(*this);
3799 if (Checker.checkStatement(
3800 Body, (AtomicKind == OMPC_update)
3801 ? diag::err_omp_atomic_update_not_expression_statement
3802 : diag::err_omp_atomic_not_expression_statement,
3803 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00003804 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00003805 if (!CurContext->isDependentContext()) {
3806 E = Checker.getExpr();
3807 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00003808 UE = Checker.getUpdateExpr();
3809 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00003810 }
Alexey Bataev459dec02014-07-24 06:46:57 +00003811 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00003812 enum {
3813 NotAnAssignmentOp,
3814 NotACompoundStatement,
3815 NotTwoSubstatements,
3816 NotASpecificExpression,
3817 NoError
3818 } ErrorFound = NoError;
3819 SourceLocation ErrorLoc, NoteLoc;
3820 SourceRange ErrorRange, NoteRange;
3821 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
3822 // If clause is a capture:
3823 // v = x++;
3824 // v = x--;
3825 // v = ++x;
3826 // v = --x;
3827 // v = x binop= expr;
3828 // v = x = x binop expr;
3829 // v = x = expr binop x;
3830 auto *AtomicBinOp =
3831 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3832 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3833 V = AtomicBinOp->getLHS();
3834 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3835 OpenMPAtomicUpdateChecker Checker(*this);
3836 if (Checker.checkStatement(
3837 Body, diag::err_omp_atomic_capture_not_expression_statement,
3838 diag::note_omp_atomic_update))
3839 return StmtError();
3840 E = Checker.getExpr();
3841 X = Checker.getX();
3842 UE = Checker.getUpdateExpr();
3843 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
3844 IsPostfixUpdate = Checker.isPostfixUpdate();
3845 } else {
3846 ErrorLoc = AtomicBody->getExprLoc();
3847 ErrorRange = AtomicBody->getSourceRange();
3848 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3849 : AtomicBody->getExprLoc();
3850 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3851 : AtomicBody->getSourceRange();
3852 ErrorFound = NotAnAssignmentOp;
3853 }
3854 if (ErrorFound != NoError) {
3855 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
3856 << ErrorRange;
3857 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
3858 return StmtError();
3859 } else if (CurContext->isDependentContext()) {
3860 UE = V = E = X = nullptr;
3861 }
3862 } else {
3863 // If clause is a capture:
3864 // { v = x; x = expr; }
3865 // { v = x; x++; }
3866 // { v = x; x--; }
3867 // { v = x; ++x; }
3868 // { v = x; --x; }
3869 // { v = x; x binop= expr; }
3870 // { v = x; x = x binop expr; }
3871 // { v = x; x = expr binop x; }
3872 // { x++; v = x; }
3873 // { x--; v = x; }
3874 // { ++x; v = x; }
3875 // { --x; v = x; }
3876 // { x binop= expr; v = x; }
3877 // { x = x binop expr; v = x; }
3878 // { x = expr binop x; v = x; }
3879 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
3880 // Check that this is { expr1; expr2; }
3881 if (CS->size() == 2) {
3882 auto *First = CS->body_front();
3883 auto *Second = CS->body_back();
3884 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
3885 First = EWC->getSubExpr()->IgnoreParenImpCasts();
3886 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
3887 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
3888 // Need to find what subexpression is 'v' and what is 'x'.
3889 OpenMPAtomicUpdateChecker Checker(*this);
3890 bool IsUpdateExprFound = !Checker.checkStatement(Second);
3891 BinaryOperator *BinOp = nullptr;
3892 if (IsUpdateExprFound) {
3893 BinOp = dyn_cast<BinaryOperator>(First);
3894 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3895 }
3896 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3897 // { v = x; x++; }
3898 // { v = x; x--; }
3899 // { v = x; ++x; }
3900 // { v = x; --x; }
3901 // { v = x; x binop= expr; }
3902 // { v = x; x = x binop expr; }
3903 // { v = x; x = expr binop x; }
3904 // Check that the first expression has form v = x.
3905 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3906 llvm::FoldingSetNodeID XId, PossibleXId;
3907 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3908 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3909 IsUpdateExprFound = XId == PossibleXId;
3910 if (IsUpdateExprFound) {
3911 V = BinOp->getLHS();
3912 X = Checker.getX();
3913 E = Checker.getExpr();
3914 UE = Checker.getUpdateExpr();
3915 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003916 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003917 }
3918 }
3919 if (!IsUpdateExprFound) {
3920 IsUpdateExprFound = !Checker.checkStatement(First);
3921 BinOp = nullptr;
3922 if (IsUpdateExprFound) {
3923 BinOp = dyn_cast<BinaryOperator>(Second);
3924 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
3925 }
3926 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
3927 // { x++; v = x; }
3928 // { x--; v = x; }
3929 // { ++x; v = x; }
3930 // { --x; v = x; }
3931 // { x binop= expr; v = x; }
3932 // { x = x binop expr; v = x; }
3933 // { x = expr binop x; v = x; }
3934 // Check that the second expression has form v = x.
3935 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
3936 llvm::FoldingSetNodeID XId, PossibleXId;
3937 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
3938 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
3939 IsUpdateExprFound = XId == PossibleXId;
3940 if (IsUpdateExprFound) {
3941 V = BinOp->getLHS();
3942 X = Checker.getX();
3943 E = Checker.getExpr();
3944 UE = Checker.getUpdateExpr();
3945 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00003946 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00003947 }
3948 }
3949 }
3950 if (!IsUpdateExprFound) {
3951 // { v = x; x = expr; }
3952 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
3953 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
3954 ErrorFound = NotAnAssignmentOp;
3955 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
3956 : First->getLocStart();
3957 NoteRange = ErrorRange = FirstBinOp
3958 ? FirstBinOp->getSourceRange()
3959 : SourceRange(ErrorLoc, ErrorLoc);
3960 } else {
3961 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
3962 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
3963 ErrorFound = NotAnAssignmentOp;
3964 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
3965 : Second->getLocStart();
3966 NoteRange = ErrorRange = SecondBinOp
3967 ? SecondBinOp->getSourceRange()
3968 : SourceRange(ErrorLoc, ErrorLoc);
3969 } else {
3970 auto *PossibleXRHSInFirst =
3971 FirstBinOp->getRHS()->IgnoreParenImpCasts();
3972 auto *PossibleXLHSInSecond =
3973 SecondBinOp->getLHS()->IgnoreParenImpCasts();
3974 llvm::FoldingSetNodeID X1Id, X2Id;
3975 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
3976 PossibleXLHSInSecond->Profile(X2Id, Context,
3977 /*Canonical=*/true);
3978 IsUpdateExprFound = X1Id == X2Id;
3979 if (IsUpdateExprFound) {
3980 V = FirstBinOp->getLHS();
3981 X = SecondBinOp->getLHS();
3982 E = SecondBinOp->getRHS();
3983 UE = nullptr;
3984 IsXLHSInRHSPart = false;
3985 IsPostfixUpdate = true;
3986 } else {
3987 ErrorFound = NotASpecificExpression;
3988 ErrorLoc = FirstBinOp->getExprLoc();
3989 ErrorRange = FirstBinOp->getSourceRange();
3990 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
3991 NoteRange = SecondBinOp->getRHS()->getSourceRange();
3992 }
3993 }
3994 }
3995 }
3996 } else {
3997 NoteLoc = ErrorLoc = Body->getLocStart();
3998 NoteRange = ErrorRange =
3999 SourceRange(Body->getLocStart(), Body->getLocStart());
4000 ErrorFound = NotTwoSubstatements;
4001 }
4002 } else {
4003 NoteLoc = ErrorLoc = Body->getLocStart();
4004 NoteRange = ErrorRange =
4005 SourceRange(Body->getLocStart(), Body->getLocStart());
4006 ErrorFound = NotACompoundStatement;
4007 }
4008 if (ErrorFound != NoError) {
4009 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4010 << ErrorRange;
4011 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4012 return StmtError();
4013 } else if (CurContext->isDependentContext()) {
4014 UE = V = E = X = nullptr;
4015 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004016 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004017 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004018
4019 getCurFunction()->setHasBranchProtectedScope();
4020
Alexey Bataev62cec442014-11-18 10:14:22 +00004021 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004022 X, V, E, UE, IsXLHSInRHSPart,
4023 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004024}
4025
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004026StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4027 Stmt *AStmt,
4028 SourceLocation StartLoc,
4029 SourceLocation EndLoc) {
4030 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4031
Alexey Bataev13314bf2014-10-09 04:18:56 +00004032 // OpenMP [2.16, Nesting of Regions]
4033 // If specified, a teams construct must be contained within a target
4034 // construct. That target construct must contain no statements or directives
4035 // outside of the teams construct.
4036 if (DSAStack->hasInnerTeamsRegion()) {
4037 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4038 bool OMPTeamsFound = true;
4039 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4040 auto I = CS->body_begin();
4041 while (I != CS->body_end()) {
4042 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4043 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4044 OMPTeamsFound = false;
4045 break;
4046 }
4047 ++I;
4048 }
4049 assert(I != CS->body_end() && "Not found statement");
4050 S = *I;
4051 }
4052 if (!OMPTeamsFound) {
4053 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4054 Diag(DSAStack->getInnerTeamsRegionLoc(),
4055 diag::note_omp_nested_teams_construct_here);
4056 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4057 << isa<OMPExecutableDirective>(S);
4058 return StmtError();
4059 }
4060 }
4061
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004062 getCurFunction()->setHasBranchProtectedScope();
4063
4064 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4065}
4066
Alexey Bataev13314bf2014-10-09 04:18:56 +00004067StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4068 Stmt *AStmt, SourceLocation StartLoc,
4069 SourceLocation EndLoc) {
4070 assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4071 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4072 // 1.2.2 OpenMP Language Terminology
4073 // Structured block - An executable statement with a single entry at the
4074 // top and a single exit at the bottom.
4075 // The point of exit cannot be a branch out of the structured block.
4076 // longjmp() and throw() must not violate the entry/exit criteria.
4077 CS->getCapturedDecl()->setNothrow();
4078
4079 getCurFunction()->setHasBranchProtectedScope();
4080
4081 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4082}
4083
Alexey Bataeved09d242014-05-28 05:53:51 +00004084OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004085 SourceLocation StartLoc,
4086 SourceLocation LParenLoc,
4087 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004088 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004089 switch (Kind) {
4090 case OMPC_if:
4091 Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4092 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00004093 case OMPC_final:
4094 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4095 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004096 case OMPC_num_threads:
4097 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4098 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004099 case OMPC_safelen:
4100 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4101 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004102 case OMPC_collapse:
4103 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4104 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004105 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004106 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004107 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004108 case OMPC_private:
4109 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004110 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004111 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004112 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004113 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004114 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004115 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004116 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004117 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004118 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004119 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004120 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004121 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004122 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004123 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004124 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004125 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004126 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004127 case OMPC_seq_cst:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004128 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004129 llvm_unreachable("Clause is not allowed.");
4130 }
4131 return Res;
4132}
4133
Alexey Bataeved09d242014-05-28 05:53:51 +00004134OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004135 SourceLocation LParenLoc,
4136 SourceLocation EndLoc) {
4137 Expr *ValExpr = Condition;
4138 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4139 !Condition->isInstantiationDependent() &&
4140 !Condition->containsUnexpandedParameterPack()) {
4141 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00004142 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004143 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004144 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004145
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004146 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004147 }
4148
4149 return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4150}
4151
Alexey Bataev3778b602014-07-17 07:32:53 +00004152OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4153 SourceLocation StartLoc,
4154 SourceLocation LParenLoc,
4155 SourceLocation EndLoc) {
4156 Expr *ValExpr = Condition;
4157 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4158 !Condition->isInstantiationDependent() &&
4159 !Condition->containsUnexpandedParameterPack()) {
4160 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4161 Condition->getExprLoc(), Condition);
4162 if (Val.isInvalid())
4163 return nullptr;
4164
4165 ValExpr = Val.get();
4166 }
4167
4168 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4169}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004170ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4171 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004172 if (!Op)
4173 return ExprError();
4174
4175 class IntConvertDiagnoser : public ICEConvertDiagnoser {
4176 public:
4177 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00004178 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00004179 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4180 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004181 return S.Diag(Loc, diag::err_omp_not_integral) << T;
4182 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004183 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4184 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004185 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4186 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004187 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4188 QualType T,
4189 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004190 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4191 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004192 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4193 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004194 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004195 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004196 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004197 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4198 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004199 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4200 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004201 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4202 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004203 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00004204 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00004205 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004206 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4207 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00004208 llvm_unreachable("conversion functions are permitted");
4209 }
4210 } ConvertDiagnoser;
4211 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4212}
4213
4214OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4215 SourceLocation StartLoc,
4216 SourceLocation LParenLoc,
4217 SourceLocation EndLoc) {
4218 Expr *ValExpr = NumThreads;
4219 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00004220 !NumThreads->containsUnexpandedParameterPack()) {
4221 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4222 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004223 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00004224 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004225 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004226
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004227 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00004228
4229 // OpenMP [2.5, Restrictions]
4230 // The num_threads expression must evaluate to a positive integer value.
4231 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00004232 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4233 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00004234 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4235 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004236 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00004237 }
4238 }
4239
Alexey Bataeved09d242014-05-28 05:53:51 +00004240 return new (Context)
4241 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00004242}
4243
Alexey Bataev62c87d22014-03-21 04:51:18 +00004244ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4245 OpenMPClauseKind CKind) {
4246 if (!E)
4247 return ExprError();
4248 if (E->isValueDependent() || E->isTypeDependent() ||
4249 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004250 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004251 llvm::APSInt Result;
4252 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4253 if (ICE.isInvalid())
4254 return ExprError();
4255 if (!Result.isStrictlyPositive()) {
4256 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4257 << getOpenMPClauseName(CKind) << E->getSourceRange();
4258 return ExprError();
4259 }
Alexander Musman09184fe2014-09-30 05:29:28 +00004260 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4261 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4262 << E->getSourceRange();
4263 return ExprError();
4264 }
Alexey Bataev9c821032015-04-30 04:23:23 +00004265 if (CKind == OMPC_collapse) {
4266 DSAStack->setCollapseNumber(Result.getExtValue());
4267 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00004268 return ICE;
4269}
4270
4271OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4272 SourceLocation LParenLoc,
4273 SourceLocation EndLoc) {
4274 // OpenMP [2.8.1, simd construct, Description]
4275 // The parameter of the safelen clause must be a constant
4276 // positive integer expression.
4277 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4278 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004279 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004280 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004281 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00004282}
4283
Alexander Musman64d33f12014-06-04 07:53:32 +00004284OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4285 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00004286 SourceLocation LParenLoc,
4287 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00004288 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004289 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00004290 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00004291 // The parameter of the collapse clause must be a constant
4292 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00004293 ExprResult NumForLoopsResult =
4294 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4295 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00004296 return nullptr;
4297 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00004298 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00004299}
4300
Alexey Bataeved09d242014-05-28 05:53:51 +00004301OMPClause *Sema::ActOnOpenMPSimpleClause(
4302 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4303 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004304 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004305 switch (Kind) {
4306 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004307 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00004308 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4309 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004310 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004311 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00004312 Res = ActOnOpenMPProcBindClause(
4313 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4314 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004315 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004316 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004317 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004318 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004319 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004320 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004321 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004322 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004323 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004324 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00004325 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004326 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004327 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004328 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004329 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004330 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004331 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004332 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004333 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004334 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004335 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004336 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004337 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004338 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004339 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004340 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004341 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004342 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004343 llvm_unreachable("Clause is not allowed.");
4344 }
4345 return Res;
4346}
4347
4348OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4349 SourceLocation KindKwLoc,
4350 SourceLocation StartLoc,
4351 SourceLocation LParenLoc,
4352 SourceLocation EndLoc) {
4353 if (Kind == OMPC_DEFAULT_unknown) {
4354 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004355 static_assert(OMPC_DEFAULT_unknown > 0,
4356 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00004357 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004358 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004359 Values += "'";
4360 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4361 Values += "'";
4362 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004363 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004364 Values += " or ";
4365 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00004366 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004367 break;
4368 default:
4369 Values += Sep;
4370 break;
4371 }
4372 }
4373 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004374 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004375 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004376 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004377 switch (Kind) {
4378 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004379 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004380 break;
4381 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004382 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004383 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004384 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004385 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00004386 break;
4387 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004388 return new (Context)
4389 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004390}
4391
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004392OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4393 SourceLocation KindKwLoc,
4394 SourceLocation StartLoc,
4395 SourceLocation LParenLoc,
4396 SourceLocation EndLoc) {
4397 if (Kind == OMPC_PROC_BIND_unknown) {
4398 std::string Values;
4399 std::string Sep(", ");
4400 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4401 Values += "'";
4402 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4403 Values += "'";
4404 switch (i) {
4405 case OMPC_PROC_BIND_unknown - 2:
4406 Values += " or ";
4407 break;
4408 case OMPC_PROC_BIND_unknown - 1:
4409 break;
4410 default:
4411 Values += Sep;
4412 break;
4413 }
4414 }
4415 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00004416 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004417 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004418 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004419 return new (Context)
4420 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004421}
4422
Alexey Bataev56dafe82014-06-20 07:16:17 +00004423OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4424 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4425 SourceLocation StartLoc, SourceLocation LParenLoc,
4426 SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4427 SourceLocation EndLoc) {
4428 OMPClause *Res = nullptr;
4429 switch (Kind) {
4430 case OMPC_schedule:
4431 Res = ActOnOpenMPScheduleClause(
4432 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4433 LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4434 break;
4435 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004436 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004437 case OMPC_num_threads:
4438 case OMPC_safelen:
4439 case OMPC_collapse:
4440 case OMPC_default:
4441 case OMPC_proc_bind:
4442 case OMPC_private:
4443 case OMPC_firstprivate:
4444 case OMPC_lastprivate:
4445 case OMPC_shared:
4446 case OMPC_reduction:
4447 case OMPC_linear:
4448 case OMPC_aligned:
4449 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004450 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004451 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004452 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004453 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004454 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004455 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004456 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004457 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004458 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004459 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004460 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004461 case OMPC_seq_cst:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004462 case OMPC_unknown:
4463 llvm_unreachable("Clause is not allowed.");
4464 }
4465 return Res;
4466}
4467
4468OMPClause *Sema::ActOnOpenMPScheduleClause(
4469 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4470 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4471 SourceLocation EndLoc) {
4472 if (Kind == OMPC_SCHEDULE_unknown) {
4473 std::string Values;
4474 std::string Sep(", ");
4475 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4476 Values += "'";
4477 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4478 Values += "'";
4479 switch (i) {
4480 case OMPC_SCHEDULE_unknown - 2:
4481 Values += " or ";
4482 break;
4483 case OMPC_SCHEDULE_unknown - 1:
4484 break;
4485 default:
4486 Values += Sep;
4487 break;
4488 }
4489 }
4490 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4491 << Values << getOpenMPClauseName(OMPC_schedule);
4492 return nullptr;
4493 }
4494 Expr *ValExpr = ChunkSize;
4495 if (ChunkSize) {
4496 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4497 !ChunkSize->isInstantiationDependent() &&
4498 !ChunkSize->containsUnexpandedParameterPack()) {
4499 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4500 ExprResult Val =
4501 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4502 if (Val.isInvalid())
4503 return nullptr;
4504
4505 ValExpr = Val.get();
4506
4507 // OpenMP [2.7.1, Restrictions]
4508 // chunk_size must be a loop invariant integer expression with a positive
4509 // value.
4510 llvm::APSInt Result;
4511 if (ValExpr->isIntegerConstantExpr(Result, Context) &&
4512 Result.isSigned() && !Result.isStrictlyPositive()) {
4513 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4514 << "schedule" << ChunkSize->getSourceRange();
4515 return nullptr;
4516 }
4517 }
4518 }
4519
4520 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4521 EndLoc, Kind, ValExpr);
4522}
4523
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004524OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4525 SourceLocation StartLoc,
4526 SourceLocation EndLoc) {
4527 OMPClause *Res = nullptr;
4528 switch (Kind) {
4529 case OMPC_ordered:
4530 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4531 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00004532 case OMPC_nowait:
4533 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4534 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004535 case OMPC_untied:
4536 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4537 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004538 case OMPC_mergeable:
4539 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4540 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004541 case OMPC_read:
4542 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4543 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00004544 case OMPC_write:
4545 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4546 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004547 case OMPC_update:
4548 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4549 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00004550 case OMPC_capture:
4551 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4552 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004553 case OMPC_seq_cst:
4554 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4555 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004556 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004557 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004558 case OMPC_num_threads:
4559 case OMPC_safelen:
4560 case OMPC_collapse:
4561 case OMPC_schedule:
4562 case OMPC_private:
4563 case OMPC_firstprivate:
4564 case OMPC_lastprivate:
4565 case OMPC_shared:
4566 case OMPC_reduction:
4567 case OMPC_linear:
4568 case OMPC_aligned:
4569 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004570 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004571 case OMPC_default:
4572 case OMPC_proc_bind:
4573 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00004574 case OMPC_flush:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004575 case OMPC_unknown:
4576 llvm_unreachable("Clause is not allowed.");
4577 }
4578 return Res;
4579}
4580
4581OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4582 SourceLocation EndLoc) {
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004583 DSAStack->setOrderedRegion();
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004584 return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4585}
4586
Alexey Bataev236070f2014-06-20 11:19:47 +00004587OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4588 SourceLocation EndLoc) {
4589 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4590}
4591
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004592OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4593 SourceLocation EndLoc) {
4594 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4595}
4596
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004597OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4598 SourceLocation EndLoc) {
4599 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4600}
4601
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004602OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4603 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004604 return new (Context) OMPReadClause(StartLoc, EndLoc);
4605}
4606
Alexey Bataevdea47612014-07-23 07:46:59 +00004607OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4608 SourceLocation EndLoc) {
4609 return new (Context) OMPWriteClause(StartLoc, EndLoc);
4610}
4611
Alexey Bataev67a4f222014-07-23 10:25:33 +00004612OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4613 SourceLocation EndLoc) {
4614 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4615}
4616
Alexey Bataev459dec02014-07-24 06:46:57 +00004617OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4618 SourceLocation EndLoc) {
4619 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4620}
4621
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004622OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4623 SourceLocation EndLoc) {
4624 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4625}
4626
Alexey Bataevc5e02582014-06-16 07:08:35 +00004627OMPClause *Sema::ActOnOpenMPVarListClause(
4628 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4629 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4630 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4631 const DeclarationNameInfo &ReductionId) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004632 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004633 switch (Kind) {
4634 case OMPC_private:
4635 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4636 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004637 case OMPC_firstprivate:
4638 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4639 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00004640 case OMPC_lastprivate:
4641 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4642 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00004643 case OMPC_shared:
4644 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4645 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00004646 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00004647 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4648 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00004649 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00004650 case OMPC_linear:
4651 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4652 ColonLoc, EndLoc);
4653 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004654 case OMPC_aligned:
4655 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4656 ColonLoc, EndLoc);
4657 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004658 case OMPC_copyin:
4659 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4660 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00004661 case OMPC_copyprivate:
4662 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4663 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004664 case OMPC_flush:
4665 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4666 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004667 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00004668 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00004669 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00004670 case OMPC_safelen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00004671 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004672 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004673 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004674 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00004675 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00004676 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00004677 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00004678 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004679 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004680 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00004681 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00004682 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00004683 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00004684 case OMPC_seq_cst:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004685 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004686 llvm_unreachable("Clause is not allowed.");
4687 }
4688 return Res;
4689}
4690
4691OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
4692 SourceLocation StartLoc,
4693 SourceLocation LParenLoc,
4694 SourceLocation EndLoc) {
4695 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00004696 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00004697 for (auto &RefExpr : VarList) {
4698 assert(RefExpr && "NULL expr in OpenMP private clause.");
4699 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004700 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004701 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004702 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004703 continue;
4704 }
4705
Alexey Bataeved09d242014-05-28 05:53:51 +00004706 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004707 // OpenMP [2.1, C/C++]
4708 // A list item is a variable name.
4709 // OpenMP [2.9.3.3, Restrictions, p.1]
4710 // A variable that is part of another variable (as an array or
4711 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004712 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004713 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004714 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004715 continue;
4716 }
4717 Decl *D = DE->getDecl();
4718 VarDecl *VD = cast<VarDecl>(D);
4719
4720 QualType Type = VD->getType();
4721 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4722 // It will be analyzed later.
4723 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004724 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004725 continue;
4726 }
4727
4728 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4729 // A variable that appears in a private clause must not have an incomplete
4730 // type or a reference type.
4731 if (RequireCompleteType(ELoc, Type,
4732 diag::err_omp_private_incomplete_type)) {
4733 continue;
4734 }
4735 if (Type->isReferenceType()) {
4736 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00004737 << getOpenMPClauseName(OMPC_private) << Type;
4738 bool IsDecl =
4739 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4740 Diag(VD->getLocation(),
4741 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4742 << VD;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004743 continue;
4744 }
4745
4746 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
4747 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004748 // clause requires an accessible, unambiguous default constructor for the
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004749 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00004750 while (Type->isArrayType()) {
4751 Type = cast<ArrayType>(Type.getTypePtr())->getElementType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004752 }
4753
Alexey Bataev758e55e2013-09-06 18:03:48 +00004754 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4755 // in a Construct]
4756 // Variables with the predetermined data-sharing attributes may not be
4757 // listed in data-sharing attributes clauses, except for the cases
4758 // listed below. For these exceptions only, listing a predetermined
4759 // variable in a data-sharing attribute clause is allowed and overrides
4760 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004761 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004762 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004763 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
4764 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004765 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00004766 continue;
4767 }
4768
Alexey Bataev03b340a2014-10-21 03:16:40 +00004769 // Generate helper private variable and initialize it with the default
4770 // value. The address of the original variable is replaced by the address of
4771 // the new private variable in CodeGen. This new variable is not added to
4772 // IdResolver, so the code in the OpenMP region uses original variable for
4773 // proper diagnostics.
Alexey Bataev50a64582015-04-22 12:24:45 +00004774 auto VDPrivate = VarDecl::Create(Context, CurContext, DE->getLocStart(),
4775 DE->getExprLoc(), VD->getIdentifier(),
4776 VD->getType().getUnqualifiedType(),
4777 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004778 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto*/ false);
4779 if (VDPrivate->isInvalidDecl())
4780 continue;
4781 CurContext->addDecl(VDPrivate);
Alexey Bataev07649fb2014-12-16 08:01:48 +00004782 auto VDPrivateRefExpr =
4783 DeclRefExpr::Create(Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
4784 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004785 /*RefersToEnclosingVariableOrCapture*/ false,
Alexey Bataev07649fb2014-12-16 08:01:48 +00004786 /*NameLoc*/ SourceLocation(), DE->getType(),
4787 /*VK*/ VK_LValue);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004788
Alexey Bataev758e55e2013-09-06 18:03:48 +00004789 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004790 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00004791 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004792 }
4793
Alexey Bataeved09d242014-05-28 05:53:51 +00004794 if (Vars.empty())
4795 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004796
Alexey Bataev03b340a2014-10-21 03:16:40 +00004797 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
4798 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004799}
4800
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004801namespace {
4802class DiagsUninitializedSeveretyRAII {
4803private:
4804 DiagnosticsEngine &Diags;
4805 SourceLocation SavedLoc;
4806 bool IsIgnored;
4807
4808public:
4809 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
4810 bool IsIgnored)
4811 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
4812 if (!IsIgnored) {
4813 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
4814 /*Map*/ diag::Severity::Ignored, Loc);
4815 }
4816 }
4817 ~DiagsUninitializedSeveretyRAII() {
4818 if (!IsIgnored)
4819 Diags.popMappings(SavedLoc);
4820 }
4821};
4822}
4823
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004824OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
4825 SourceLocation StartLoc,
4826 SourceLocation LParenLoc,
4827 SourceLocation EndLoc) {
4828 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004829 SmallVector<Expr *, 8> PrivateCopies;
4830 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004831 bool IsImplicitClause =
4832 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
4833 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
4834
Alexey Bataeved09d242014-05-28 05:53:51 +00004835 for (auto &RefExpr : VarList) {
4836 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
4837 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004838 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00004839 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004840 PrivateCopies.push_back(nullptr);
4841 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004842 continue;
4843 }
4844
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004845 SourceLocation ELoc =
4846 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004847 // OpenMP [2.1, C/C++]
4848 // A list item is a variable name.
4849 // OpenMP [2.9.3.3, Restrictions, p.1]
4850 // A variable that is part of another variable (as an array or
4851 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00004852 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004853 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00004854 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004855 continue;
4856 }
4857 Decl *D = DE->getDecl();
4858 VarDecl *VD = cast<VarDecl>(D);
4859
4860 QualType Type = VD->getType();
4861 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
4862 // It will be analyzed later.
4863 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004864 PrivateCopies.push_back(nullptr);
4865 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004866 continue;
4867 }
4868
4869 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
4870 // A variable that appears in a private clause must not have an incomplete
4871 // type or a reference type.
4872 if (RequireCompleteType(ELoc, Type,
4873 diag::err_omp_firstprivate_incomplete_type)) {
4874 continue;
4875 }
4876 if (Type->isReferenceType()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004877 if (IsImplicitClause) {
4878 Diag(ImplicitClauseLoc,
4879 diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
4880 << Type;
4881 Diag(RefExpr->getExprLoc(), diag::note_used_here);
4882 } else {
4883 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
4884 << getOpenMPClauseName(OMPC_firstprivate) << Type;
4885 }
Alexey Bataeved09d242014-05-28 05:53:51 +00004886 bool IsDecl =
4887 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
4888 Diag(VD->getLocation(),
4889 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
4890 << VD;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004891 continue;
4892 }
4893
4894 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
4895 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00004896 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004897 // class type.
Alexey Bataev69c62a92015-04-15 04:52:20 +00004898 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004899
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004900 // If an implicit firstprivate variable found it was checked already.
4901 if (!IsImplicitClause) {
4902 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004903 Type = Type.getNonReferenceType().getCanonicalType();
4904 bool IsConstant = Type.isConstant(Context);
4905 Type = Context.getBaseElementType(Type);
4906 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
4907 // A list item that specifies a given variable may not appear in more
4908 // than one clause on the same directive, except that a variable may be
4909 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004910 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00004911 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004912 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004913 << getOpenMPClauseName(DVar.CKind)
4914 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004915 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004916 continue;
4917 }
4918
4919 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4920 // in a Construct]
4921 // Variables with the predetermined data-sharing attributes may not be
4922 // listed in data-sharing attributes clauses, except for the cases
4923 // listed below. For these exceptions only, listing a predetermined
4924 // variable in a data-sharing attribute clause is allowed and overrides
4925 // the variable's predetermined data-sharing attributes.
4926 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
4927 // in a Construct, C/C++, p.2]
4928 // Variables with const-qualified type having no mutable member may be
4929 // listed in a firstprivate clause, even if they are static data members.
4930 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
4931 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
4932 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00004933 << getOpenMPClauseName(DVar.CKind)
4934 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004935 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004936 continue;
4937 }
4938
Alexey Bataevf29276e2014-06-18 04:14:57 +00004939 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004940 // OpenMP [2.9.3.4, Restrictions, p.2]
4941 // A list item that is private within a parallel region must not appear
4942 // in a firstprivate clause on a worksharing construct if any of the
4943 // worksharing regions arising from the worksharing construct ever bind
4944 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00004945 if (isOpenMPWorksharingDirective(CurrDir) &&
4946 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004947 DVar = DSAStack->getImplicitDSA(VD, true);
4948 if (DVar.CKind != OMPC_shared &&
4949 (isOpenMPParallelDirective(DVar.DKind) ||
4950 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00004951 Diag(ELoc, diag::err_omp_required_access)
4952 << getOpenMPClauseName(OMPC_firstprivate)
4953 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00004954 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004955 continue;
4956 }
4957 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004958 // OpenMP [2.9.3.4, Restrictions, p.3]
4959 // A list item that appears in a reduction clause of a parallel construct
4960 // must not appear in a firstprivate clause on a worksharing or task
4961 // construct if any of the worksharing or task regions arising from the
4962 // worksharing or task construct ever bind to any of the parallel regions
4963 // arising from the parallel construct.
4964 // OpenMP [2.9.3.4, Restrictions, p.4]
4965 // A list item that appears in a reduction clause in worksharing
4966 // construct must not appear in a firstprivate clause in a task construct
4967 // encountered during execution of any of the worksharing regions arising
4968 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004969 if (CurrDir == OMPD_task) {
4970 DVar =
4971 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
4972 [](OpenMPDirectiveKind K) -> bool {
4973 return isOpenMPParallelDirective(K) ||
4974 isOpenMPWorksharingDirective(K);
4975 },
4976 false);
4977 if (DVar.CKind == OMPC_reduction &&
4978 (isOpenMPParallelDirective(DVar.DKind) ||
4979 isOpenMPWorksharingDirective(DVar.DKind))) {
4980 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
4981 << getOpenMPDirectiveName(DVar.DKind);
4982 ReportOriginalDSA(*this, DSAStack, VD, DVar);
4983 continue;
4984 }
4985 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004986 }
4987
Alexey Bataev69c62a92015-04-15 04:52:20 +00004988 auto VDPrivate =
4989 VarDecl::Create(Context, CurContext, DE->getLocStart(), ELoc,
4990 VD->getIdentifier(), VD->getType().getUnqualifiedType(),
4991 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00004992 // Generate helper private variable and initialize it with the value of the
4993 // original variable. The address of the original variable is replaced by
4994 // the address of the new private variable in the CodeGen. This new variable
4995 // is not added to IdResolver, so the code in the OpenMP region uses
4996 // original variable for proper diagnostics and variable capturing.
4997 Expr *VDInitRefExpr = nullptr;
4998 // For arrays generate initializer for single element and replace it by the
4999 // original array element in CodeGen.
5000 if (DE->getType()->isArrayType()) {
5001 auto VDInit = VarDecl::Create(Context, CurContext, DE->getLocStart(),
5002 ELoc, VD->getIdentifier(), Type,
5003 VD->getTypeSourceInfo(), /*S*/ SC_Auto);
5004 CurContext->addHiddenDecl(VDInit);
5005 VDInitRefExpr = DeclRefExpr::Create(
5006 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5007 /*TemplateKWLoc*/ SourceLocation(), VDInit,
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005008 /*RefersToEnclosingVariableOrCapture*/ true, ELoc, Type,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005009 /*VK*/ VK_LValue);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005010 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataev69c62a92015-04-15 04:52:20 +00005011 auto *VDInitTemp =
5012 BuildVarDecl(*this, DE->getLocStart(), Type.getUnqualifiedType(),
5013 ".firstprivate.temp");
5014 InitializedEntity Entity =
5015 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005016 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5017
5018 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5019 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5020 if (Result.isInvalid())
5021 VDPrivate->setInvalidDecl();
5022 else
5023 VDPrivate->setInit(Result.getAs<Expr>());
5024 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00005025 auto *VDInit =
5026 BuildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
5027 VDInitRefExpr =
5028 BuildDeclRefExpr(VDInit, Type, VK_LValue, DE->getExprLoc()).get();
5029 AddInitializerToDecl(VDPrivate,
5030 DefaultLvalueConversion(VDInitRefExpr).get(),
5031 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005032 }
5033 if (VDPrivate->isInvalidDecl()) {
5034 if (IsImplicitClause) {
5035 Diag(DE->getExprLoc(),
5036 diag::note_omp_task_predetermined_firstprivate_here);
5037 }
5038 continue;
5039 }
5040 CurContext->addDecl(VDPrivate);
Alexey Bataev69c62a92015-04-15 04:52:20 +00005041 auto VDPrivateRefExpr = DeclRefExpr::Create(
5042 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5043 /*TemplateKWLoc*/ SourceLocation(), VDPrivate,
5044 /*RefersToEnclosingVariableOrCapture*/ false, DE->getLocStart(),
5045 DE->getType().getUnqualifiedType(), /*VK*/ VK_LValue);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005046 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5047 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005048 PrivateCopies.push_back(VDPrivateRefExpr);
5049 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005050 }
5051
Alexey Bataeved09d242014-05-28 05:53:51 +00005052 if (Vars.empty())
5053 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005054
5055 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005056 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005057}
5058
Alexander Musman1bb328c2014-06-04 13:06:39 +00005059OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5060 SourceLocation StartLoc,
5061 SourceLocation LParenLoc,
5062 SourceLocation EndLoc) {
5063 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00005064 SmallVector<Expr *, 8> SrcExprs;
5065 SmallVector<Expr *, 8> DstExprs;
5066 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005067 for (auto &RefExpr : VarList) {
5068 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5069 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5070 // It will be analyzed later.
5071 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00005072 SrcExprs.push_back(nullptr);
5073 DstExprs.push_back(nullptr);
5074 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005075 continue;
5076 }
5077
5078 SourceLocation ELoc = RefExpr->getExprLoc();
5079 // OpenMP [2.1, C/C++]
5080 // A list item is a variable name.
5081 // OpenMP [2.14.3.5, Restrictions, p.1]
5082 // A variable that is part of another variable (as an array or structure
5083 // element) cannot appear in a lastprivate clause.
5084 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5085 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5086 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5087 continue;
5088 }
5089 Decl *D = DE->getDecl();
5090 VarDecl *VD = cast<VarDecl>(D);
5091
5092 QualType Type = VD->getType();
5093 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5094 // It will be analyzed later.
5095 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005096 SrcExprs.push_back(nullptr);
5097 DstExprs.push_back(nullptr);
5098 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005099 continue;
5100 }
5101
5102 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5103 // A variable that appears in a lastprivate clause must not have an
5104 // incomplete type or a reference type.
5105 if (RequireCompleteType(ELoc, Type,
5106 diag::err_omp_lastprivate_incomplete_type)) {
5107 continue;
5108 }
5109 if (Type->isReferenceType()) {
5110 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5111 << getOpenMPClauseName(OMPC_lastprivate) << Type;
5112 bool IsDecl =
5113 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5114 Diag(VD->getLocation(),
5115 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5116 << VD;
5117 continue;
5118 }
5119
5120 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5121 // in a Construct]
5122 // Variables with the predetermined data-sharing attributes may not be
5123 // listed in data-sharing attributes clauses, except for the cases
5124 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005125 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005126 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5127 DVar.CKind != OMPC_firstprivate &&
5128 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5129 Diag(ELoc, diag::err_omp_wrong_dsa)
5130 << getOpenMPClauseName(DVar.CKind)
5131 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005132 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005133 continue;
5134 }
5135
Alexey Bataevf29276e2014-06-18 04:14:57 +00005136 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5137 // OpenMP [2.14.3.5, Restrictions, p.2]
5138 // A list item that is private within a parallel region, or that appears in
5139 // the reduction clause of a parallel construct, must not appear in a
5140 // lastprivate clause on a worksharing construct if any of the corresponding
5141 // worksharing regions ever binds to any of the corresponding parallel
5142 // regions.
Alexey Bataev549210e2014-06-24 04:39:47 +00005143 if (isOpenMPWorksharingDirective(CurrDir) &&
5144 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005145 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005146 if (DVar.CKind != OMPC_shared) {
5147 Diag(ELoc, diag::err_omp_required_access)
5148 << getOpenMPClauseName(OMPC_lastprivate)
5149 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005150 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005151 continue;
5152 }
5153 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00005154 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00005155 // A variable of class type (or array thereof) that appears in a
5156 // lastprivate clause requires an accessible, unambiguous default
5157 // constructor for the class type, unless the list item is also specified
5158 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00005159 // A variable of class type (or array thereof) that appears in a
5160 // lastprivate clause requires an accessible, unambiguous copy assignment
5161 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00005162 Type = Context.getBaseElementType(Type).getNonReferenceType();
5163 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(),
5164 Type.getUnqualifiedType(), ".lastprivate.src");
5165 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, Type.getUnqualifiedType(),
5166 VK_LValue, DE->getExprLoc()).get();
5167 auto *DstVD =
5168 BuildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
5169 auto *PseudoDstExpr =
5170 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
5171 // For arrays generate assignment operation for single element and replace
5172 // it by the original array element in CodeGen.
5173 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5174 PseudoDstExpr, PseudoSrcExpr);
5175 if (AssignmentOp.isInvalid())
5176 continue;
5177 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5178 /*DiscardedValue=*/true);
5179 if (AssignmentOp.isInvalid())
5180 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005181
Alexey Bataevf29276e2014-06-18 04:14:57 +00005182 if (DVar.CKind != OMPC_firstprivate)
5183 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005184 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00005185 SrcExprs.push_back(PseudoSrcExpr);
5186 DstExprs.push_back(PseudoDstExpr);
5187 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00005188 }
5189
5190 if (Vars.empty())
5191 return nullptr;
5192
5193 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00005194 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00005195}
5196
Alexey Bataev758e55e2013-09-06 18:03:48 +00005197OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5198 SourceLocation StartLoc,
5199 SourceLocation LParenLoc,
5200 SourceLocation EndLoc) {
5201 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00005202 for (auto &RefExpr : VarList) {
5203 assert(RefExpr && "NULL expr in OpenMP shared clause.");
5204 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00005205 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005206 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005207 continue;
5208 }
5209
Alexey Bataeved09d242014-05-28 05:53:51 +00005210 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005211 // OpenMP [2.1, C/C++]
5212 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00005213 // OpenMP [2.14.3.2, Restrictions, p.1]
5214 // A variable that is part of another variable (as an array or structure
5215 // element) cannot appear in a shared unless it is a static data member
5216 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00005217 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005218 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005219 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00005220 continue;
5221 }
5222 Decl *D = DE->getDecl();
5223 VarDecl *VD = cast<VarDecl>(D);
5224
5225 QualType Type = VD->getType();
5226 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5227 // It will be analyzed later.
5228 Vars.push_back(DE);
5229 continue;
5230 }
5231
5232 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5233 // in a Construct]
5234 // Variables with the predetermined data-sharing attributes may not be
5235 // listed in data-sharing attributes clauses, except for the cases
5236 // listed below. For these exceptions only, listing a predetermined
5237 // variable in a data-sharing attribute clause is allowed and overrides
5238 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005239 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00005240 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5241 DVar.RefExpr) {
5242 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5243 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005244 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005245 continue;
5246 }
5247
5248 DSAStack->addDSA(VD, DE, OMPC_shared);
5249 Vars.push_back(DE);
5250 }
5251
Alexey Bataeved09d242014-05-28 05:53:51 +00005252 if (Vars.empty())
5253 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005254
5255 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5256}
5257
Alexey Bataevc5e02582014-06-16 07:08:35 +00005258namespace {
5259class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5260 DSAStackTy *Stack;
5261
5262public:
5263 bool VisitDeclRefExpr(DeclRefExpr *E) {
5264 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005265 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005266 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5267 return false;
5268 if (DVar.CKind != OMPC_unknown)
5269 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00005270 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005271 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005272 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00005273 return true;
5274 return false;
5275 }
5276 return false;
5277 }
5278 bool VisitStmt(Stmt *S) {
5279 for (auto Child : S->children()) {
5280 if (Child && Visit(Child))
5281 return true;
5282 }
5283 return false;
5284 }
Alexey Bataev23b69422014-06-18 07:08:49 +00005285 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00005286};
Alexey Bataev23b69422014-06-18 07:08:49 +00005287} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00005288
5289OMPClause *Sema::ActOnOpenMPReductionClause(
5290 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5291 SourceLocation ColonLoc, SourceLocation EndLoc,
5292 CXXScopeSpec &ReductionIdScopeSpec,
5293 const DeclarationNameInfo &ReductionId) {
5294 // TODO: Allow scope specification search when 'declare reduction' is
5295 // supported.
5296 assert(ReductionIdScopeSpec.isEmpty() &&
5297 "No support for scoped reduction identifiers yet.");
5298
5299 auto DN = ReductionId.getName();
5300 auto OOK = DN.getCXXOverloadedOperator();
5301 BinaryOperatorKind BOK = BO_Comma;
5302
5303 // OpenMP [2.14.3.6, reduction clause]
5304 // C
5305 // reduction-identifier is either an identifier or one of the following
5306 // operators: +, -, *, &, |, ^, && and ||
5307 // C++
5308 // reduction-identifier is either an id-expression or one of the following
5309 // operators: +, -, *, &, |, ^, && and ||
5310 // FIXME: Only 'min' and 'max' identifiers are supported for now.
5311 switch (OOK) {
5312 case OO_Plus:
5313 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005314 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005315 break;
5316 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005317 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005318 break;
5319 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005320 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005321 break;
5322 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005323 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005324 break;
5325 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005326 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005327 break;
5328 case OO_AmpAmp:
5329 BOK = BO_LAnd;
5330 break;
5331 case OO_PipePipe:
5332 BOK = BO_LOr;
5333 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005334 case OO_New:
5335 case OO_Delete:
5336 case OO_Array_New:
5337 case OO_Array_Delete:
5338 case OO_Slash:
5339 case OO_Percent:
5340 case OO_Tilde:
5341 case OO_Exclaim:
5342 case OO_Equal:
5343 case OO_Less:
5344 case OO_Greater:
5345 case OO_LessEqual:
5346 case OO_GreaterEqual:
5347 case OO_PlusEqual:
5348 case OO_MinusEqual:
5349 case OO_StarEqual:
5350 case OO_SlashEqual:
5351 case OO_PercentEqual:
5352 case OO_CaretEqual:
5353 case OO_AmpEqual:
5354 case OO_PipeEqual:
5355 case OO_LessLess:
5356 case OO_GreaterGreater:
5357 case OO_LessLessEqual:
5358 case OO_GreaterGreaterEqual:
5359 case OO_EqualEqual:
5360 case OO_ExclaimEqual:
5361 case OO_PlusPlus:
5362 case OO_MinusMinus:
5363 case OO_Comma:
5364 case OO_ArrowStar:
5365 case OO_Arrow:
5366 case OO_Call:
5367 case OO_Subscript:
5368 case OO_Conditional:
5369 case NUM_OVERLOADED_OPERATORS:
5370 llvm_unreachable("Unexpected reduction identifier");
5371 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005372 if (auto II = DN.getAsIdentifierInfo()) {
5373 if (II->isStr("max"))
5374 BOK = BO_GT;
5375 else if (II->isStr("min"))
5376 BOK = BO_LT;
5377 }
5378 break;
5379 }
5380 SourceRange ReductionIdRange;
5381 if (ReductionIdScopeSpec.isValid()) {
5382 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5383 }
5384 ReductionIdRange.setEnd(ReductionId.getEndLoc());
5385 if (BOK == BO_Comma) {
5386 // Not allowed reduction identifier is found.
5387 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5388 << ReductionIdRange;
5389 return nullptr;
5390 }
5391
5392 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005393 SmallVector<Expr *, 8> LHSs;
5394 SmallVector<Expr *, 8> RHSs;
5395 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005396 for (auto RefExpr : VarList) {
5397 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5398 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5399 // It will be analyzed later.
5400 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005401 LHSs.push_back(nullptr);
5402 RHSs.push_back(nullptr);
5403 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005404 continue;
5405 }
5406
5407 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5408 RefExpr->isInstantiationDependent() ||
5409 RefExpr->containsUnexpandedParameterPack()) {
5410 // It will be analyzed later.
5411 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005412 LHSs.push_back(nullptr);
5413 RHSs.push_back(nullptr);
5414 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005415 continue;
5416 }
5417
5418 auto ELoc = RefExpr->getExprLoc();
5419 auto ERange = RefExpr->getSourceRange();
5420 // OpenMP [2.1, C/C++]
5421 // A list item is a variable or array section, subject to the restrictions
5422 // specified in Section 2.4 on page 42 and in each of the sections
5423 // describing clauses and directives for which a list appears.
5424 // OpenMP [2.14.3.3, Restrictions, p.1]
5425 // A variable that is part of another variable (as an array or
5426 // structure element) cannot appear in a private clause.
5427 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5428 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5429 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5430 continue;
5431 }
5432 auto D = DE->getDecl();
5433 auto VD = cast<VarDecl>(D);
5434 auto Type = VD->getType();
5435 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5436 // A variable that appears in a private clause must not have an incomplete
5437 // type or a reference type.
5438 if (RequireCompleteType(ELoc, Type,
5439 diag::err_omp_reduction_incomplete_type))
5440 continue;
5441 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5442 // Arrays may not appear in a reduction clause.
5443 if (Type.getNonReferenceType()->isArrayType()) {
5444 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5445 bool IsDecl =
5446 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5447 Diag(VD->getLocation(),
5448 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5449 << VD;
5450 continue;
5451 }
5452 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5453 // A list item that appears in a reduction clause must not be
5454 // const-qualified.
5455 if (Type.getNonReferenceType().isConstant(Context)) {
5456 Diag(ELoc, diag::err_omp_const_variable)
5457 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5458 bool IsDecl =
5459 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5460 Diag(VD->getLocation(),
5461 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5462 << VD;
5463 continue;
5464 }
5465 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5466 // If a list-item is a reference type then it must bind to the same object
5467 // for all threads of the team.
5468 VarDecl *VDDef = VD->getDefinition();
5469 if (Type->isReferenceType() && VDDef) {
5470 DSARefChecker Check(DSAStack);
5471 if (Check.Visit(VDDef->getInit())) {
5472 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5473 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5474 continue;
5475 }
5476 }
5477 // OpenMP [2.14.3.6, reduction clause, Restrictions]
5478 // The type of a list item that appears in a reduction clause must be valid
5479 // for the reduction-identifier. For a max or min reduction in C, the type
5480 // of the list item must be an allowed arithmetic data type: char, int,
5481 // float, double, or _Bool, possibly modified with long, short, signed, or
5482 // unsigned. For a max or min reduction in C++, the type of the list item
5483 // must be an allowed arithmetic data type: char, wchar_t, int, float,
5484 // double, or bool, possibly modified with long, short, signed, or unsigned.
5485 if ((BOK == BO_GT || BOK == BO_LT) &&
5486 !(Type->isScalarType() ||
5487 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5488 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5489 << getLangOpts().CPlusPlus;
5490 bool IsDecl =
5491 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5492 Diag(VD->getLocation(),
5493 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5494 << VD;
5495 continue;
5496 }
5497 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5498 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5499 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
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 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00005507 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5508 // in a Construct]
5509 // Variables with the predetermined data-sharing attributes may not be
5510 // listed in data-sharing attributes clauses, except for the cases
5511 // listed below. For these exceptions only, listing a predetermined
5512 // variable in a data-sharing attribute clause is allowed and overrides
5513 // the variable's predetermined data-sharing attributes.
5514 // OpenMP [2.14.3.6, Restrictions, p.3]
5515 // Any number of reduction clauses can be specified on the directive,
5516 // but a list item can appear only once in the reduction clauses for that
5517 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005518 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005519 if (DVar.CKind == OMPC_reduction) {
5520 Diag(ELoc, diag::err_omp_once_referenced)
5521 << getOpenMPClauseName(OMPC_reduction);
5522 if (DVar.RefExpr) {
5523 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5524 }
5525 } else if (DVar.CKind != OMPC_unknown) {
5526 Diag(ELoc, diag::err_omp_wrong_dsa)
5527 << getOpenMPClauseName(DVar.CKind)
5528 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005529 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005530 continue;
5531 }
5532
5533 // OpenMP [2.14.3.6, Restrictions, p.1]
5534 // A list item that appears in a reduction clause of a worksharing
5535 // construct must be shared in the parallel regions to which any of the
5536 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00005537 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00005538 if (isOpenMPWorksharingDirective(CurrDir) &&
5539 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005540 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005541 if (DVar.CKind != OMPC_shared) {
5542 Diag(ELoc, diag::err_omp_required_access)
5543 << getOpenMPClauseName(OMPC_reduction)
5544 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005545 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005546 continue;
5547 }
5548 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005549 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
5550 auto *LHSVD = BuildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5551 auto *RHSVD = BuildVarDecl(*this, ELoc, Type, VD->getName());
5552 // Add initializer for private variable.
5553 Expr *Init = nullptr;
5554 switch (BOK) {
5555 case BO_Add:
5556 case BO_Xor:
5557 case BO_Or:
5558 case BO_LOr:
5559 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5560 if (Type->isScalarType() || Type->isAnyComplexType()) {
5561 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005562 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005563 break;
5564 case BO_Mul:
5565 case BO_LAnd:
5566 if (Type->isScalarType() || Type->isAnyComplexType()) {
5567 // '*' and '&&' reduction ops - initializer is '1'.
5568 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5569 }
5570 break;
5571 case BO_And: {
5572 // '&' reduction op - initializer is '~0'.
5573 QualType OrigType = Type;
5574 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5575 Type = ComplexTy->getElementType();
5576 }
5577 if (Type->isRealFloatingType()) {
5578 llvm::APFloat InitValue =
5579 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5580 /*isIEEE=*/true);
5581 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5582 Type, ELoc);
5583 } else if (Type->isScalarType()) {
5584 auto Size = Context.getTypeSize(Type);
5585 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5586 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5587 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5588 }
5589 if (Init && OrigType->isAnyComplexType()) {
5590 // Init = 0xFFFF + 0xFFFFi;
5591 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5592 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5593 }
5594 Type = OrigType;
5595 break;
5596 }
5597 case BO_LT:
5598 case BO_GT: {
5599 // 'min' reduction op - initializer is 'Largest representable number in
5600 // the reduction list item type'.
5601 // 'max' reduction op - initializer is 'Least representable number in
5602 // the reduction list item type'.
5603 if (Type->isIntegerType() || Type->isPointerType()) {
5604 bool IsSigned = Type->hasSignedIntegerRepresentation();
5605 auto Size = Context.getTypeSize(Type);
5606 QualType IntTy =
5607 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5608 llvm::APInt InitValue =
5609 (BOK != BO_LT)
5610 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5611 : llvm::APInt::getMinValue(Size)
5612 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5613 : llvm::APInt::getMaxValue(Size);
5614 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5615 if (Type->isPointerType()) {
5616 // Cast to pointer type.
5617 auto CastExpr = BuildCStyleCastExpr(
5618 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5619 SourceLocation(), Init);
5620 if (CastExpr.isInvalid())
5621 continue;
5622 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00005623 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005624 } else if (Type->isRealFloatingType()) {
5625 llvm::APFloat InitValue = llvm::APFloat::getLargest(
5626 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5627 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5628 Type, ELoc);
5629 }
5630 break;
5631 }
5632 case BO_PtrMemD:
5633 case BO_PtrMemI:
5634 case BO_MulAssign:
5635 case BO_Div:
5636 case BO_Rem:
5637 case BO_Sub:
5638 case BO_Shl:
5639 case BO_Shr:
5640 case BO_LE:
5641 case BO_GE:
5642 case BO_EQ:
5643 case BO_NE:
5644 case BO_AndAssign:
5645 case BO_XorAssign:
5646 case BO_OrAssign:
5647 case BO_Assign:
5648 case BO_AddAssign:
5649 case BO_SubAssign:
5650 case BO_DivAssign:
5651 case BO_RemAssign:
5652 case BO_ShlAssign:
5653 case BO_ShrAssign:
5654 case BO_Comma:
5655 llvm_unreachable("Unexpected reduction operation");
5656 }
5657 if (Init) {
5658 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5659 /*TypeMayContainAuto=*/false);
5660 } else {
5661 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5662 }
5663 if (!RHSVD->hasInit()) {
5664 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5665 << ReductionIdRange;
5666 bool IsDecl =
5667 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5668 Diag(VD->getLocation(),
5669 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5670 << VD;
5671 continue;
5672 }
5673 auto *LHSDRE = BuildDeclRefExpr(LHSVD, Type, VK_LValue, ELoc).get();
5674 auto *RHSDRE = BuildDeclRefExpr(RHSVD, Type, VK_LValue, ELoc).get();
5675 ExprResult ReductionOp =
5676 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5677 LHSDRE, RHSDRE);
5678 if (ReductionOp.isUsable()) {
5679 if (BOK != BO_LOr && BOK != BO_LAnd) {
5680 ReductionOp =
5681 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5682 BO_Assign, LHSDRE, ReductionOp.get());
5683 } else {
5684 auto *ConditionalOp = new (Context) ConditionalOperator(
5685 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
5686 RHSDRE, Type, VK_LValue, OK_Ordinary);
5687 ReductionOp =
5688 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
5689 BO_Assign, LHSDRE, ConditionalOp);
5690 }
5691 if (ReductionOp.isUsable()) {
5692 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005693 }
5694 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005695 if (ReductionOp.isInvalid())
5696 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005697
5698 DSAStack->addDSA(VD, DE, OMPC_reduction);
5699 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005700 LHSs.push_back(LHSDRE);
5701 RHSs.push_back(RHSDRE);
5702 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00005703 }
5704
5705 if (Vars.empty())
5706 return nullptr;
5707
5708 return OMPReductionClause::Create(
5709 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005710 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
5711 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005712}
5713
Alexander Musman8dba6642014-04-22 13:09:42 +00005714OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
5715 SourceLocation StartLoc,
5716 SourceLocation LParenLoc,
5717 SourceLocation ColonLoc,
5718 SourceLocation EndLoc) {
5719 SmallVector<Expr *, 8> Vars;
Alexander Musman3276a272015-03-21 10:12:56 +00005720 SmallVector<Expr *, 8> Inits;
Alexey Bataeved09d242014-05-28 05:53:51 +00005721 for (auto &RefExpr : VarList) {
5722 assert(RefExpr && "NULL expr in OpenMP linear clause.");
5723 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00005724 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005725 Vars.push_back(RefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00005726 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005727 continue;
5728 }
5729
5730 // OpenMP [2.14.3.7, linear clause]
5731 // A list item that appears in a linear clause is subject to the private
5732 // clause semantics described in Section 2.14.3.3 on page 159 except as
5733 // noted. In addition, the value of the new list item on each iteration
5734 // of the associated loop(s) corresponds to the value of the original
5735 // list item before entering the construct plus the logical number of
5736 // the iteration times linear-step.
5737
Alexey Bataeved09d242014-05-28 05:53:51 +00005738 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00005739 // OpenMP [2.1, C/C++]
5740 // A list item is a variable name.
5741 // OpenMP [2.14.3.3, Restrictions, p.1]
5742 // A variable that is part of another variable (as an array or
5743 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005744 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005745 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005746 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00005747 continue;
5748 }
5749
5750 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5751
5752 // OpenMP [2.14.3.7, linear clause]
5753 // A list-item cannot appear in more than one linear clause.
5754 // A list-item that appears in a linear clause cannot appear in any
5755 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005756 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00005757 if (DVar.RefExpr) {
5758 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5759 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005760 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00005761 continue;
5762 }
5763
5764 QualType QType = VD->getType();
5765 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
5766 // It will be analyzed later.
5767 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005768 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00005769 continue;
5770 }
5771
5772 // A variable must not have an incomplete type or a reference type.
5773 if (RequireCompleteType(ELoc, QType,
5774 diag::err_omp_linear_incomplete_type)) {
5775 continue;
5776 }
5777 if (QType->isReferenceType()) {
5778 Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5779 << getOpenMPClauseName(OMPC_linear) << QType;
5780 bool IsDecl =
5781 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5782 Diag(VD->getLocation(),
5783 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5784 << VD;
5785 continue;
5786 }
5787
5788 // A list item must not be const-qualified.
5789 if (QType.isConstant(Context)) {
5790 Diag(ELoc, diag::err_omp_const_variable)
5791 << getOpenMPClauseName(OMPC_linear);
5792 bool IsDecl =
5793 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5794 Diag(VD->getLocation(),
5795 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5796 << VD;
5797 continue;
5798 }
5799
5800 // A list item must be of integral or pointer type.
5801 QType = QType.getUnqualifiedType().getCanonicalType();
5802 const Type *Ty = QType.getTypePtrOrNull();
5803 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
5804 !Ty->isPointerType())) {
5805 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
5806 bool IsDecl =
5807 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5808 Diag(VD->getLocation(),
5809 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5810 << VD;
5811 continue;
5812 }
5813
Alexander Musman3276a272015-03-21 10:12:56 +00005814 // Build var to save initial value.
5815 VarDecl *Init = BuildVarDecl(*this, ELoc, DE->getType(), ".linear.start");
5816 AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
5817 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
5818 CurContext->addDecl(Init);
5819 Init->setIsUsed();
5820 auto InitRef = DeclRefExpr::Create(
5821 Context, /*QualifierLoc*/ NestedNameSpecifierLoc(),
5822 /*TemplateKWLoc*/ SourceLocation(), Init,
5823 /*isEnclosingLocal*/ false, DE->getLocStart(), DE->getType(),
5824 /*VK*/ VK_LValue);
Alexander Musman8dba6642014-04-22 13:09:42 +00005825 DSAStack->addDSA(VD, DE, OMPC_linear);
5826 Vars.push_back(DE);
Alexander Musman3276a272015-03-21 10:12:56 +00005827 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00005828 }
5829
5830 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005831 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005832
5833 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00005834 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00005835 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5836 !Step->isInstantiationDependent() &&
5837 !Step->containsUnexpandedParameterPack()) {
5838 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005839 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00005840 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005841 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005842 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00005843
Alexander Musman3276a272015-03-21 10:12:56 +00005844 // Build var to save the step value.
5845 VarDecl *SaveVar =
5846 BuildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
5847 CurContext->addDecl(SaveVar);
5848 SaveVar->setIsUsed();
5849 ExprResult SaveRef =
5850 BuildDeclRefExpr(SaveVar, StepExpr->getType(), VK_LValue, StepLoc);
5851 ExprResult CalcStep =
5852 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
5853
Alexander Musman8dba6642014-04-22 13:09:42 +00005854 // Warn about zero linear step (it would be probably better specified as
5855 // making corresponding variables 'const').
5856 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00005857 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
5858 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00005859 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
5860 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00005861 if (!IsConstant && CalcStep.isUsable()) {
5862 // Calculate the step beforehand instead of doing this on each iteration.
5863 // (This is not used if the number of iterations may be kfold-ed).
5864 CalcStepExpr = CalcStep.get();
5865 }
Alexander Musman8dba6642014-04-22 13:09:42 +00005866 }
5867
5868 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
Alexander Musman3276a272015-03-21 10:12:56 +00005869 Vars, Inits, StepExpr, CalcStepExpr);
5870}
5871
5872static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
5873 Expr *NumIterations, Sema &SemaRef,
5874 Scope *S) {
5875 // Walk the vars and build update/final expressions for the CodeGen.
5876 SmallVector<Expr *, 8> Updates;
5877 SmallVector<Expr *, 8> Finals;
5878 Expr *Step = Clause.getStep();
5879 Expr *CalcStep = Clause.getCalcStep();
5880 // OpenMP [2.14.3.7, linear clause]
5881 // If linear-step is not specified it is assumed to be 1.
5882 if (Step == nullptr)
5883 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5884 else if (CalcStep)
5885 Step = cast<BinaryOperator>(CalcStep)->getLHS();
5886 bool HasErrors = false;
5887 auto CurInit = Clause.inits().begin();
5888 for (auto &RefExpr : Clause.varlists()) {
5889 Expr *InitExpr = *CurInit;
5890
5891 // Build privatized reference to the current linear var.
5892 auto DE = cast<DeclRefExpr>(RefExpr);
5893 auto PrivateRef = DeclRefExpr::Create(
5894 SemaRef.Context, /*QualifierLoc*/ DE->getQualifierLoc(),
5895 /*TemplateKWLoc*/ SourceLocation(), DE->getDecl(),
5896 /* RefersToEnclosingVariableOrCapture */ true, DE->getLocStart(),
5897 DE->getType(), /*VK*/ VK_LValue);
5898
5899 // Build update: Var = InitExpr + IV * Step
5900 ExprResult Update =
5901 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
5902 InitExpr, IV, Step, /* Subtract */ false);
5903 Update = SemaRef.ActOnFinishFullExpr(Update.get());
5904
5905 // Build final: Var = InitExpr + NumIterations * Step
5906 ExprResult Final =
5907 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), RefExpr, InitExpr,
5908 NumIterations, Step, /* Subtract */ false);
5909 Final = SemaRef.ActOnFinishFullExpr(Final.get());
5910 if (!Update.isUsable() || !Final.isUsable()) {
5911 Updates.push_back(nullptr);
5912 Finals.push_back(nullptr);
5913 HasErrors = true;
5914 } else {
5915 Updates.push_back(Update.get());
5916 Finals.push_back(Final.get());
5917 }
5918 ++CurInit;
5919 }
5920 Clause.setUpdates(Updates);
5921 Clause.setFinals(Finals);
5922 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00005923}
5924
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005925OMPClause *Sema::ActOnOpenMPAlignedClause(
5926 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
5927 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
5928
5929 SmallVector<Expr *, 8> Vars;
5930 for (auto &RefExpr : VarList) {
5931 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
5932 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5933 // It will be analyzed later.
5934 Vars.push_back(RefExpr);
5935 continue;
5936 }
5937
5938 SourceLocation ELoc = RefExpr->getExprLoc();
5939 // OpenMP [2.1, C/C++]
5940 // A list item is a variable name.
5941 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5942 if (!DE || !isa<VarDecl>(DE->getDecl())) {
5943 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5944 continue;
5945 }
5946
5947 VarDecl *VD = cast<VarDecl>(DE->getDecl());
5948
5949 // OpenMP [2.8.1, simd construct, Restrictions]
5950 // The type of list items appearing in the aligned clause must be
5951 // array, pointer, reference to array, or reference to pointer.
5952 QualType QType = DE->getType()
5953 .getNonReferenceType()
5954 .getUnqualifiedType()
5955 .getCanonicalType();
5956 const Type *Ty = QType.getTypePtrOrNull();
5957 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
5958 !Ty->isPointerType())) {
5959 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
5960 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
5961 bool IsDecl =
5962 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5963 Diag(VD->getLocation(),
5964 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5965 << VD;
5966 continue;
5967 }
5968
5969 // OpenMP [2.8.1, simd construct, Restrictions]
5970 // A list-item cannot appear in more than one aligned clause.
5971 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
5972 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
5973 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
5974 << getOpenMPClauseName(OMPC_aligned);
5975 continue;
5976 }
5977
5978 Vars.push_back(DE);
5979 }
5980
5981 // OpenMP [2.8.1, simd construct, Description]
5982 // The parameter of the aligned clause, alignment, must be a constant
5983 // positive integer expression.
5984 // If no optional parameter is specified, implementation-defined default
5985 // alignments for SIMD instructions on the target platforms are assumed.
5986 if (Alignment != nullptr) {
5987 ExprResult AlignResult =
5988 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
5989 if (AlignResult.isInvalid())
5990 return nullptr;
5991 Alignment = AlignResult.get();
5992 }
5993 if (Vars.empty())
5994 return nullptr;
5995
5996 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
5997 EndLoc, Vars, Alignment);
5998}
5999
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006000OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6001 SourceLocation StartLoc,
6002 SourceLocation LParenLoc,
6003 SourceLocation EndLoc) {
6004 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006005 SmallVector<Expr *, 8> SrcExprs;
6006 SmallVector<Expr *, 8> DstExprs;
6007 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00006008 for (auto &RefExpr : VarList) {
6009 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6010 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006011 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006012 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006013 SrcExprs.push_back(nullptr);
6014 DstExprs.push_back(nullptr);
6015 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006016 continue;
6017 }
6018
Alexey Bataeved09d242014-05-28 05:53:51 +00006019 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006020 // OpenMP [2.1, C/C++]
6021 // A list item is a variable name.
6022 // OpenMP [2.14.4.1, Restrictions, p.1]
6023 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00006024 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006025 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006026 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006027 continue;
6028 }
6029
6030 Decl *D = DE->getDecl();
6031 VarDecl *VD = cast<VarDecl>(D);
6032
6033 QualType Type = VD->getType();
6034 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6035 // It will be analyzed later.
6036 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006037 SrcExprs.push_back(nullptr);
6038 DstExprs.push_back(nullptr);
6039 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006040 continue;
6041 }
6042
6043 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6044 // A list item that appears in a copyin clause must be threadprivate.
6045 if (!DSAStack->isThreadPrivate(VD)) {
6046 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00006047 << getOpenMPClauseName(OMPC_copyin)
6048 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006049 continue;
6050 }
6051
6052 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6053 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00006054 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006055 // operator for the class type.
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006056 Type = Context.getBaseElementType(Type).getNonReferenceType();
6057 auto *SrcVD = BuildVarDecl(*this, DE->getLocStart(),
6058 Type.getUnqualifiedType(), ".copyin.src");
6059 auto *PseudoSrcExpr = BuildDeclRefExpr(SrcVD, Type.getUnqualifiedType(),
6060 VK_LValue, DE->getExprLoc())
6061 .get();
6062 auto *DstVD = BuildVarDecl(*this, DE->getLocStart(), Type, ".copyin.dst");
6063 auto *PseudoDstExpr =
6064 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
6065 // For arrays generate assignment operation for single element and replace
6066 // it by the original array element in CodeGen.
6067 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6068 PseudoDstExpr, PseudoSrcExpr);
6069 if (AssignmentOp.isInvalid())
6070 continue;
6071 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6072 /*DiscardedValue=*/true);
6073 if (AssignmentOp.isInvalid())
6074 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006075
6076 DSAStack->addDSA(VD, DE, OMPC_copyin);
6077 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006078 SrcExprs.push_back(PseudoSrcExpr);
6079 DstExprs.push_back(PseudoDstExpr);
6080 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006081 }
6082
Alexey Bataeved09d242014-05-28 05:53:51 +00006083 if (Vars.empty())
6084 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006085
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006086 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6087 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006088}
6089
Alexey Bataevbae9a792014-06-27 10:37:06 +00006090OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6091 SourceLocation StartLoc,
6092 SourceLocation LParenLoc,
6093 SourceLocation EndLoc) {
6094 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00006095 SmallVector<Expr *, 8> SrcExprs;
6096 SmallVector<Expr *, 8> DstExprs;
6097 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006098 for (auto &RefExpr : VarList) {
6099 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6100 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6101 // It will be analyzed later.
6102 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006103 SrcExprs.push_back(nullptr);
6104 DstExprs.push_back(nullptr);
6105 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006106 continue;
6107 }
6108
6109 SourceLocation ELoc = RefExpr->getExprLoc();
6110 // OpenMP [2.1, C/C++]
6111 // A list item is a variable name.
6112 // OpenMP [2.14.4.1, Restrictions, p.1]
6113 // A list item that appears in a copyin clause must be threadprivate.
6114 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6115 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6116 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6117 continue;
6118 }
6119
6120 Decl *D = DE->getDecl();
6121 VarDecl *VD = cast<VarDecl>(D);
6122
6123 QualType Type = VD->getType();
6124 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6125 // It will be analyzed later.
6126 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006127 SrcExprs.push_back(nullptr);
6128 DstExprs.push_back(nullptr);
6129 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006130 continue;
6131 }
6132
6133 // OpenMP [2.14.4.2, Restrictions, p.2]
6134 // A list item that appears in a copyprivate clause may not appear in a
6135 // private or firstprivate clause on the single construct.
6136 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006137 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006138 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6139 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00006140 Diag(ELoc, diag::err_omp_wrong_dsa)
6141 << getOpenMPClauseName(DVar.CKind)
6142 << getOpenMPClauseName(OMPC_copyprivate);
6143 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6144 continue;
6145 }
6146
6147 // OpenMP [2.11.4.2, Restrictions, p.1]
6148 // All list items that appear in a copyprivate clause must be either
6149 // threadprivate or private in the enclosing context.
6150 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006151 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006152 if (DVar.CKind == OMPC_shared) {
6153 Diag(ELoc, diag::err_omp_required_access)
6154 << getOpenMPClauseName(OMPC_copyprivate)
6155 << "threadprivate or private in the enclosing context";
6156 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6157 continue;
6158 }
6159 }
6160 }
6161
6162 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6163 // A variable of class type (or array thereof) that appears in a
6164 // copyin clause requires an accessible, unambiguous copy assignment
6165 // operator for the class type.
Alexey Bataev420d45b2015-04-14 05:11:24 +00006166 Type = Context.getBaseElementType(Type).getUnqualifiedType();
6167 auto *SrcVD =
6168 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6169 auto *PseudoSrcExpr =
6170 BuildDeclRefExpr(SrcVD, Type, VK_LValue, DE->getExprLoc()).get();
6171 auto *DstVD =
6172 BuildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6173 auto *PseudoDstExpr =
6174 BuildDeclRefExpr(DstVD, Type, VK_LValue, DE->getExprLoc()).get();
Alexey Bataeva63048e2015-03-23 06:18:07 +00006175 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6176 PseudoDstExpr, PseudoSrcExpr);
6177 if (AssignmentOp.isInvalid())
6178 continue;
6179 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6180 /*DiscardedValue=*/true);
6181 if (AssignmentOp.isInvalid())
6182 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00006183
6184 // No need to mark vars as copyprivate, they are already threadprivate or
6185 // implicitly private.
6186 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00006187 SrcExprs.push_back(PseudoSrcExpr);
6188 DstExprs.push_back(PseudoDstExpr);
6189 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00006190 }
6191
6192 if (Vars.empty())
6193 return nullptr;
6194
Alexey Bataeva63048e2015-03-23 06:18:07 +00006195 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6196 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00006197}
6198
Alexey Bataev6125da92014-07-21 11:26:11 +00006199OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6200 SourceLocation StartLoc,
6201 SourceLocation LParenLoc,
6202 SourceLocation EndLoc) {
6203 if (VarList.empty())
6204 return nullptr;
6205
6206 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6207}
Alexey Bataevdea47612014-07-23 07:46:59 +00006208