blob: 9045724aa2b2fe473a62f28330e1680669e5bc80 [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 Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000024#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000025#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000027#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000028#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
38namespace {
39/// \brief Default data sharing attributes, which can be applied to directive.
40enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000041 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
42 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
43 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000044};
Alexey Bataev7ff55242014-06-19 09:13:45 +000045
Alexey Bataevf29276e2014-06-18 04:14:57 +000046template <class T> struct MatchesAny {
Alexey Bataev23b69422014-06-18 07:08:49 +000047 explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
Alexey Bataevf29276e2014-06-18 04:14:57 +000048 bool operator()(T Kind) {
49 for (auto KindEl : Arr)
50 if (KindEl == Kind)
51 return true;
52 return false;
53 }
54
55private:
56 ArrayRef<T> Arr;
57};
Alexey Bataev23b69422014-06-18 07:08:49 +000058struct MatchesAlways {
Alexey Bataevf29276e2014-06-18 04:14:57 +000059 MatchesAlways() {}
Alexey Bataev7ff55242014-06-19 09:13:45 +000060 template <class T> bool operator()(T) { return true; }
Alexey Bataevf29276e2014-06-18 04:14:57 +000061};
62
63typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
64typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
Alexey Bataev758e55e2013-09-06 18:03:48 +000065
66/// \brief Stack for tracking declarations used in OpenMP directives and
67/// clauses and their data-sharing attributes.
68class DSAStackTy {
69public:
70 struct DSAVarData {
71 OpenMPDirectiveKind DKind;
72 OpenMPClauseKind CKind;
73 DeclRefExpr *RefExpr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000074 SourceLocation ImplicitDSALoc;
75 DSAVarData()
76 : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
77 ImplicitDSALoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000078 };
Alexey Bataeved09d242014-05-28 05:53:51 +000079
Alexey Bataev758e55e2013-09-06 18:03:48 +000080private:
81 struct DSAInfo {
82 OpenMPClauseKind Attributes;
83 DeclRefExpr *RefExpr;
84 };
85 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000086 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
Alexey Bataev9c821032015-04-30 04:23:23 +000087 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000088
89 struct SharingMapTy {
90 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000091 AlignedMapTy AlignedMap;
Alexey Bataev9c821032015-04-30 04:23:23 +000092 LoopControlVariablesSetTy LCVSet;
Alexey Bataev758e55e2013-09-06 18:03:48 +000093 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +000095 OpenMPDirectiveKind Directive;
96 DeclarationNameInfo DirectiveName;
97 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev346265e2015-09-25 10:37:12 +000099 /// \brief first argument (Expr *) contains optional argument of the
100 /// 'ordered' clause, the second one is true if the regions has 'ordered'
101 /// clause, false otherwise.
102 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000103 bool NowaitRegion;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000104 bool CancelRegion;
Alexey Bataev9c821032015-04-30 04:23:23 +0000105 unsigned CollapseNumber;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000106 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000107 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000108 Scope *CurScope, SourceLocation Loc)
Alexey Bataev9c821032015-04-30 04:23:23 +0000109 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000110 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev346265e2015-09-25 10:37:12 +0000111 ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
Alexey Bataev25e5b442015-09-15 12:52:43 +0000112 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000113 SharingMapTy()
Alexey Bataev9c821032015-04-30 04:23:23 +0000114 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000115 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev346265e2015-09-25 10:37:12 +0000116 ConstructLoc(), OrderedRegion(), NowaitRegion(false),
Alexey Bataev25e5b442015-09-15 12:52:43 +0000117 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118 };
119
120 typedef SmallVector<SharingMapTy, 64> StackTy;
121
122 /// \brief Stack of used declaration and their data-sharing attributes.
123 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000124 /// \brief true, if check for DSA must be from parent directive, false, if
125 /// from current directive.
Alexey Bataevaac108a2015-06-23 04:51:00 +0000126 OpenMPClauseKind ClauseKindMode;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000127 Sema &SemaRef;
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000128 bool ForceCapturing;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000129
130 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
131
132 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000133
134 /// \brief Checks if the variable is a local for OpenMP region.
135 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000136
Alexey Bataev758e55e2013-09-06 18:03:48 +0000137public:
Alexey Bataevaac108a2015-06-23 04:51:00 +0000138 explicit DSAStackTy(Sema &S)
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000139 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
140 ForceCapturing(false) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000141
Alexey Bataevaac108a2015-06-23 04:51:00 +0000142 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
143 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000144
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000145 bool isForceVarCapturing() const { return ForceCapturing; }
146 void setForceVarCapturing(bool V) { ForceCapturing = V; }
147
Alexey Bataev758e55e2013-09-06 18:03:48 +0000148 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000149 Scope *CurScope, SourceLocation Loc) {
150 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
151 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000152 }
153
154 void pop() {
155 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
156 Stack.pop_back();
157 }
158
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000159 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000160 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000161 /// for diagnostics.
162 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
163
Alexey Bataev9c821032015-04-30 04:23:23 +0000164 /// \brief Register specified variable as loop control variable.
165 void addLoopControlVariable(VarDecl *D);
166 /// \brief Check if the specified variable is a loop control variable for
167 /// current region.
168 bool isLoopControlVariable(VarDecl *D);
169
Alexey Bataev758e55e2013-09-06 18:03:48 +0000170 /// \brief Adds explicit data sharing attribute to the specified declaration.
171 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
172
Alexey Bataev758e55e2013-09-06 18:03:48 +0000173 /// \brief Returns data sharing attributes from top of the stack for the
174 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000175 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000176 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000177 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000178 /// \brief Checks if the specified variables has data-sharing attributes which
179 /// match specified \a CPred predicate in any directive which matches \a DPred
180 /// predicate.
181 template <class ClausesPredicate, class DirectivesPredicate>
182 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000183 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000184 /// \brief Checks if the specified variables has data-sharing attributes which
185 /// match specified \a CPred predicate in any innermost directive which
186 /// matches \a DPred predicate.
187 template <class ClausesPredicate, class DirectivesPredicate>
188 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000189 DirectivesPredicate DPred,
190 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000191 /// \brief Checks if the specified variables has explicit data-sharing
192 /// attributes which match specified \a CPred predicate at the specified
193 /// OpenMP region.
194 bool hasExplicitDSA(VarDecl *D,
195 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
196 unsigned Level);
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000197 /// \brief Finds a directive which matches specified \a DPred predicate.
198 template <class NamedDirectivesPredicate>
199 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000200
Alexey Bataev758e55e2013-09-06 18:03:48 +0000201 /// \brief Returns currently analyzed directive.
202 OpenMPDirectiveKind getCurrentDirective() const {
203 return Stack.back().Directive;
204 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000205 /// \brief Returns parent directive.
206 OpenMPDirectiveKind getParentDirective() const {
207 if (Stack.size() > 2)
208 return Stack[Stack.size() - 2].Directive;
209 return OMPD_unknown;
210 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000211
212 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000213 void setDefaultDSANone(SourceLocation Loc) {
214 Stack.back().DefaultAttr = DSA_none;
215 Stack.back().DefaultAttrLoc = Loc;
216 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000217 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000218 void setDefaultDSAShared(SourceLocation Loc) {
219 Stack.back().DefaultAttr = DSA_shared;
220 Stack.back().DefaultAttrLoc = Loc;
221 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000222
223 DefaultDataSharingAttributes getDefaultDSA() const {
224 return Stack.back().DefaultAttr;
225 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000226 SourceLocation getDefaultDSALocation() const {
227 return Stack.back().DefaultAttrLoc;
228 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000229
Alexey Bataevf29276e2014-06-18 04:14:57 +0000230 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000231 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000232 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000233 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000234 }
235
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000236 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000237 void setOrderedRegion(bool IsOrdered, Expr *Param) {
238 Stack.back().OrderedRegion.setInt(IsOrdered);
239 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000240 }
241 /// \brief Returns true, if parent region is ordered (has associated
242 /// 'ordered' clause), false - otherwise.
243 bool isParentOrderedRegion() const {
244 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000245 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000246 return false;
247 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000248 /// \brief Returns optional parameter for the ordered region.
249 Expr *getParentOrderedRegionParam() const {
250 if (Stack.size() > 2)
251 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
252 return nullptr;
253 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000254 /// \brief Marks current region as nowait (it has a 'nowait' clause).
255 void setNowaitRegion(bool IsNowait = true) {
256 Stack.back().NowaitRegion = IsNowait;
257 }
258 /// \brief Returns true, if parent region is nowait (has associated
259 /// 'nowait' clause), false - otherwise.
260 bool isParentNowaitRegion() const {
261 if (Stack.size() > 2)
262 return Stack[Stack.size() - 2].NowaitRegion;
263 return false;
264 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000265 /// \brief Marks parent region as cancel region.
266 void setParentCancelRegion(bool Cancel = true) {
267 if (Stack.size() > 2)
268 Stack[Stack.size() - 2].CancelRegion =
269 Stack[Stack.size() - 2].CancelRegion || Cancel;
270 }
271 /// \brief Return true if current region has inner cancel construct.
272 bool isCancelRegion() const {
273 return Stack.back().CancelRegion;
274 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275
Alexey Bataev9c821032015-04-30 04:23:23 +0000276 /// \brief Set collapse value for the region.
277 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
278 /// \brief Return collapse value for region.
279 unsigned getCollapseNumber() const {
280 return Stack.back().CollapseNumber;
281 }
282
Alexey Bataev13314bf2014-10-09 04:18:56 +0000283 /// \brief Marks current target region as one with closely nested teams
284 /// region.
285 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
286 if (Stack.size() > 2)
287 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
288 }
289 /// \brief Returns true, if current region has closely nested teams region.
290 bool hasInnerTeamsRegion() const {
291 return getInnerTeamsRegionLoc().isValid();
292 }
293 /// \brief Returns location of the nested teams region (if any).
294 SourceLocation getInnerTeamsRegionLoc() const {
295 if (Stack.size() > 1)
296 return Stack.back().InnerTeamsRegionLoc;
297 return SourceLocation();
298 }
299
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000300 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000301 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000302 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000303};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000304bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
305 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000306 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000307}
Alexey Bataeved09d242014-05-28 05:53:51 +0000308} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000309
310DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
311 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000312 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000313 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000314 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000315 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
316 // in a region but not in construct]
317 // File-scope or namespace-scope variables referenced in called routines
318 // in the region are shared unless they appear in a threadprivate
319 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000320 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000321 DVar.CKind = OMPC_shared;
322
323 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
324 // in a region but not in construct]
325 // Variables with static storage duration that are declared in called
326 // routines in the region are shared.
327 if (D->hasGlobalStorage())
328 DVar.CKind = OMPC_shared;
329
Alexey Bataev758e55e2013-09-06 18:03:48 +0000330 return DVar;
331 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000332
Alexey Bataev758e55e2013-09-06 18:03:48 +0000333 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000334 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
335 // in a Construct, C/C++, predetermined, p.1]
336 // Variables with automatic storage duration that are declared in a scope
337 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000338 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
339 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
340 DVar.CKind = OMPC_private;
341 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000342 }
343
Alexey Bataev758e55e2013-09-06 18:03:48 +0000344 // Explicitly specified attributes and local variables with predetermined
345 // attributes.
346 if (Iter->SharingMap.count(D)) {
347 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
348 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000349 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000350 return DVar;
351 }
352
353 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
354 // in a Construct, C/C++, implicitly determined, p.1]
355 // In a parallel or task construct, the data-sharing attributes of these
356 // variables are determined by the default clause, if present.
357 switch (Iter->DefaultAttr) {
358 case DSA_shared:
359 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000360 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000361 return DVar;
362 case DSA_none:
363 return DVar;
364 case DSA_unspecified:
365 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
366 // in a Construct, implicitly determined, p.2]
367 // In a parallel construct, if no default clause is present, these
368 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000369 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000370 if (isOpenMPParallelDirective(DVar.DKind) ||
371 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000372 DVar.CKind = OMPC_shared;
373 return DVar;
374 }
375
376 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
377 // in a Construct, implicitly determined, p.4]
378 // In a task construct, if no default clause is present, a variable that in
379 // the enclosing context is determined to be shared by all implicit tasks
380 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000381 if (DVar.DKind == OMPD_task) {
382 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000383 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000384 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000385 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
386 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000387 // in a Construct, implicitly determined, p.6]
388 // In a task construct, if no default clause is present, a variable
389 // whose data-sharing attribute is not determined by the rules above is
390 // firstprivate.
391 DVarTemp = getDSA(I, D);
392 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000393 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000394 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000395 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000396 return DVar;
397 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000398 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000399 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000400 }
401 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000403 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000404 return DVar;
405 }
406 }
407 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
408 // in a Construct, implicitly determined, p.3]
409 // For constructs other than task, if no default clause is present, these
410 // variables inherit their data-sharing attributes from the enclosing
411 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000412 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000413}
414
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000415DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
416 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000417 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000418 auto It = Stack.back().AlignedMap.find(D);
419 if (It == Stack.back().AlignedMap.end()) {
420 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
421 Stack.back().AlignedMap[D] = NewDE;
422 return nullptr;
423 } else {
424 assert(It->second && "Unexpected nullptr expr in the aligned map");
425 return It->second;
426 }
427 return nullptr;
428}
429
Alexey Bataev9c821032015-04-30 04:23:23 +0000430void DSAStackTy::addLoopControlVariable(VarDecl *D) {
431 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
432 D = D->getCanonicalDecl();
433 Stack.back().LCVSet.insert(D);
434}
435
436bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
437 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
438 D = D->getCanonicalDecl();
439 return Stack.back().LCVSet.count(D) > 0;
440}
441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000443 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000444 if (A == OMPC_threadprivate) {
445 Stack[0].SharingMap[D].Attributes = A;
446 Stack[0].SharingMap[D].RefExpr = E;
447 } else {
448 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
449 Stack.back().SharingMap[D].Attributes = A;
450 Stack.back().SharingMap[D].RefExpr = E;
451 }
452}
453
Alexey Bataeved09d242014-05-28 05:53:51 +0000454bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000455 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000456 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000457 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000458 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000460 ++I;
461 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000462 if (I == E)
463 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000464 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000465 Scope *CurScope = getCurScope();
466 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000467 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000468 }
469 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000470 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000471 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000472}
473
Alexey Bataev39f915b82015-05-08 10:41:21 +0000474/// \brief Build a variable declaration for OpenMP loop iteration variable.
475static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000476 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000477 DeclContext *DC = SemaRef.CurContext;
478 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
479 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
480 VarDecl *Decl =
481 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000482 if (Attrs) {
483 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
484 I != E; ++I)
485 Decl->addAttr(*I);
486 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000487 Decl->setImplicit();
488 return Decl;
489}
490
491static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
492 SourceLocation Loc,
493 bool RefersToCapture = false) {
494 D->setReferenced();
495 D->markUsed(S.Context);
496 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
497 SourceLocation(), D, RefersToCapture, Loc, Ty,
498 VK_LValue);
499}
500
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000501DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000502 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000503 DSAVarData DVar;
504
505 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
506 // in a Construct, C/C++, predetermined, p.1]
507 // Variables appearing in threadprivate directives are threadprivate.
Samuel Antaof8b50122015-07-13 22:54:53 +0000508 if ((D->getTLSKind() != VarDecl::TLS_None &&
509 !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
510 SemaRef.getLangOpts().OpenMPUseTLS &&
511 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000512 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
513 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000514 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
515 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000516 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000517 }
518 if (Stack[0].SharingMap.count(D)) {
519 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
520 DVar.CKind = OMPC_threadprivate;
521 return DVar;
522 }
523
524 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
525 // in a Construct, C/C++, predetermined, p.1]
526 // Variables with automatic storage duration that are declared in a scope
527 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000528 OpenMPDirectiveKind Kind =
529 FromParent ? getParentDirective() : getCurrentDirective();
530 auto StartI = std::next(Stack.rbegin());
531 auto EndI = std::prev(Stack.rend());
532 if (FromParent && StartI != EndI) {
533 StartI = std::next(StartI);
534 }
535 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000536 if (isOpenMPLocal(D, StartI) &&
537 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
538 D->getStorageClass() == SC_None)) ||
539 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000540 DVar.CKind = OMPC_private;
541 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000542 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000543
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000544 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
545 // in a Construct, C/C++, predetermined, p.4]
546 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000547 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
548 // in a Construct, C/C++, predetermined, p.7]
549 // Variables with static storage duration that are declared in a scope
550 // inside the construct are shared.
Kelvin Li4eea8c62015-09-15 18:56:58 +0000551 if (D->isStaticDataMember()) {
Alexey Bataev42971a32015-01-20 07:03:46 +0000552 DSAVarData DVarTemp =
553 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
554 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
555 return DVar;
556
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000557 DVar.CKind = OMPC_shared;
558 return DVar;
559 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000560 }
561
562 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000563 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
564 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000565 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
566 // in a Construct, C/C++, predetermined, p.6]
567 // Variables with const qualified type having no mutable member are
568 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000569 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000570 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000571 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000572 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 // Variables with const-qualified type having no mutable member may be
574 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000575 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
576 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000577 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
578 return DVar;
579
Alexey Bataev758e55e2013-09-06 18:03:48 +0000580 DVar.CKind = OMPC_shared;
581 return DVar;
582 }
583
Alexey Bataev758e55e2013-09-06 18:03:48 +0000584 // Explicitly specified attributes and local variables with predetermined
585 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000586 auto I = std::prev(StartI);
587 if (I->SharingMap.count(D)) {
588 DVar.RefExpr = I->SharingMap[D].RefExpr;
589 DVar.CKind = I->SharingMap[D].Attributes;
590 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000591 }
592
593 return DVar;
594}
595
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000596DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000597 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000598 auto StartI = Stack.rbegin();
599 auto EndI = std::prev(Stack.rend());
600 if (FromParent && StartI != EndI) {
601 StartI = std::next(StartI);
602 }
603 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000604}
605
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606template <class ClausesPredicate, class DirectivesPredicate>
607DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 DirectivesPredicate DPred,
609 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000610 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000611 auto StartI = std::next(Stack.rbegin());
612 auto EndI = std::prev(Stack.rend());
613 if (FromParent && StartI != EndI) {
614 StartI = std::next(StartI);
615 }
616 for (auto I = StartI, EE = EndI; I != EE; ++I) {
617 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000618 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000619 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000620 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000621 return DVar;
622 }
623 return DSAVarData();
624}
625
Alexey Bataevf29276e2014-06-18 04:14:57 +0000626template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000627DSAStackTy::DSAVarData
628DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
629 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000630 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000631 auto StartI = std::next(Stack.rbegin());
632 auto EndI = std::prev(Stack.rend());
633 if (FromParent && StartI != EndI) {
634 StartI = std::next(StartI);
635 }
636 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000637 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000638 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000639 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000640 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000641 return DVar;
642 return DSAVarData();
643 }
644 return DSAVarData();
645}
646
Alexey Bataevaac108a2015-06-23 04:51:00 +0000647bool DSAStackTy::hasExplicitDSA(
648 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
649 unsigned Level) {
650 if (CPred(ClauseKindMode))
651 return true;
652 if (isClauseParsingMode())
653 ++Level;
654 D = D->getCanonicalDecl();
655 auto StartI = Stack.rbegin();
656 auto EndI = std::prev(Stack.rend());
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000657 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000658 return false;
659 std::advance(StartI, Level);
660 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
661 CPred(StartI->SharingMap[D].Attributes);
662}
663
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000664template <class NamedDirectivesPredicate>
665bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
666 auto StartI = std::next(Stack.rbegin());
667 auto EndI = std::prev(Stack.rend());
668 if (FromParent && StartI != EndI) {
669 StartI = std::next(StartI);
670 }
671 for (auto I = StartI, EE = EndI; I != EE; ++I) {
672 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
673 return true;
674 }
675 return false;
676}
677
Alexey Bataev758e55e2013-09-06 18:03:48 +0000678void Sema::InitDataSharingAttributesStack() {
679 VarDataSharingAttributesStack = new DSAStackTy(*this);
680}
681
682#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
683
Alexey Bataevf841bd92014-12-16 07:00:22 +0000684bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
685 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000686 VD = VD->getCanonicalDecl();
Alexey Bataev48977c32015-08-04 08:10:48 +0000687 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
688 (!DSAStack->isClauseParsingMode() ||
689 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000690 if (DSAStack->isLoopControlVariable(VD) ||
691 (VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000692 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
693 DSAStack->isForceVarCapturing())
Alexey Bataev9c821032015-04-30 04:23:23 +0000694 return true;
Alexey Bataevaac108a2015-06-23 04:51:00 +0000695 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000696 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
697 return true;
698 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataevaac108a2015-06-23 04:51:00 +0000699 DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000700 return DVarPrivate.CKind != OMPC_unknown;
701 }
702 return false;
703}
704
Alexey Bataevaac108a2015-06-23 04:51:00 +0000705bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
706 assert(LangOpts.OpenMP && "OpenMP is not allowed");
707 return DSAStack->hasExplicitDSA(
708 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
709}
710
Alexey Bataeved09d242014-05-28 05:53:51 +0000711void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000712
713void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
714 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000715 Scope *CurScope, SourceLocation Loc) {
716 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000717 PushExpressionEvaluationContext(PotentiallyEvaluated);
718}
719
Alexey Bataevaac108a2015-06-23 04:51:00 +0000720void Sema::StartOpenMPClause(OpenMPClauseKind K) {
721 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000722}
723
Alexey Bataevaac108a2015-06-23 04:51:00 +0000724void Sema::EndOpenMPClause() {
725 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000726}
727
Alexey Bataev758e55e2013-09-06 18:03:48 +0000728void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000729 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
730 // A variable of class type (or array thereof) that appears in a lastprivate
731 // clause requires an accessible, unambiguous default constructor for the
732 // class type, unless the list item is also specified in a firstprivate
733 // clause.
734 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000735 for (auto *C : D->clauses()) {
736 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
737 SmallVector<Expr *, 8> PrivateCopies;
738 for (auto *DE : Clause->varlists()) {
739 if (DE->isValueDependent() || DE->isTypeDependent()) {
740 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000741 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000742 }
743 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000744 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000745 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000746 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000747 // Generate helper private variable and initialize it with the
748 // default value. The address of the original variable is replaced
749 // by the address of the new private variable in CodeGen. This new
750 // variable is not added to IdResolver, so the code in the OpenMP
751 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000752 auto *VDPrivate = buildVarDecl(
753 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
754 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +0000755 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
756 if (VDPrivate->isInvalidDecl())
757 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000758 PrivateCopies.push_back(buildDeclRefExpr(
759 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000760 } else {
761 // The variable is also a firstprivate, so initialization sequence
762 // for private copy is generated already.
763 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000764 }
765 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000766 // Set initializers to private copies if no errors were found.
767 if (PrivateCopies.size() == Clause->varlist_size()) {
768 Clause->setPrivateCopies(PrivateCopies);
769 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000770 }
771 }
772 }
773
Alexey Bataev758e55e2013-09-06 18:03:48 +0000774 DSAStack->pop();
775 DiscardCleanupsInEvaluationContext();
776 PopExpressionEvaluationContext();
777}
778
Alexander Musman3276a272015-03-21 10:12:56 +0000779static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
780 Expr *NumIterations, Sema &SemaRef,
781 Scope *S);
782
Alexey Bataeva769e072013-03-22 06:34:35 +0000783namespace {
784
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000785class VarDeclFilterCCC : public CorrectionCandidateCallback {
786private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000787 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000788
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000789public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000790 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000791 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000792 NamedDecl *ND = Candidate.getCorrectionDecl();
793 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
794 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000795 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
796 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000797 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000798 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000799 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000800};
Alexey Bataeved09d242014-05-28 05:53:51 +0000801} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000802
803ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
804 CXXScopeSpec &ScopeSpec,
805 const DeclarationNameInfo &Id) {
806 LookupResult Lookup(*this, Id, LookupOrdinaryName);
807 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
808
809 if (Lookup.isAmbiguous())
810 return ExprError();
811
812 VarDecl *VD;
813 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000814 if (TypoCorrection Corrected = CorrectTypo(
815 Id, LookupOrdinaryName, CurScope, nullptr,
816 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000817 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000818 PDiag(Lookup.empty()
819 ? diag::err_undeclared_var_use_suggest
820 : diag::err_omp_expected_var_arg_suggest)
821 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000822 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000823 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000824 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
825 : diag::err_omp_expected_var_arg)
826 << Id.getName();
827 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000828 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000829 } else {
830 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000831 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000832 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
833 return ExprError();
834 }
835 }
836 Lookup.suppressDiagnostics();
837
838 // OpenMP [2.9.2, Syntax, C/C++]
839 // Variables must be file-scope, namespace-scope, or static block-scope.
840 if (!VD->hasGlobalStorage()) {
841 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000842 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
843 bool IsDecl =
844 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000845 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000846 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
847 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000848 return ExprError();
849 }
850
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000851 VarDecl *CanonicalVD = VD->getCanonicalDecl();
852 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000853 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
854 // A threadprivate directive for file-scope variables must appear outside
855 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000856 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
857 !getCurLexicalContext()->isTranslationUnit()) {
858 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000859 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
860 bool IsDecl =
861 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
862 Diag(VD->getLocation(),
863 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
864 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000865 return ExprError();
866 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000867 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
868 // A threadprivate directive for static class member variables must appear
869 // in the class definition, in the same scope in which the member
870 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000871 if (CanonicalVD->isStaticDataMember() &&
872 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
873 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000874 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
875 bool IsDecl =
876 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
877 Diag(VD->getLocation(),
878 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
879 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000880 return ExprError();
881 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000882 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
883 // A threadprivate directive for namespace-scope variables must appear
884 // outside any definition or declaration other than the namespace
885 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000886 if (CanonicalVD->getDeclContext()->isNamespace() &&
887 (!getCurLexicalContext()->isFileContext() ||
888 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
889 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000890 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
891 bool IsDecl =
892 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
893 Diag(VD->getLocation(),
894 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
895 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000896 return ExprError();
897 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000898 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
899 // A threadprivate directive for static block-scope variables must appear
900 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000901 if (CanonicalVD->isStaticLocal() && CurScope &&
902 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000903 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000904 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
905 bool IsDecl =
906 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
907 Diag(VD->getLocation(),
908 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
909 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000910 return ExprError();
911 }
912
913 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
914 // A threadprivate directive must lexically precede all references to any
915 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000916 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000917 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +0000918 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000919 return ExprError();
920 }
921
922 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +0000923 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000924 return DE;
925}
926
Alexey Bataeved09d242014-05-28 05:53:51 +0000927Sema::DeclGroupPtrTy
928Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
929 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000930 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000931 CurContext->addDecl(D);
932 return DeclGroupPtrTy::make(DeclGroupRef(D));
933 }
934 return DeclGroupPtrTy();
935}
936
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000937namespace {
938class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
939 Sema &SemaRef;
940
941public:
942 bool VisitDeclRefExpr(const DeclRefExpr *E) {
943 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
944 if (VD->hasLocalStorage()) {
945 SemaRef.Diag(E->getLocStart(),
946 diag::err_omp_local_var_in_threadprivate_init)
947 << E->getSourceRange();
948 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
949 << VD << VD->getSourceRange();
950 return true;
951 }
952 }
953 return false;
954 }
955 bool VisitStmt(const Stmt *S) {
956 for (auto Child : S->children()) {
957 if (Child && Visit(Child))
958 return true;
959 }
960 return false;
961 }
Alexey Bataev23b69422014-06-18 07:08:49 +0000962 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +0000963};
964} // namespace
965
Alexey Bataeved09d242014-05-28 05:53:51 +0000966OMPThreadPrivateDecl *
967Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000968 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +0000969 for (auto &RefExpr : VarList) {
970 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000971 VarDecl *VD = cast<VarDecl>(DE->getDecl());
972 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +0000973
Alexey Bataevf56f98c2015-04-16 05:39:01 +0000974 QualType QType = VD->getType();
975 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
976 // It will be analyzed later.
977 Vars.push_back(DE);
978 continue;
979 }
980
Alexey Bataeva769e072013-03-22 06:34:35 +0000981 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
982 // A threadprivate variable must not have an incomplete type.
983 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000984 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +0000985 continue;
986 }
987
988 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
989 // A threadprivate variable must not have a reference type.
990 if (VD->getType()->isReferenceType()) {
991 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000992 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
993 bool IsDecl =
994 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
995 Diag(VD->getLocation(),
996 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
997 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +0000998 continue;
999 }
1000
Samuel Antaof8b50122015-07-13 22:54:53 +00001001 // Check if this is a TLS variable. If TLS is not being supported, produce
1002 // the corresponding diagnostic.
1003 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1004 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1005 getLangOpts().OpenMPUseTLS &&
1006 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001007 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1008 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001009 Diag(ILoc, diag::err_omp_var_thread_local)
1010 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001011 bool IsDecl =
1012 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1013 Diag(VD->getLocation(),
1014 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1015 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001016 continue;
1017 }
1018
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001019 // Check if initial value of threadprivate variable reference variable with
1020 // local storage (it is not supported by runtime).
1021 if (auto Init = VD->getAnyInitializer()) {
1022 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001023 if (Checker.Visit(Init))
1024 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001025 }
1026
Alexey Bataeved09d242014-05-28 05:53:51 +00001027 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001028 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001029 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1030 Context, SourceRange(Loc, Loc)));
1031 if (auto *ML = Context.getASTMutationListener())
1032 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001033 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001034 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001035 if (!Vars.empty()) {
1036 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1037 Vars);
1038 D->setAccess(AS_public);
1039 }
1040 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001041}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001042
Alexey Bataev7ff55242014-06-19 09:13:45 +00001043static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1044 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1045 bool IsLoopIterVar = false) {
1046 if (DVar.RefExpr) {
1047 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1048 << getOpenMPClauseName(DVar.CKind);
1049 return;
1050 }
1051 enum {
1052 PDSA_StaticMemberShared,
1053 PDSA_StaticLocalVarShared,
1054 PDSA_LoopIterVarPrivate,
1055 PDSA_LoopIterVarLinear,
1056 PDSA_LoopIterVarLastprivate,
1057 PDSA_ConstVarShared,
1058 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001059 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001060 PDSA_LocalVarPrivate,
1061 PDSA_Implicit
1062 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001063 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001064 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +00001065 if (IsLoopIterVar) {
1066 if (DVar.CKind == OMPC_private)
1067 Reason = PDSA_LoopIterVarPrivate;
1068 else if (DVar.CKind == OMPC_lastprivate)
1069 Reason = PDSA_LoopIterVarLastprivate;
1070 else
1071 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001072 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1073 Reason = PDSA_TaskVarFirstprivate;
1074 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001075 } else if (VD->isStaticLocal())
1076 Reason = PDSA_StaticLocalVarShared;
1077 else if (VD->isStaticDataMember())
1078 Reason = PDSA_StaticMemberShared;
1079 else if (VD->isFileVarDecl())
1080 Reason = PDSA_GlobalVarShared;
1081 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1082 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001083 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001084 ReportHint = true;
1085 Reason = PDSA_LocalVarPrivate;
1086 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001087 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001088 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001089 << Reason << ReportHint
1090 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1091 } else if (DVar.ImplicitDSALoc.isValid()) {
1092 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1093 << getOpenMPClauseName(DVar.CKind);
1094 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001095}
1096
Alexey Bataev758e55e2013-09-06 18:03:48 +00001097namespace {
1098class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1099 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001100 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001101 bool ErrorFound;
1102 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001103 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001104 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001105
Alexey Bataev758e55e2013-09-06 18:03:48 +00001106public:
1107 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001108 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001109 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001110 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1111 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001112
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001113 auto DVar = Stack->getTopDSA(VD, false);
1114 // Check if the variable has explicit DSA set and stop analysis if it so.
1115 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001116
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001117 auto ELoc = E->getExprLoc();
1118 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001119 // The default(none) clause requires that each variable that is referenced
1120 // in the construct, and does not have a predetermined data-sharing
1121 // attribute, must have its data-sharing attribute explicitly determined
1122 // by being listed in a data-sharing attribute clause.
1123 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001124 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001125 VarsWithInheritedDSA.count(VD) == 0) {
1126 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001127 return;
1128 }
1129
1130 // OpenMP [2.9.3.6, Restrictions, p.2]
1131 // A list item that appears in a reduction clause of the innermost
1132 // enclosing worksharing or parallel construct may not be accessed in an
1133 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001134 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001135 [](OpenMPDirectiveKind K) -> bool {
1136 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001137 isOpenMPWorksharingDirective(K) ||
1138 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001139 },
1140 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001141 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1142 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001143 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1144 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001145 return;
1146 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001147
1148 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001149 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001150 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001151 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001152 }
1153 }
1154 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001155 for (auto *C : S->clauses()) {
1156 // Skip analysis of arguments of implicitly defined firstprivate clause
1157 // for task directives.
1158 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1159 for (auto *CC : C->children()) {
1160 if (CC)
1161 Visit(CC);
1162 }
1163 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001164 }
1165 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001166 for (auto *C : S->children()) {
1167 if (C && !isa<OMPExecutableDirective>(C))
1168 Visit(C);
1169 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001170 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001171
1172 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001173 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001174 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1175 return VarsWithInheritedDSA;
1176 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001177
Alexey Bataev7ff55242014-06-19 09:13:45 +00001178 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1179 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001180};
Alexey Bataeved09d242014-05-28 05:53:51 +00001181} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001182
Alexey Bataevbae9a792014-06-27 10:37:06 +00001183void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001184 switch (DKind) {
1185 case OMPD_parallel: {
1186 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001187 QualType KmpInt32PtrTy =
1188 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001189 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001190 std::make_pair(".global_tid.", KmpInt32PtrTy),
1191 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1192 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001193 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001194 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1195 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001196 break;
1197 }
1198 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001199 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001200 std::make_pair(StringRef(), QualType()) // __context with shared vars
1201 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001202 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1203 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001204 break;
1205 }
1206 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001207 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001208 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001209 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001210 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1211 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001212 break;
1213 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001214 case OMPD_for_simd: {
1215 Sema::CapturedParamNameType Params[] = {
1216 std::make_pair(StringRef(), QualType()) // __context with shared vars
1217 };
1218 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1219 Params);
1220 break;
1221 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001222 case OMPD_sections: {
1223 Sema::CapturedParamNameType Params[] = {
1224 std::make_pair(StringRef(), QualType()) // __context with shared vars
1225 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001226 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1227 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001228 break;
1229 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001230 case OMPD_section: {
1231 Sema::CapturedParamNameType Params[] = {
1232 std::make_pair(StringRef(), QualType()) // __context with shared vars
1233 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001234 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1235 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001236 break;
1237 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001238 case OMPD_single: {
1239 Sema::CapturedParamNameType Params[] = {
1240 std::make_pair(StringRef(), QualType()) // __context with shared vars
1241 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001242 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1243 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001244 break;
1245 }
Alexander Musman80c22892014-07-17 08:54:58 +00001246 case OMPD_master: {
1247 Sema::CapturedParamNameType Params[] = {
1248 std::make_pair(StringRef(), QualType()) // __context with shared vars
1249 };
1250 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1251 Params);
1252 break;
1253 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001254 case OMPD_critical: {
1255 Sema::CapturedParamNameType Params[] = {
1256 std::make_pair(StringRef(), QualType()) // __context with shared vars
1257 };
1258 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1259 Params);
1260 break;
1261 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001262 case OMPD_parallel_for: {
1263 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001264 QualType KmpInt32PtrTy =
1265 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev4acb8592014-07-07 13:01:15 +00001266 Sema::CapturedParamNameType Params[] = {
1267 std::make_pair(".global_tid.", KmpInt32PtrTy),
1268 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1269 std::make_pair(StringRef(), QualType()) // __context with shared vars
1270 };
1271 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1272 Params);
1273 break;
1274 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001275 case OMPD_parallel_for_simd: {
1276 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001277 QualType KmpInt32PtrTy =
1278 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexander Musmane4e893b2014-09-23 09:33:00 +00001279 Sema::CapturedParamNameType Params[] = {
1280 std::make_pair(".global_tid.", KmpInt32PtrTy),
1281 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1282 std::make_pair(StringRef(), QualType()) // __context with shared vars
1283 };
1284 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1285 Params);
1286 break;
1287 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001288 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001289 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001290 QualType KmpInt32PtrTy =
1291 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001292 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001293 std::make_pair(".global_tid.", KmpInt32PtrTy),
1294 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001295 std::make_pair(StringRef(), QualType()) // __context with shared vars
1296 };
1297 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1298 Params);
1299 break;
1300 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001301 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001302 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001303 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1304 FunctionProtoType::ExtProtoInfo EPI;
1305 EPI.Variadic = true;
1306 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001307 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001308 std::make_pair(".global_tid.", KmpInt32Ty),
1309 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001310 std::make_pair(".privates.",
1311 Context.VoidPtrTy.withConst().withRestrict()),
1312 std::make_pair(
1313 ".copy_fn.",
1314 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001315 std::make_pair(StringRef(), QualType()) // __context with shared vars
1316 };
1317 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1318 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001319 // Mark this captured region as inlined, because we don't use outlined
1320 // function directly.
1321 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1322 AlwaysInlineAttr::CreateImplicit(
1323 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001324 break;
1325 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001326 case OMPD_ordered: {
1327 Sema::CapturedParamNameType Params[] = {
1328 std::make_pair(StringRef(), QualType()) // __context with shared vars
1329 };
1330 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1331 Params);
1332 break;
1333 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001334 case OMPD_atomic: {
1335 Sema::CapturedParamNameType Params[] = {
1336 std::make_pair(StringRef(), QualType()) // __context with shared vars
1337 };
1338 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1339 Params);
1340 break;
1341 }
Michael Wong65f367f2015-07-21 13:44:28 +00001342 case OMPD_target_data:
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001343 case OMPD_target: {
1344 Sema::CapturedParamNameType Params[] = {
1345 std::make_pair(StringRef(), QualType()) // __context with shared vars
1346 };
1347 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1348 Params);
1349 break;
1350 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001351 case OMPD_teams: {
1352 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001353 QualType KmpInt32PtrTy =
1354 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev13314bf2014-10-09 04:18:56 +00001355 Sema::CapturedParamNameType Params[] = {
1356 std::make_pair(".global_tid.", KmpInt32PtrTy),
1357 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1358 std::make_pair(StringRef(), QualType()) // __context with shared vars
1359 };
1360 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1361 Params);
1362 break;
1363 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001364 case OMPD_taskgroup: {
1365 Sema::CapturedParamNameType Params[] = {
1366 std::make_pair(StringRef(), QualType()) // __context with shared vars
1367 };
1368 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1369 Params);
1370 break;
1371 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001372 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001373 case OMPD_taskyield:
1374 case OMPD_barrier:
1375 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001376 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001377 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001378 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001379 llvm_unreachable("OpenMP Directive is not allowed");
1380 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001381 llvm_unreachable("Unknown OpenMP directive");
1382 }
1383}
1384
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001385StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1386 ArrayRef<OMPClause *> Clauses) {
1387 if (!S.isUsable()) {
1388 ActOnCapturedRegionError();
1389 return StmtError();
1390 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001391 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001392 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001393 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001394 Clause->getClauseKind() == OMPC_copyprivate ||
1395 (getLangOpts().OpenMPUseTLS &&
1396 getASTContext().getTargetInfo().isTLSSupported() &&
1397 Clause->getClauseKind() == OMPC_copyin)) {
1398 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001399 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001400 for (auto *VarRef : Clause->children()) {
1401 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001402 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001403 }
1404 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001405 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev040d5402015-05-12 08:35:28 +00001406 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1407 Clause->getClauseKind() == OMPC_schedule) {
1408 // Mark all variables in private list clauses as used in inner region.
1409 // Required for proper codegen of combined directives.
1410 // TODO: add processing for other clauses.
1411 if (auto *E = cast_or_null<Expr>(
1412 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1413 MarkDeclarationsReferencedInExpr(E);
1414 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001415 }
1416 }
1417 return ActOnCapturedRegionEnd(S.get());
1418}
1419
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001420static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1421 OpenMPDirectiveKind CurrentRegion,
1422 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001423 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001424 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001425 // Allowed nesting of constructs
1426 // +------------------+-----------------+------------------------------------+
1427 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1428 // +------------------+-----------------+------------------------------------+
1429 // | parallel | parallel | * |
1430 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001431 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001432 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001433 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001434 // | parallel | simd | * |
1435 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001436 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001437 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001438 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001439 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001440 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001441 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001442 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001443 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001444 // | parallel | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001445 // | parallel | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001446 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001447 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001448 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001449 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001450 // | parallel | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001451 // | parallel | cancellation | |
1452 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001453 // | parallel | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001454 // +------------------+-----------------+------------------------------------+
1455 // | for | parallel | * |
1456 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001457 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001458 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001459 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001460 // | for | simd | * |
1461 // | for | sections | + |
1462 // | for | section | + |
1463 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001464 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001465 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001466 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001467 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001468 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001469 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001470 // | for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001471 // | for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001472 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001473 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001474 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001475 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001476 // | for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001477 // | for | cancellation | |
1478 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001479 // | for | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001480 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001481 // | master | parallel | * |
1482 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001483 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001484 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001485 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001486 // | master | simd | * |
1487 // | master | sections | + |
1488 // | master | section | + |
1489 // | master | single | + |
1490 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001491 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001492 // | master |parallel sections| * |
1493 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001494 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001495 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001496 // | master | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001497 // | master | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001498 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001499 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001500 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001501 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001502 // | master | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001503 // | master | cancellation | |
1504 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001505 // | master | cancel | |
Alexander Musman80c22892014-07-17 08:54:58 +00001506 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001507 // | critical | parallel | * |
1508 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001509 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001510 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001511 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001512 // | critical | simd | * |
1513 // | critical | sections | + |
1514 // | critical | section | + |
1515 // | critical | single | + |
1516 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001517 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001518 // | critical |parallel sections| * |
1519 // | critical | task | * |
1520 // | critical | taskyield | * |
1521 // | critical | barrier | + |
1522 // | critical | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001523 // | critical | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001524 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001525 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001526 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001527 // | critical | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001528 // | critical | cancellation | |
1529 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001530 // | critical | cancel | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001531 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001532 // | simd | parallel | |
1533 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001534 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001535 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001536 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001537 // | simd | simd | |
1538 // | simd | sections | |
1539 // | simd | section | |
1540 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001541 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001542 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001543 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001544 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001545 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001546 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001547 // | simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001548 // | simd | taskgroup | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001549 // | simd | flush | |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001550 // | simd | ordered | |
Alexey Bataev0162e452014-07-22 10:10:35 +00001551 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001552 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001553 // | simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001554 // | simd | cancellation | |
1555 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001556 // | simd | cancel | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001557 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001558 // | for simd | parallel | |
1559 // | for simd | for | |
1560 // | for simd | for simd | |
1561 // | for simd | master | |
1562 // | for simd | critical | |
1563 // | for simd | simd | |
1564 // | for simd | sections | |
1565 // | for simd | section | |
1566 // | for simd | single | |
1567 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001568 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001569 // | for simd |parallel sections| |
1570 // | for simd | task | |
1571 // | for simd | taskyield | |
1572 // | for simd | barrier | |
1573 // | for simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001574 // | for simd | taskgroup | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001575 // | for simd | flush | |
1576 // | for simd | ordered | |
1577 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001578 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001579 // | for simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001580 // | for simd | cancellation | |
1581 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001582 // | for simd | cancel | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001583 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001584 // | parallel for simd| parallel | |
1585 // | parallel for simd| for | |
1586 // | parallel for simd| for simd | |
1587 // | parallel for simd| master | |
1588 // | parallel for simd| critical | |
1589 // | parallel for simd| simd | |
1590 // | parallel for simd| sections | |
1591 // | parallel for simd| section | |
1592 // | parallel for simd| single | |
1593 // | parallel for simd| parallel for | |
1594 // | parallel for simd|parallel for simd| |
1595 // | parallel for simd|parallel sections| |
1596 // | parallel for simd| task | |
1597 // | parallel for simd| taskyield | |
1598 // | parallel for simd| barrier | |
1599 // | parallel for simd| taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001600 // | parallel for simd| taskgroup | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001601 // | parallel for simd| flush | |
1602 // | parallel for simd| ordered | |
1603 // | parallel for simd| atomic | |
1604 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001605 // | parallel for simd| teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001606 // | parallel for simd| cancellation | |
1607 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001608 // | parallel for simd| cancel | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001609 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001610 // | sections | parallel | * |
1611 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001612 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001613 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001614 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001615 // | sections | simd | * |
1616 // | sections | sections | + |
1617 // | sections | section | * |
1618 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001619 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001620 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001621 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001622 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001623 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001624 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001625 // | sections | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001626 // | sections | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001627 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001628 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001629 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001630 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001631 // | sections | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001632 // | sections | cancellation | |
1633 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001634 // | sections | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001635 // +------------------+-----------------+------------------------------------+
1636 // | section | parallel | * |
1637 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001638 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001639 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001640 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001641 // | section | simd | * |
1642 // | section | sections | + |
1643 // | section | section | + |
1644 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001645 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001646 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001647 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001648 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001649 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001650 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001651 // | section | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001652 // | section | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001653 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001654 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001655 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001656 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001657 // | section | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001658 // | section | cancellation | |
1659 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001660 // | section | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001661 // +------------------+-----------------+------------------------------------+
1662 // | single | parallel | * |
1663 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001664 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001665 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001666 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001667 // | single | simd | * |
1668 // | single | sections | + |
1669 // | single | section | + |
1670 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001671 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001672 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001673 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001674 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001675 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001676 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001677 // | single | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001678 // | single | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001679 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001680 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001681 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001682 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001683 // | single | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001684 // | single | cancellation | |
1685 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001686 // | single | cancel | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001687 // +------------------+-----------------+------------------------------------+
1688 // | parallel for | parallel | * |
1689 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001690 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001691 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001692 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001693 // | parallel for | simd | * |
1694 // | parallel for | sections | + |
1695 // | parallel for | section | + |
1696 // | parallel for | single | + |
1697 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001698 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001699 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001700 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001701 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001702 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001703 // | parallel for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001704 // | parallel for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001705 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001706 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001707 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001708 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001709 // | parallel for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001710 // | parallel for | cancellation | |
1711 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001712 // | parallel for | cancel | ! |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001713 // +------------------+-----------------+------------------------------------+
1714 // | parallel sections| parallel | * |
1715 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001716 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001717 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001718 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001719 // | parallel sections| simd | * |
1720 // | parallel sections| sections | + |
1721 // | parallel sections| section | * |
1722 // | parallel sections| single | + |
1723 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001724 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001725 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001726 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001727 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001728 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001729 // | parallel sections| taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001730 // | parallel sections| taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001731 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001732 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001733 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001734 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001735 // | parallel sections| teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001736 // | parallel sections| cancellation | |
1737 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001738 // | parallel sections| cancel | ! |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001739 // +------------------+-----------------+------------------------------------+
1740 // | task | parallel | * |
1741 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001742 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001743 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001744 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001745 // | task | simd | * |
1746 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001747 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001748 // | task | single | + |
1749 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001750 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001751 // | task |parallel sections| * |
1752 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001753 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001754 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001755 // | task | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001756 // | task | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001757 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001758 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001759 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001760 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001761 // | task | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001762 // | task | cancellation | |
Alexey Bataev80909872015-07-02 11:25:17 +00001763 // | | point | ! |
1764 // | task | cancel | ! |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001765 // +------------------+-----------------+------------------------------------+
1766 // | ordered | parallel | * |
1767 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001768 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001769 // | ordered | master | * |
1770 // | ordered | critical | * |
1771 // | ordered | simd | * |
1772 // | ordered | sections | + |
1773 // | ordered | section | + |
1774 // | ordered | single | + |
1775 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001776 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001777 // | ordered |parallel sections| * |
1778 // | ordered | task | * |
1779 // | ordered | taskyield | * |
1780 // | ordered | barrier | + |
1781 // | ordered | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001782 // | ordered | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001783 // | ordered | flush | * |
1784 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001785 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001786 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001787 // | ordered | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001788 // | ordered | cancellation | |
1789 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001790 // | ordered | cancel | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001791 // +------------------+-----------------+------------------------------------+
1792 // | atomic | parallel | |
1793 // | atomic | for | |
1794 // | atomic | for simd | |
1795 // | atomic | master | |
1796 // | atomic | critical | |
1797 // | atomic | simd | |
1798 // | atomic | sections | |
1799 // | atomic | section | |
1800 // | atomic | single | |
1801 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001802 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001803 // | atomic |parallel sections| |
1804 // | atomic | task | |
1805 // | atomic | taskyield | |
1806 // | atomic | barrier | |
1807 // | atomic | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001808 // | atomic | taskgroup | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001809 // | atomic | flush | |
1810 // | atomic | ordered | |
1811 // | atomic | atomic | |
1812 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001813 // | atomic | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001814 // | atomic | cancellation | |
1815 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001816 // | atomic | cancel | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001817 // +------------------+-----------------+------------------------------------+
1818 // | target | parallel | * |
1819 // | target | for | * |
1820 // | target | for simd | * |
1821 // | target | master | * |
1822 // | target | critical | * |
1823 // | target | simd | * |
1824 // | target | sections | * |
1825 // | target | section | * |
1826 // | target | single | * |
1827 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001828 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001829 // | target |parallel sections| * |
1830 // | target | task | * |
1831 // | target | taskyield | * |
1832 // | target | barrier | * |
1833 // | target | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001834 // | target | taskgroup | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001835 // | target | flush | * |
1836 // | target | ordered | * |
1837 // | target | atomic | * |
1838 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001839 // | target | teams | * |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001840 // | target | cancellation | |
1841 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001842 // | target | cancel | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001843 // +------------------+-----------------+------------------------------------+
1844 // | teams | parallel | * |
1845 // | teams | for | + |
1846 // | teams | for simd | + |
1847 // | teams | master | + |
1848 // | teams | critical | + |
1849 // | teams | simd | + |
1850 // | teams | sections | + |
1851 // | teams | section | + |
1852 // | teams | single | + |
1853 // | teams | parallel for | * |
1854 // | teams |parallel for simd| * |
1855 // | teams |parallel sections| * |
1856 // | teams | task | + |
1857 // | teams | taskyield | + |
1858 // | teams | barrier | + |
1859 // | teams | taskwait | + |
Alexey Bataev80909872015-07-02 11:25:17 +00001860 // | teams | taskgroup | + |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001861 // | teams | flush | + |
1862 // | teams | ordered | + |
1863 // | teams | atomic | + |
1864 // | teams | target | + |
1865 // | teams | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001866 // | teams | cancellation | |
1867 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001868 // | teams | cancel | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001869 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001870 if (Stack->getCurScope()) {
1871 auto ParentRegion = Stack->getParentDirective();
1872 bool NestingProhibited = false;
1873 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001874 enum {
1875 NoRecommend,
1876 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001877 ShouldBeInOrderedRegion,
1878 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001879 } Recommend = NoRecommend;
Alexey Bataev549210e2014-06-24 04:39:47 +00001880 if (isOpenMPSimdDirective(ParentRegion)) {
1881 // OpenMP [2.16, Nesting of Regions]
1882 // OpenMP constructs may not be nested inside a simd region.
1883 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1884 return true;
1885 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001886 if (ParentRegion == OMPD_atomic) {
1887 // OpenMP [2.16, Nesting of Regions]
1888 // OpenMP constructs may not be nested inside an atomic region.
1889 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1890 return true;
1891 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001892 if (CurrentRegion == OMPD_section) {
1893 // OpenMP [2.7.2, sections Construct, Restrictions]
1894 // Orphaned section directives are prohibited. That is, the section
1895 // directives must appear within the sections construct and must not be
1896 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001897 if (ParentRegion != OMPD_sections &&
1898 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001899 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1900 << (ParentRegion != OMPD_unknown)
1901 << getOpenMPDirectiveName(ParentRegion);
1902 return true;
1903 }
1904 return false;
1905 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001906 // Allow some constructs to be orphaned (they could be used in functions,
1907 // called from OpenMP regions with the required preconditions).
1908 if (ParentRegion == OMPD_unknown)
1909 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001910 if (CurrentRegion == OMPD_cancellation_point ||
1911 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001912 // OpenMP [2.16, Nesting of Regions]
1913 // A cancellation point construct for which construct-type-clause is
1914 // taskgroup must be nested inside a task construct. A cancellation
1915 // point construct for which construct-type-clause is not taskgroup must
1916 // be closely nested inside an OpenMP construct that matches the type
1917 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001918 // A cancel construct for which construct-type-clause is taskgroup must be
1919 // nested inside a task construct. A cancel construct for which
1920 // construct-type-clause is not taskgroup must be closely nested inside an
1921 // OpenMP construct that matches the type specified in
1922 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001923 NestingProhibited =
1924 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001925 (CancelRegion == OMPD_for &&
1926 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001927 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1928 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001929 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1930 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001931 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001932 // OpenMP [2.16, Nesting of Regions]
1933 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001934 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001935 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1936 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001937 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1938 // OpenMP [2.16, Nesting of Regions]
1939 // A critical region may not be nested (closely or otherwise) inside a
1940 // critical region with the same name. Note that this restriction is not
1941 // sufficient to prevent deadlock.
1942 SourceLocation PreviousCriticalLoc;
1943 bool DeadLock =
1944 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1945 OpenMPDirectiveKind K,
1946 const DeclarationNameInfo &DNI,
1947 SourceLocation Loc)
1948 ->bool {
1949 if (K == OMPD_critical &&
1950 DNI.getName() == CurrentName.getName()) {
1951 PreviousCriticalLoc = Loc;
1952 return true;
1953 } else
1954 return false;
1955 },
1956 false /* skip top directive */);
1957 if (DeadLock) {
1958 SemaRef.Diag(StartLoc,
1959 diag::err_omp_prohibited_region_critical_same_name)
1960 << CurrentName.getName();
1961 if (PreviousCriticalLoc.isValid())
1962 SemaRef.Diag(PreviousCriticalLoc,
1963 diag::note_omp_previous_critical_region);
1964 return true;
1965 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001966 } else if (CurrentRegion == OMPD_barrier) {
1967 // OpenMP [2.16, Nesting of Regions]
1968 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001969 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001970 NestingProhibited =
1971 isOpenMPWorksharingDirective(ParentRegion) ||
1972 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1973 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00001974 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00001975 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001976 // OpenMP [2.16, Nesting of Regions]
1977 // A worksharing region may not be closely nested inside a worksharing,
1978 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001979 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00001980 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001981 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1982 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1983 Recommend = ShouldBeInParallelRegion;
1984 } else if (CurrentRegion == OMPD_ordered) {
1985 // OpenMP [2.16, Nesting of Regions]
1986 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00001987 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001988 // An ordered region must be closely nested inside a loop region (or
1989 // parallel loop region) with an ordered clause.
1990 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00001991 ParentRegion == OMPD_task ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001992 !Stack->isParentOrderedRegion();
1993 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00001994 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1995 // OpenMP [2.16, Nesting of Regions]
1996 // If specified, a teams construct must be contained within a target
1997 // construct.
1998 NestingProhibited = ParentRegion != OMPD_target;
1999 Recommend = ShouldBeInTargetRegion;
2000 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2001 }
2002 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2003 // OpenMP [2.16, Nesting of Regions]
2004 // distribute, parallel, parallel sections, parallel workshare, and the
2005 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2006 // constructs that can be closely nested in the teams region.
2007 // TODO: add distribute directive.
2008 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
2009 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002010 }
2011 if (NestingProhibited) {
2012 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002013 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
2014 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00002015 return true;
2016 }
2017 }
2018 return false;
2019}
2020
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002021static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2022 ArrayRef<OMPClause *> Clauses,
2023 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2024 bool ErrorFound = false;
2025 unsigned NamedModifiersNumber = 0;
2026 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2027 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002028 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002029 for (const auto *C : Clauses) {
2030 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2031 // At most one if clause without a directive-name-modifier can appear on
2032 // the directive.
2033 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2034 if (FoundNameModifiers[CurNM]) {
2035 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2036 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2037 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2038 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002039 } else if (CurNM != OMPD_unknown) {
2040 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002041 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002042 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002043 FoundNameModifiers[CurNM] = IC;
2044 if (CurNM == OMPD_unknown)
2045 continue;
2046 // Check if the specified name modifier is allowed for the current
2047 // directive.
2048 // At most one if clause with the particular directive-name-modifier can
2049 // appear on the directive.
2050 bool MatchFound = false;
2051 for (auto NM : AllowedNameModifiers) {
2052 if (CurNM == NM) {
2053 MatchFound = true;
2054 break;
2055 }
2056 }
2057 if (!MatchFound) {
2058 S.Diag(IC->getNameModifierLoc(),
2059 diag::err_omp_wrong_if_directive_name_modifier)
2060 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2061 ErrorFound = true;
2062 }
2063 }
2064 }
2065 // If any if clause on the directive includes a directive-name-modifier then
2066 // all if clauses on the directive must include a directive-name-modifier.
2067 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2068 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2069 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2070 diag::err_omp_no_more_if_clause);
2071 } else {
2072 std::string Values;
2073 std::string Sep(", ");
2074 unsigned AllowedCnt = 0;
2075 unsigned TotalAllowedNum =
2076 AllowedNameModifiers.size() - NamedModifiersNumber;
2077 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2078 ++Cnt) {
2079 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2080 if (!FoundNameModifiers[NM]) {
2081 Values += "'";
2082 Values += getOpenMPDirectiveName(NM);
2083 Values += "'";
2084 if (AllowedCnt + 2 == TotalAllowedNum)
2085 Values += " or ";
2086 else if (AllowedCnt + 1 != TotalAllowedNum)
2087 Values += Sep;
2088 ++AllowedCnt;
2089 }
2090 }
2091 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2092 diag::err_omp_unnamed_if_clause)
2093 << (TotalAllowedNum > 1) << Values;
2094 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002095 for (auto Loc : NameModifierLoc) {
2096 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2097 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002098 ErrorFound = true;
2099 }
2100 return ErrorFound;
2101}
2102
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002103StmtResult Sema::ActOnOpenMPExecutableDirective(
2104 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2105 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2106 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002107 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002108 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2109 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002110 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002111
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002112 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00002113 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002114 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002115 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002116 if (AStmt) {
2117 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2118
2119 // Check default data sharing attributes for referenced variables.
2120 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2121 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2122 if (DSAChecker.isErrorFound())
2123 return StmtError();
2124 // Generate list of implicitly defined firstprivate variables.
2125 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002126
2127 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2128 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2129 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2130 SourceLocation(), SourceLocation())) {
2131 ClausesWithImplicit.push_back(Implicit);
2132 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2133 DSAChecker.getImplicitFirstprivate().size();
2134 } else
2135 ErrorFound = true;
2136 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002137 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002138
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002139 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002140 switch (Kind) {
2141 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002142 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2143 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002144 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002145 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002146 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002147 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2148 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002149 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002150 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002151 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2152 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002153 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002154 case OMPD_for_simd:
2155 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2156 EndLoc, VarsWithInheritedDSA);
2157 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002158 case OMPD_sections:
2159 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2160 EndLoc);
2161 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002162 case OMPD_section:
2163 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002164 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002165 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2166 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002167 case OMPD_single:
2168 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2169 EndLoc);
2170 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002171 case OMPD_master:
2172 assert(ClausesWithImplicit.empty() &&
2173 "No clauses are allowed for 'omp master' directive");
2174 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2175 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002176 case OMPD_critical:
2177 assert(ClausesWithImplicit.empty() &&
2178 "No clauses are allowed for 'omp critical' directive");
2179 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
2180 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002181 case OMPD_parallel_for:
2182 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2183 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002184 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002185 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002186 case OMPD_parallel_for_simd:
2187 Res = ActOnOpenMPParallelForSimdDirective(
2188 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002189 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002190 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002191 case OMPD_parallel_sections:
2192 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2193 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002194 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002195 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002196 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002197 Res =
2198 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002199 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002200 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002201 case OMPD_taskyield:
2202 assert(ClausesWithImplicit.empty() &&
2203 "No clauses are allowed for 'omp taskyield' directive");
2204 assert(AStmt == nullptr &&
2205 "No associated statement allowed for 'omp taskyield' directive");
2206 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2207 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002208 case OMPD_barrier:
2209 assert(ClausesWithImplicit.empty() &&
2210 "No clauses are allowed for 'omp barrier' directive");
2211 assert(AStmt == nullptr &&
2212 "No associated statement allowed for 'omp barrier' directive");
2213 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2214 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002215 case OMPD_taskwait:
2216 assert(ClausesWithImplicit.empty() &&
2217 "No clauses are allowed for 'omp taskwait' directive");
2218 assert(AStmt == nullptr &&
2219 "No associated statement allowed for 'omp taskwait' directive");
2220 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2221 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002222 case OMPD_taskgroup:
2223 assert(ClausesWithImplicit.empty() &&
2224 "No clauses are allowed for 'omp taskgroup' directive");
2225 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2226 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002227 case OMPD_flush:
2228 assert(AStmt == nullptr &&
2229 "No associated statement allowed for 'omp flush' directive");
2230 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2231 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002232 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002233 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2234 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002235 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002236 case OMPD_atomic:
2237 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2238 EndLoc);
2239 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002240 case OMPD_teams:
2241 Res =
2242 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2243 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002244 case OMPD_target:
2245 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2246 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002247 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002248 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002249 case OMPD_cancellation_point:
2250 assert(ClausesWithImplicit.empty() &&
2251 "No clauses are allowed for 'omp cancellation point' directive");
2252 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2253 "cancellation point' directive");
2254 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2255 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002256 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002257 assert(AStmt == nullptr &&
2258 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002259 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2260 CancelRegion);
2261 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002262 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002263 case OMPD_target_data:
2264 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2265 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002266 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002267 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002268 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002269 llvm_unreachable("OpenMP Directive is not allowed");
2270 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002271 llvm_unreachable("Unknown OpenMP directive");
2272 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002273
Alexey Bataev4acb8592014-07-07 13:01:15 +00002274 for (auto P : VarsWithInheritedDSA) {
2275 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2276 << P.first << P.second->getSourceRange();
2277 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002278 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2279
2280 if (!AllowedNameModifiers.empty())
2281 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2282 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002283
Alexey Bataeved09d242014-05-28 05:53:51 +00002284 if (ErrorFound)
2285 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002286 return Res;
2287}
2288
2289StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2290 Stmt *AStmt,
2291 SourceLocation StartLoc,
2292 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002293 if (!AStmt)
2294 return StmtError();
2295
Alexey Bataev9959db52014-05-06 10:08:46 +00002296 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2297 // 1.2.2 OpenMP Language Terminology
2298 // Structured block - An executable statement with a single entry at the
2299 // top and a single exit at the bottom.
2300 // The point of exit cannot be a branch out of the structured block.
2301 // longjmp() and throw() must not violate the entry/exit criteria.
2302 CS->getCapturedDecl()->setNothrow();
2303
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002304 getCurFunction()->setHasBranchProtectedScope();
2305
Alexey Bataev25e5b442015-09-15 12:52:43 +00002306 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2307 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002308}
2309
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002310namespace {
2311/// \brief Helper class for checking canonical form of the OpenMP loops and
2312/// extracting iteration space of each loop in the loop nest, that will be used
2313/// for IR generation.
2314class OpenMPIterationSpaceChecker {
2315 /// \brief Reference to Sema.
2316 Sema &SemaRef;
2317 /// \brief A location for diagnostics (when there is no some better location).
2318 SourceLocation DefaultLoc;
2319 /// \brief A location for diagnostics (when increment is not compatible).
2320 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002321 /// \brief A source location for referring to loop init later.
2322 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002323 /// \brief A source location for referring to condition later.
2324 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002325 /// \brief A source location for referring to increment later.
2326 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002327 /// \brief Loop variable.
2328 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002329 /// \brief Reference to loop variable.
2330 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002331 /// \brief Lower bound (initializer for the var).
2332 Expr *LB;
2333 /// \brief Upper bound.
2334 Expr *UB;
2335 /// \brief Loop step (increment).
2336 Expr *Step;
2337 /// \brief This flag is true when condition is one of:
2338 /// Var < UB
2339 /// Var <= UB
2340 /// UB > Var
2341 /// UB >= Var
2342 bool TestIsLessOp;
2343 /// \brief This flag is true when condition is strict ( < or > ).
2344 bool TestIsStrictOp;
2345 /// \brief This flag is true when step is subtracted on each iteration.
2346 bool SubtractStep;
2347
2348public:
2349 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2350 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002351 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2352 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002353 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2354 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002355 /// \brief Check init-expr for canonical loop form and save loop counter
2356 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002357 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002358 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2359 /// for less/greater and for strict/non-strict comparison.
2360 bool CheckCond(Expr *S);
2361 /// \brief Check incr-expr for canonical loop form and return true if it
2362 /// does not conform, otherwise save loop step (#Step).
2363 bool CheckInc(Expr *S);
2364 /// \brief Return the loop counter variable.
2365 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002366 /// \brief Return the reference expression to loop counter variable.
2367 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002368 /// \brief Source range of the loop init.
2369 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2370 /// \brief Source range of the loop condition.
2371 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2372 /// \brief Source range of the loop increment.
2373 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2374 /// \brief True if the step should be subtracted.
2375 bool ShouldSubtractStep() const { return SubtractStep; }
2376 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002377 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002378 /// \brief Build the precondition expression for the loops.
2379 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002380 /// \brief Build reference expression to the counter be used for codegen.
2381 Expr *BuildCounterVar() const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002382 /// \brief Build reference expression to the private counter be used for
2383 /// codegen.
2384 Expr *BuildPrivateCounterVar() const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002385 /// \brief Build initization of the counter be used for codegen.
2386 Expr *BuildCounterInit() const;
2387 /// \brief Build step of the counter be used for codegen.
2388 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002389 /// \brief Return true if any expression is dependent.
2390 bool Dependent() const;
2391
2392private:
2393 /// \brief Check the right-hand side of an assignment in the increment
2394 /// expression.
2395 bool CheckIncRHS(Expr *RHS);
2396 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002397 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002398 /// \brief Helper to set upper bound.
2399 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002400 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002401 /// \brief Helper to set loop increment.
2402 bool SetStep(Expr *NewStep, bool Subtract);
2403};
2404
2405bool OpenMPIterationSpaceChecker::Dependent() const {
2406 if (!Var) {
2407 assert(!LB && !UB && !Step);
2408 return false;
2409 }
2410 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2411 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2412}
2413
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002414template <typename T>
2415static T *getExprAsWritten(T *E) {
2416 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2417 E = ExprTemp->getSubExpr();
2418
2419 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2420 E = MTE->GetTemporaryExpr();
2421
2422 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2423 E = Binder->getSubExpr();
2424
2425 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2426 E = ICE->getSubExprAsWritten();
2427 return E->IgnoreParens();
2428}
2429
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002430bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2431 DeclRefExpr *NewVarRefExpr,
2432 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002433 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002434 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2435 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002436 if (!NewVar || !NewLB)
2437 return true;
2438 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002439 VarRef = NewVarRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002440 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2441 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002442 if ((Ctor->isCopyOrMoveConstructor() ||
2443 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2444 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002445 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002446 LB = NewLB;
2447 return false;
2448}
2449
2450bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2451 const SourceRange &SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002452 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002453 // State consistency checking to ensure correct usage.
2454 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2455 !TestIsLessOp && !TestIsStrictOp);
2456 if (!NewUB)
2457 return true;
2458 UB = NewUB;
2459 TestIsLessOp = LessOp;
2460 TestIsStrictOp = StrictOp;
2461 ConditionSrcRange = SR;
2462 ConditionLoc = SL;
2463 return false;
2464}
2465
2466bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2467 // State consistency checking to ensure correct usage.
2468 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2469 if (!NewStep)
2470 return true;
2471 if (!NewStep->isValueDependent()) {
2472 // Check that the step is integer expression.
2473 SourceLocation StepLoc = NewStep->getLocStart();
2474 ExprResult Val =
2475 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2476 if (Val.isInvalid())
2477 return true;
2478 NewStep = Val.get();
2479
2480 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2481 // If test-expr is of form var relational-op b and relational-op is < or
2482 // <= then incr-expr must cause var to increase on each iteration of the
2483 // loop. If test-expr is of form var relational-op b and relational-op is
2484 // > or >= then incr-expr must cause var to decrease on each iteration of
2485 // the loop.
2486 // If test-expr is of form b relational-op var and relational-op is < or
2487 // <= then incr-expr must cause var to decrease on each iteration of the
2488 // loop. If test-expr is of form b relational-op var and relational-op is
2489 // > or >= then incr-expr must cause var to increase on each iteration of
2490 // the loop.
2491 llvm::APSInt Result;
2492 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2493 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2494 bool IsConstNeg =
2495 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002496 bool IsConstPos =
2497 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002498 bool IsConstZero = IsConstant && !Result.getBoolValue();
2499 if (UB && (IsConstZero ||
2500 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002501 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002502 SemaRef.Diag(NewStep->getExprLoc(),
2503 diag::err_omp_loop_incr_not_compatible)
2504 << Var << TestIsLessOp << NewStep->getSourceRange();
2505 SemaRef.Diag(ConditionLoc,
2506 diag::note_omp_loop_cond_requres_compatible_incr)
2507 << TestIsLessOp << ConditionSrcRange;
2508 return true;
2509 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002510 if (TestIsLessOp == Subtract) {
2511 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2512 NewStep).get();
2513 Subtract = !Subtract;
2514 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002515 }
2516
2517 Step = NewStep;
2518 SubtractStep = Subtract;
2519 return false;
2520}
2521
Alexey Bataev9c821032015-04-30 04:23:23 +00002522bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002523 // Check init-expr for canonical loop form and save loop counter
2524 // variable - #Var and its initialization value - #LB.
2525 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2526 // var = lb
2527 // integer-type var = lb
2528 // random-access-iterator-type var = lb
2529 // pointer-type var = lb
2530 //
2531 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002532 if (EmitDiags) {
2533 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2534 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002535 return true;
2536 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002537 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002538 if (Expr *E = dyn_cast<Expr>(S))
2539 S = E->IgnoreParens();
2540 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2541 if (BO->getOpcode() == BO_Assign)
2542 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002543 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002544 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002545 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2546 if (DS->isSingleDecl()) {
2547 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002548 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002549 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002550 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002551 SemaRef.Diag(S->getLocStart(),
2552 diag::ext_omp_loop_not_canonical_init)
2553 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002554 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002555 }
2556 }
2557 }
2558 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2559 if (CE->getOperator() == OO_Equal)
2560 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002561 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2562 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002563
Alexey Bataev9c821032015-04-30 04:23:23 +00002564 if (EmitDiags) {
2565 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2566 << S->getSourceRange();
2567 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002568 return true;
2569}
2570
Alexey Bataev23b69422014-06-18 07:08:49 +00002571/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002572/// variable (which may be the loop variable) if possible.
2573static const VarDecl *GetInitVarDecl(const Expr *E) {
2574 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002575 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002576 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002577 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2578 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002579 if ((Ctor->isCopyOrMoveConstructor() ||
2580 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2581 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002582 E = CE->getArg(0)->IgnoreParenImpCasts();
2583 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2584 if (!DRE)
2585 return nullptr;
2586 return dyn_cast<VarDecl>(DRE->getDecl());
2587}
2588
2589bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2590 // Check test-expr for canonical form, save upper-bound UB, flags for
2591 // less/greater and for strict/non-strict comparison.
2592 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2593 // var relational-op b
2594 // b relational-op var
2595 //
2596 if (!S) {
2597 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2598 return true;
2599 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002600 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002601 SourceLocation CondLoc = S->getLocStart();
2602 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2603 if (BO->isRelationalOp()) {
2604 if (GetInitVarDecl(BO->getLHS()) == Var)
2605 return SetUB(BO->getRHS(),
2606 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2607 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2608 BO->getSourceRange(), BO->getOperatorLoc());
2609 if (GetInitVarDecl(BO->getRHS()) == Var)
2610 return SetUB(BO->getLHS(),
2611 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2612 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2613 BO->getSourceRange(), BO->getOperatorLoc());
2614 }
2615 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2616 if (CE->getNumArgs() == 2) {
2617 auto Op = CE->getOperator();
2618 switch (Op) {
2619 case OO_Greater:
2620 case OO_GreaterEqual:
2621 case OO_Less:
2622 case OO_LessEqual:
2623 if (GetInitVarDecl(CE->getArg(0)) == Var)
2624 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2625 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2626 CE->getOperatorLoc());
2627 if (GetInitVarDecl(CE->getArg(1)) == Var)
2628 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2629 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2630 CE->getOperatorLoc());
2631 break;
2632 default:
2633 break;
2634 }
2635 }
2636 }
2637 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2638 << S->getSourceRange() << Var;
2639 return true;
2640}
2641
2642bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2643 // RHS of canonical loop form increment can be:
2644 // var + incr
2645 // incr + var
2646 // var - incr
2647 //
2648 RHS = RHS->IgnoreParenImpCasts();
2649 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2650 if (BO->isAdditiveOp()) {
2651 bool IsAdd = BO->getOpcode() == BO_Add;
2652 if (GetInitVarDecl(BO->getLHS()) == Var)
2653 return SetStep(BO->getRHS(), !IsAdd);
2654 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2655 return SetStep(BO->getLHS(), false);
2656 }
2657 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2658 bool IsAdd = CE->getOperator() == OO_Plus;
2659 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2660 if (GetInitVarDecl(CE->getArg(0)) == Var)
2661 return SetStep(CE->getArg(1), !IsAdd);
2662 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2663 return SetStep(CE->getArg(0), false);
2664 }
2665 }
2666 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2667 << RHS->getSourceRange() << Var;
2668 return true;
2669}
2670
2671bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2672 // Check incr-expr for canonical loop form and return true if it
2673 // does not conform.
2674 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2675 // ++var
2676 // var++
2677 // --var
2678 // var--
2679 // var += incr
2680 // var -= incr
2681 // var = var + incr
2682 // var = incr + var
2683 // var = var - incr
2684 //
2685 if (!S) {
2686 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2687 return true;
2688 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002689 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002690 S = S->IgnoreParens();
2691 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2692 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2693 return SetStep(
2694 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2695 (UO->isDecrementOp() ? -1 : 1)).get(),
2696 false);
2697 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2698 switch (BO->getOpcode()) {
2699 case BO_AddAssign:
2700 case BO_SubAssign:
2701 if (GetInitVarDecl(BO->getLHS()) == Var)
2702 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2703 break;
2704 case BO_Assign:
2705 if (GetInitVarDecl(BO->getLHS()) == Var)
2706 return CheckIncRHS(BO->getRHS());
2707 break;
2708 default:
2709 break;
2710 }
2711 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2712 switch (CE->getOperator()) {
2713 case OO_PlusPlus:
2714 case OO_MinusMinus:
2715 if (GetInitVarDecl(CE->getArg(0)) == Var)
2716 return SetStep(
2717 SemaRef.ActOnIntegerConstant(
2718 CE->getLocStart(),
2719 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2720 false);
2721 break;
2722 case OO_PlusEqual:
2723 case OO_MinusEqual:
2724 if (GetInitVarDecl(CE->getArg(0)) == Var)
2725 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2726 break;
2727 case OO_Equal:
2728 if (GetInitVarDecl(CE->getArg(0)) == Var)
2729 return CheckIncRHS(CE->getArg(1));
2730 break;
2731 default:
2732 break;
2733 }
2734 }
2735 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2736 << S->getSourceRange() << Var;
2737 return true;
2738}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002739
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002740namespace {
2741// Transform variables declared in GNU statement expressions to new ones to
2742// avoid crash on codegen.
2743class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
2744 typedef TreeTransform<TransformToNewDefs> BaseTransform;
2745
2746public:
2747 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
2748
2749 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
2750 if (auto *VD = cast<VarDecl>(D))
2751 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
2752 !isa<ImplicitParamDecl>(D)) {
2753 auto *NewVD = VarDecl::Create(
2754 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
2755 VD->getLocation(), VD->getIdentifier(), VD->getType(),
2756 VD->getTypeSourceInfo(), VD->getStorageClass());
2757 NewVD->setTSCSpec(VD->getTSCSpec());
2758 NewVD->setInit(VD->getInit());
2759 NewVD->setInitStyle(VD->getInitStyle());
2760 NewVD->setExceptionVariable(VD->isExceptionVariable());
2761 NewVD->setNRVOVariable(VD->isNRVOVariable());
2762 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
2763 NewVD->setConstexpr(VD->isConstexpr());
2764 NewVD->setInitCapture(VD->isInitCapture());
2765 NewVD->setPreviousDeclInSameBlockScope(
2766 VD->isPreviousDeclInSameBlockScope());
2767 VD->getDeclContext()->addHiddenDecl(NewVD);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002768 if (VD->hasAttrs())
2769 NewVD->setAttrs(VD->getAttrs());
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002770 transformedLocalDecl(VD, NewVD);
2771 return NewVD;
2772 }
2773 return BaseTransform::TransformDefinition(Loc, D);
2774 }
2775
2776 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
2777 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
2778 if (E->getDecl() != NewD) {
2779 NewD->setReferenced();
2780 NewD->markUsed(SemaRef.Context);
2781 return DeclRefExpr::Create(
2782 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
2783 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
2784 E->getNameInfo(), E->getType(), E->getValueKind());
2785 }
2786 return BaseTransform::TransformDeclRefExpr(E);
2787 }
2788};
2789}
2790
Alexander Musmana5f070a2014-10-01 06:03:56 +00002791/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002792Expr *
2793OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2794 const bool LimitedType) const {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002795 TransformToNewDefs Transform(SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002796 ExprResult Diff;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002797 auto VarType = Var->getType().getNonReferenceType();
2798 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002799 SemaRef.getLangOpts().CPlusPlus) {
2800 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002801 auto *UBExpr = TestIsLessOp ? UB : LB;
2802 auto *LBExpr = TestIsLessOp ? LB : UB;
2803 Expr *Upper = Transform.TransformExpr(UBExpr).get();
2804 Expr *Lower = Transform.TransformExpr(LBExpr).get();
2805 if (!Upper || !Lower)
2806 return nullptr;
2807 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
2808 Sema::AA_Converting,
2809 /*AllowExplicit=*/true)
2810 .get();
2811 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
2812 Sema::AA_Converting,
2813 /*AllowExplicit=*/true)
2814 .get();
2815 if (!Upper || !Lower)
2816 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002817
2818 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2819
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002820 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002821 // BuildBinOp already emitted error, this one is to point user to upper
2822 // and lower bound, and to tell what is passed to 'operator-'.
2823 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2824 << Upper->getSourceRange() << Lower->getSourceRange();
2825 return nullptr;
2826 }
2827 }
2828
2829 if (!Diff.isUsable())
2830 return nullptr;
2831
2832 // Upper - Lower [- 1]
2833 if (TestIsStrictOp)
2834 Diff = SemaRef.BuildBinOp(
2835 S, DefaultLoc, BO_Sub, Diff.get(),
2836 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2837 if (!Diff.isUsable())
2838 return nullptr;
2839
2840 // Upper - Lower [- 1] + Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002841 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2842 if (NewStep.isInvalid())
2843 return nullptr;
2844 NewStep = SemaRef.PerformImplicitConversion(
2845 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2846 /*AllowExplicit=*/true);
2847 if (NewStep.isInvalid())
2848 return nullptr;
2849 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002850 if (!Diff.isUsable())
2851 return nullptr;
2852
2853 // Parentheses (for dumping/debugging purposes only).
2854 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2855 if (!Diff.isUsable())
2856 return nullptr;
2857
2858 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002859 NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2860 if (NewStep.isInvalid())
2861 return nullptr;
2862 NewStep = SemaRef.PerformImplicitConversion(
2863 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2864 /*AllowExplicit=*/true);
2865 if (NewStep.isInvalid())
2866 return nullptr;
2867 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002868 if (!Diff.isUsable())
2869 return nullptr;
2870
Alexander Musman174b3ca2014-10-06 11:16:29 +00002871 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002872 QualType Type = Diff.get()->getType();
2873 auto &C = SemaRef.Context;
2874 bool UseVarType = VarType->hasIntegerRepresentation() &&
2875 C.getTypeSize(Type) > C.getTypeSize(VarType);
2876 if (!Type->isIntegerType() || UseVarType) {
2877 unsigned NewSize =
2878 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
2879 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
2880 : Type->hasSignedIntegerRepresentation();
2881 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
2882 Diff = SemaRef.PerformImplicitConversion(
2883 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
2884 if (!Diff.isUsable())
2885 return nullptr;
2886 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00002887 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00002888 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2889 if (NewSize != C.getTypeSize(Type)) {
2890 if (NewSize < C.getTypeSize(Type)) {
2891 assert(NewSize == 64 && "incorrect loop var size");
2892 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2893 << InitSrcRange << ConditionSrcRange;
2894 }
2895 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002896 NewSize, Type->hasSignedIntegerRepresentation() ||
2897 C.getTypeSize(Type) < NewSize);
Alexander Musman174b3ca2014-10-06 11:16:29 +00002898 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2899 Sema::AA_Converting, true);
2900 if (!Diff.isUsable())
2901 return nullptr;
2902 }
2903 }
2904
Alexander Musmana5f070a2014-10-01 06:03:56 +00002905 return Diff.get();
2906}
2907
Alexey Bataev62dbb972015-04-22 11:59:37 +00002908Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2909 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2910 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2911 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002912 TransformToNewDefs Transform(SemaRef);
2913
2914 auto NewLB = Transform.TransformExpr(LB);
2915 auto NewUB = Transform.TransformExpr(UB);
2916 if (NewLB.isInvalid() || NewUB.isInvalid())
2917 return Cond;
2918 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
2919 Sema::AA_Converting,
2920 /*AllowExplicit=*/true);
2921 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
2922 Sema::AA_Converting,
2923 /*AllowExplicit=*/true);
2924 if (NewLB.isInvalid() || NewUB.isInvalid())
2925 return Cond;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002926 auto CondExpr = SemaRef.BuildBinOp(
2927 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2928 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002929 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002930 if (CondExpr.isUsable()) {
2931 CondExpr = SemaRef.PerformImplicitConversion(
2932 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
2933 /*AllowExplicit=*/true);
2934 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00002935 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2936 // Otherwise use original loop conditon and evaluate it in runtime.
2937 return CondExpr.isUsable() ? CondExpr.get() : Cond;
2938}
2939
Alexander Musmana5f070a2014-10-01 06:03:56 +00002940/// \brief Build reference expression to the counter be used for codegen.
2941Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataeva8899172015-08-06 12:30:57 +00002942 return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
2943 DefaultLoc);
2944}
2945
2946Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
2947 if (Var && !Var->isInvalidDecl()) {
2948 auto Type = Var->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002949 auto *PrivateVar =
2950 buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
2951 Var->hasAttrs() ? &Var->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00002952 if (PrivateVar->isInvalidDecl())
2953 return nullptr;
2954 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
2955 }
2956 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002957}
2958
2959/// \brief Build initization of the counter be used for codegen.
2960Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2961
2962/// \brief Build step of the counter be used for codegen.
2963Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2964
2965/// \brief Iteration space of a single for loop.
2966struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00002967 /// \brief Condition of the loop.
2968 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002969 /// \brief This expression calculates the number of iterations in the loop.
2970 /// It is always possible to calculate it before starting the loop.
2971 Expr *NumIterations;
2972 /// \brief The loop counter variable.
2973 Expr *CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00002974 /// \brief Private loop counter variable.
2975 Expr *PrivateCounterVar;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002976 /// \brief This is initializer for the initial value of #CounterVar.
2977 Expr *CounterInit;
2978 /// \brief This is step for the #CounterVar used to generate its update:
2979 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2980 Expr *CounterStep;
2981 /// \brief Should step be subtracted?
2982 bool Subtract;
2983 /// \brief Source range of the loop init.
2984 SourceRange InitSrcRange;
2985 /// \brief Source range of the loop condition.
2986 SourceRange CondSrcRange;
2987 /// \brief Source range of the loop increment.
2988 SourceRange IncSrcRange;
2989};
2990
Alexey Bataev23b69422014-06-18 07:08:49 +00002991} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002992
Alexey Bataev9c821032015-04-30 04:23:23 +00002993void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2994 assert(getLangOpts().OpenMP && "OpenMP is not active.");
2995 assert(Init && "Expected loop in canonical form.");
2996 unsigned CollapseIteration = DSAStack->getCollapseNumber();
2997 if (CollapseIteration > 0 &&
2998 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2999 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3000 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3001 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3002 }
3003 DSAStack->setCollapseNumber(CollapseIteration - 1);
3004 }
3005}
3006
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003007/// \brief Called on a for stmt to check and extract its iteration space
3008/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003009static bool CheckOpenMPIterationSpace(
3010 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3011 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003012 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003013 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3014 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003015 // OpenMP [2.6, Canonical Loop Form]
3016 // for (init-expr; test-expr; incr-expr) structured-block
3017 auto For = dyn_cast_or_null<ForStmt>(S);
3018 if (!For) {
3019 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003020 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3021 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3022 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3023 if (NestedLoopCount > 1) {
3024 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3025 SemaRef.Diag(DSA.getConstructLoc(),
3026 diag::note_omp_collapse_ordered_expr)
3027 << 2 << CollapseLoopCountExpr->getSourceRange()
3028 << OrderedLoopCountExpr->getSourceRange();
3029 else if (CollapseLoopCountExpr)
3030 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3031 diag::note_omp_collapse_ordered_expr)
3032 << 0 << CollapseLoopCountExpr->getSourceRange();
3033 else
3034 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3035 diag::note_omp_collapse_ordered_expr)
3036 << 1 << OrderedLoopCountExpr->getSourceRange();
3037 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003038 return true;
3039 }
3040 assert(For->getBody());
3041
3042 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3043
3044 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003045 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003046 if (ISC.CheckInit(Init)) {
3047 return true;
3048 }
3049
3050 bool HasErrors = false;
3051
3052 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003053 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003054
3055 // OpenMP [2.6, Canonical Loop Form]
3056 // Var is one of the following:
3057 // A variable of signed or unsigned integer type.
3058 // For C++, a variable of a random access iterator type.
3059 // For C, a variable of a pointer type.
Alexey Bataeva8899172015-08-06 12:30:57 +00003060 auto VarType = Var->getType().getNonReferenceType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003061 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3062 !VarType->isPointerType() &&
3063 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3064 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3065 << SemaRef.getLangOpts().CPlusPlus;
3066 HasErrors = true;
3067 }
3068
Alexey Bataev4acb8592014-07-07 13:01:15 +00003069 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3070 // Construct
3071 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3072 // parallel for construct is (are) private.
3073 // The loop iteration variable in the associated for-loop of a simd construct
3074 // with just one associated for-loop is linear with a constant-linear-step
3075 // that is the increment of the associated for-loop.
3076 // Exclude loop var from the list of variables with implicitly defined data
3077 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00003078 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003079
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003080 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3081 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00003082 // The loop iteration variable in the associated for-loop of a simd construct
3083 // with just one associated for-loop may be listed in a linear clause with a
3084 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00003085 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3086 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003087 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003088 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3089 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3090 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003091 auto PredeterminedCKind =
3092 isOpenMPSimdDirective(DKind)
3093 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3094 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003095 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003096 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00003097 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
3098 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003099 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
3100 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
3101 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003102 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00003103 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3104 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00003105 if (DVar.RefExpr == nullptr)
3106 DVar.CKind = PredeterminedCKind;
3107 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003108 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003109 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003110 // Make the loop iteration variable private (for worksharing constructs),
3111 // linear (for simd directives with the only one associated loop) or
Alexey Bataev10e775f2015-07-30 11:36:16 +00003112 // lastprivate (for simd directives with several collapsed or ordered
3113 // loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00003114 if (DVar.CKind == OMPC_unknown)
3115 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
3116 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00003117 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003118 }
3119
Alexey Bataev7ff55242014-06-19 09:13:45 +00003120 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00003121
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003122 // Check test-expr.
3123 HasErrors |= ISC.CheckCond(For->getCond());
3124
3125 // Check incr-expr.
3126 HasErrors |= ISC.CheckInc(For->getInc());
3127
Alexander Musmana5f070a2014-10-01 06:03:56 +00003128 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129 return HasErrors;
3130
Alexander Musmana5f070a2014-10-01 06:03:56 +00003131 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003132 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00003133 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3134 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00003135 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
Alexey Bataeva8899172015-08-06 12:30:57 +00003136 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003137 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3138 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3139 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3140 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3141 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3142 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3143
Alexey Bataev62dbb972015-04-22 11:59:37 +00003144 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3145 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003146 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003147 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003148 ResultIterSpace.CounterInit == nullptr ||
3149 ResultIterSpace.CounterStep == nullptr);
3150
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003151 return HasErrors;
3152}
3153
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003154/// \brief Build 'VarRef = Start.
3155static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
3156 ExprResult VarRef, ExprResult Start) {
3157 TransformToNewDefs Transform(SemaRef);
3158 // Build 'VarRef = Start.
3159 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3160 if (NewStart.isInvalid())
3161 return ExprError();
3162 NewStart = SemaRef.PerformImplicitConversion(
3163 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3164 Sema::AA_Converting,
3165 /*AllowExplicit=*/true);
3166 if (NewStart.isInvalid())
3167 return ExprError();
3168 NewStart = SemaRef.PerformImplicitConversion(
3169 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3170 /*AllowExplicit=*/true);
3171 if (!NewStart.isUsable())
3172 return ExprError();
3173
3174 auto Init =
3175 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3176 return Init;
3177}
3178
Alexander Musmana5f070a2014-10-01 06:03:56 +00003179/// \brief Build 'VarRef = Start + Iter * Step'.
3180static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3181 SourceLocation Loc, ExprResult VarRef,
3182 ExprResult Start, ExprResult Iter,
3183 ExprResult Step, bool Subtract) {
3184 // Add parentheses (for debugging purposes only).
3185 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3186 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3187 !Step.isUsable())
3188 return ExprError();
3189
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003190 TransformToNewDefs Transform(SemaRef);
3191 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3192 if (NewStep.isInvalid())
3193 return ExprError();
3194 NewStep = SemaRef.PerformImplicitConversion(
3195 NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3196 Sema::AA_Converting,
3197 /*AllowExplicit=*/true);
3198 if (NewStep.isInvalid())
3199 return ExprError();
3200 ExprResult Update =
3201 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003202 if (!Update.isUsable())
3203 return ExprError();
3204
3205 // Build 'VarRef = Start + Iter * Step'.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003206 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3207 if (NewStart.isInvalid())
3208 return ExprError();
3209 NewStart = SemaRef.PerformImplicitConversion(
3210 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3211 Sema::AA_Converting,
3212 /*AllowExplicit=*/true);
3213 if (NewStart.isInvalid())
3214 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003215 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003216 NewStart.get(), Update.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003217 if (!Update.isUsable())
3218 return ExprError();
3219
3220 Update = SemaRef.PerformImplicitConversion(
3221 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3222 if (!Update.isUsable())
3223 return ExprError();
3224
3225 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3226 return Update;
3227}
3228
3229/// \brief Convert integer expression \a E to make it have at least \a Bits
3230/// bits.
3231static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3232 Sema &SemaRef) {
3233 if (E == nullptr)
3234 return ExprError();
3235 auto &C = SemaRef.Context;
3236 QualType OldType = E->getType();
3237 unsigned HasBits = C.getTypeSize(OldType);
3238 if (HasBits >= Bits)
3239 return ExprResult(E);
3240 // OK to convert to signed, because new type has more bits than old.
3241 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3242 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3243 true);
3244}
3245
3246/// \brief Check if the given expression \a E is a constant integer that fits
3247/// into \a Bits bits.
3248static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3249 if (E == nullptr)
3250 return false;
3251 llvm::APSInt Result;
3252 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3253 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3254 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003255}
3256
3257/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003258/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3259/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003260static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003261CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3262 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3263 DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003264 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003265 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003266 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003267 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003268 // Found 'collapse' clause - calculate collapse number.
3269 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003270 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3271 NestedLoopCount += Result.getLimitedValue() - 1;
3272 }
3273 if (OrderedLoopCountExpr) {
3274 // Found 'ordered' clause - calculate collapse number.
3275 llvm::APSInt Result;
3276 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3277 NestedLoopCount += Result.getLimitedValue() - 1;
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003278 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003279 // This is helper routine for loop directives (e.g., 'for', 'simd',
3280 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00003281 SmallVector<LoopIterationSpace, 4> IterSpaces;
3282 IterSpaces.resize(NestedLoopCount);
3283 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003284 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003285 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003286 NestedLoopCount, CollapseLoopCountExpr,
3287 OrderedLoopCountExpr, VarsWithImplicitDSA,
3288 IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003289 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003290 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003291 // OpenMP [2.8.1, simd construct, Restrictions]
3292 // All loops associated with the construct must be perfectly nested; that
3293 // is, there must be no intervening code nor any OpenMP directive between
3294 // any two loops.
3295 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003296 }
3297
Alexander Musmana5f070a2014-10-01 06:03:56 +00003298 Built.clear(/* size */ NestedLoopCount);
3299
3300 if (SemaRef.CurContext->isDependentContext())
3301 return NestedLoopCount;
3302
3303 // An example of what is generated for the following code:
3304 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003305 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003306 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003307 // for (k = 0; k < NK; ++k)
3308 // for (j = J0; j < NJ; j+=2) {
3309 // <loop body>
3310 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003311 //
3312 // We generate the code below.
3313 // Note: the loop body may be outlined in CodeGen.
3314 // Note: some counters may be C++ classes, operator- is used to find number of
3315 // iterations and operator+= to calculate counter value.
3316 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3317 // or i64 is currently supported).
3318 //
3319 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3320 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3321 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3322 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3323 // // similar updates for vars in clauses (e.g. 'linear')
3324 // <loop body (using local i and j)>
3325 // }
3326 // i = NI; // assign final values of counters
3327 // j = NJ;
3328 //
3329
3330 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3331 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003332 // Precondition tests if there is at least one iteration (all conditions are
3333 // true).
3334 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003335 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003336 ExprResult LastIteration32 = WidenIterationCount(
3337 32 /* Bits */, SemaRef.PerformImplicitConversion(
3338 N0->IgnoreImpCasts(), N0->getType(),
3339 Sema::AA_Converting, /*AllowExplicit=*/true)
3340 .get(),
3341 SemaRef);
3342 ExprResult LastIteration64 = WidenIterationCount(
3343 64 /* Bits */, SemaRef.PerformImplicitConversion(
3344 N0->IgnoreImpCasts(), N0->getType(),
3345 Sema::AA_Converting, /*AllowExplicit=*/true)
3346 .get(),
3347 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003348
3349 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3350 return NestedLoopCount;
3351
3352 auto &C = SemaRef.Context;
3353 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3354
3355 Scope *CurScope = DSA.getCurScope();
3356 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003357 if (PreCond.isUsable()) {
3358 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3359 PreCond.get(), IterSpaces[Cnt].PreCond);
3360 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003361 auto N = IterSpaces[Cnt].NumIterations;
3362 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3363 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003364 LastIteration32 = SemaRef.BuildBinOp(
3365 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3366 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3367 Sema::AA_Converting,
3368 /*AllowExplicit=*/true)
3369 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003370 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003371 LastIteration64 = SemaRef.BuildBinOp(
3372 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3373 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3374 Sema::AA_Converting,
3375 /*AllowExplicit=*/true)
3376 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003377 }
3378
3379 // Choose either the 32-bit or 64-bit version.
3380 ExprResult LastIteration = LastIteration64;
3381 if (LastIteration32.isUsable() &&
3382 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3383 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3384 FitsInto(
3385 32 /* Bits */,
3386 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3387 LastIteration64.get(), SemaRef)))
3388 LastIteration = LastIteration32;
3389
3390 if (!LastIteration.isUsable())
3391 return 0;
3392
3393 // Save the number of iterations.
3394 ExprResult NumIterations = LastIteration;
3395 {
3396 LastIteration = SemaRef.BuildBinOp(
3397 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3398 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3399 if (!LastIteration.isUsable())
3400 return 0;
3401 }
3402
3403 // Calculate the last iteration number beforehand instead of doing this on
3404 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3405 llvm::APSInt Result;
3406 bool IsConstant =
3407 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3408 ExprResult CalcLastIteration;
3409 if (!IsConstant) {
3410 SourceLocation SaveLoc;
3411 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003412 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003413 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00003414 ExprResult SaveRef = buildDeclRefExpr(
3415 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003416 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3417 SaveRef.get(), LastIteration.get());
3418 LastIteration = SaveRef;
3419
3420 // Prepare SaveRef + 1.
3421 NumIterations = SemaRef.BuildBinOp(
3422 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3423 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3424 if (!NumIterations.isUsable())
3425 return 0;
3426 }
3427
3428 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3429
Alexander Musmanc6388682014-12-15 07:07:06 +00003430 QualType VType = LastIteration.get()->getType();
3431 // Build variables passed into runtime, nesessary for worksharing directives.
3432 ExprResult LB, UB, IL, ST, EUB;
3433 if (isOpenMPWorksharingDirective(DKind)) {
3434 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003435 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3436 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003437 SemaRef.AddInitializerToDecl(
3438 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3439 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3440
3441 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003442 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3443 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003444 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3445 /*DirectInit*/ false,
3446 /*TypeMayContainAuto*/ false);
3447
3448 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3449 // This will be used to implement clause 'lastprivate'.
3450 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003451 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3452 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003453 SemaRef.AddInitializerToDecl(
3454 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3455 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3456
3457 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00003458 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3459 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003460 SemaRef.AddInitializerToDecl(
3461 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3462 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3463
3464 // Build expression: UB = min(UB, LastIteration)
3465 // It is nesessary for CodeGen of directives with static scheduling.
3466 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3467 UB.get(), LastIteration.get());
3468 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3469 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3470 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3471 CondOp.get());
3472 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3473 }
3474
3475 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003476 ExprResult IV;
3477 ExprResult Init;
3478 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00003479 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3480 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003481 Expr *RHS = isOpenMPWorksharingDirective(DKind)
3482 ? LB.get()
3483 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3484 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3485 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003486 }
3487
Alexander Musmanc6388682014-12-15 07:07:06 +00003488 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003489 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00003490 ExprResult Cond =
3491 isOpenMPWorksharingDirective(DKind)
3492 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3493 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3494 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003495
3496 // Loop increment (IV = IV + 1)
3497 SourceLocation IncLoc;
3498 ExprResult Inc =
3499 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3500 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3501 if (!Inc.isUsable())
3502 return 0;
3503 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00003504 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3505 if (!Inc.isUsable())
3506 return 0;
3507
3508 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3509 // Used for directives with static scheduling.
3510 ExprResult NextLB, NextUB;
3511 if (isOpenMPWorksharingDirective(DKind)) {
3512 // LB + ST
3513 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3514 if (!NextLB.isUsable())
3515 return 0;
3516 // LB = LB + ST
3517 NextLB =
3518 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3519 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3520 if (!NextLB.isUsable())
3521 return 0;
3522 // UB + ST
3523 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3524 if (!NextUB.isUsable())
3525 return 0;
3526 // UB = UB + ST
3527 NextUB =
3528 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3529 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3530 if (!NextUB.isUsable())
3531 return 0;
3532 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003533
3534 // Build updates and final values of the loop counters.
3535 bool HasErrors = false;
3536 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003537 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003538 Built.Updates.resize(NestedLoopCount);
3539 Built.Finals.resize(NestedLoopCount);
3540 {
3541 ExprResult Div;
3542 // Go from inner nested loop to outer.
3543 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3544 LoopIterationSpace &IS = IterSpaces[Cnt];
3545 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3546 // Build: Iter = (IV / Div) % IS.NumIters
3547 // where Div is product of previous iterations' IS.NumIters.
3548 ExprResult Iter;
3549 if (Div.isUsable()) {
3550 Iter =
3551 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3552 } else {
3553 Iter = IV;
3554 assert((Cnt == (int)NestedLoopCount - 1) &&
3555 "unusable div expected on first iteration only");
3556 }
3557
3558 if (Cnt != 0 && Iter.isUsable())
3559 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3560 IS.NumIterations);
3561 if (!Iter.isUsable()) {
3562 HasErrors = true;
3563 break;
3564 }
3565
Alexey Bataev39f915b82015-05-08 10:41:21 +00003566 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3567 auto *CounterVar = buildDeclRefExpr(
3568 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3569 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3570 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003571 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
3572 IS.CounterInit);
3573 if (!Init.isUsable()) {
3574 HasErrors = true;
3575 break;
3576 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003577 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003578 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003579 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3580 if (!Update.isUsable()) {
3581 HasErrors = true;
3582 break;
3583 }
3584
3585 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3586 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003587 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003588 IS.NumIterations, IS.CounterStep, IS.Subtract);
3589 if (!Final.isUsable()) {
3590 HasErrors = true;
3591 break;
3592 }
3593
3594 // Build Div for the next iteration: Div <- Div * IS.NumIters
3595 if (Cnt != 0) {
3596 if (Div.isUnset())
3597 Div = IS.NumIterations;
3598 else
3599 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3600 IS.NumIterations);
3601
3602 // Add parentheses (for debugging purposes only).
3603 if (Div.isUsable())
3604 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3605 if (!Div.isUsable()) {
3606 HasErrors = true;
3607 break;
3608 }
3609 }
3610 if (!Update.isUsable() || !Final.isUsable()) {
3611 HasErrors = true;
3612 break;
3613 }
3614 // Save results
3615 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00003616 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003617 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003618 Built.Updates[Cnt] = Update.get();
3619 Built.Finals[Cnt] = Final.get();
3620 }
3621 }
3622
3623 if (HasErrors)
3624 return 0;
3625
3626 // Save results
3627 Built.IterationVarRef = IV.get();
3628 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003629 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003630 Built.CalcLastIteration =
3631 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003632 Built.PreCond = PreCond.get();
3633 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003634 Built.Init = Init.get();
3635 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003636 Built.LB = LB.get();
3637 Built.UB = UB.get();
3638 Built.IL = IL.get();
3639 Built.ST = ST.get();
3640 Built.EUB = EUB.get();
3641 Built.NLB = NextLB.get();
3642 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003643
Alexey Bataevabfc0692014-06-25 06:52:00 +00003644 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003645}
3646
Alexey Bataev10e775f2015-07-30 11:36:16 +00003647static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003648 auto CollapseClauses =
3649 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
3650 if (CollapseClauses.begin() != CollapseClauses.end())
3651 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003652 return nullptr;
3653}
3654
Alexey Bataev10e775f2015-07-30 11:36:16 +00003655static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003656 auto OrderedClauses =
3657 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
3658 if (OrderedClauses.begin() != OrderedClauses.end())
3659 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003660 return nullptr;
3661}
3662
Alexey Bataev66b15b52015-08-21 11:14:16 +00003663static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
3664 const Expr *Safelen) {
3665 llvm::APSInt SimdlenRes, SafelenRes;
3666 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
3667 Simdlen->isInstantiationDependent() ||
3668 Simdlen->containsUnexpandedParameterPack())
3669 return false;
3670 if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
3671 Safelen->isInstantiationDependent() ||
3672 Safelen->containsUnexpandedParameterPack())
3673 return false;
3674 Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
3675 Safelen->EvaluateAsInt(SafelenRes, S.Context);
3676 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3677 // If both simdlen and safelen clauses are specified, the value of the simdlen
3678 // parameter must be less than or equal to the value of the safelen parameter.
3679 if (SimdlenRes > SafelenRes) {
3680 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
3681 << Simdlen->getSourceRange() << Safelen->getSourceRange();
3682 return true;
3683 }
3684 return false;
3685}
3686
Alexey Bataev4acb8592014-07-07 13:01:15 +00003687StmtResult Sema::ActOnOpenMPSimdDirective(
3688 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3689 SourceLocation EndLoc,
3690 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003691 if (!AStmt)
3692 return StmtError();
3693
3694 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003695 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003696 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3697 // define the nested loops number.
3698 unsigned NestedLoopCount = CheckOpenMPLoop(
3699 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3700 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003701 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003702 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003703
Alexander Musmana5f070a2014-10-01 06:03:56 +00003704 assert((CurContext->isDependentContext() || B.builtAll()) &&
3705 "omp simd loop exprs were not built");
3706
Alexander Musman3276a272015-03-21 10:12:56 +00003707 if (!CurContext->isDependentContext()) {
3708 // Finalize the clauses that need pre-built expressions for CodeGen.
3709 for (auto C : Clauses) {
3710 if (auto LC = dyn_cast<OMPLinearClause>(C))
3711 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3712 B.NumIterations, *this, CurScope))
3713 return StmtError();
3714 }
3715 }
3716
Alexey Bataev66b15b52015-08-21 11:14:16 +00003717 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3718 // If both simdlen and safelen clauses are specified, the value of the simdlen
3719 // parameter must be less than or equal to the value of the safelen parameter.
3720 OMPSafelenClause *Safelen = nullptr;
3721 OMPSimdlenClause *Simdlen = nullptr;
3722 for (auto *Clause : Clauses) {
3723 if (Clause->getClauseKind() == OMPC_safelen)
3724 Safelen = cast<OMPSafelenClause>(Clause);
3725 else if (Clause->getClauseKind() == OMPC_simdlen)
3726 Simdlen = cast<OMPSimdlenClause>(Clause);
3727 if (Safelen && Simdlen)
3728 break;
3729 }
3730 if (Simdlen && Safelen &&
3731 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3732 Safelen->getSafelen()))
3733 return StmtError();
3734
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003735 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003736 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3737 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003738}
3739
Alexey Bataev4acb8592014-07-07 13:01:15 +00003740StmtResult Sema::ActOnOpenMPForDirective(
3741 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3742 SourceLocation EndLoc,
3743 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003744 if (!AStmt)
3745 return StmtError();
3746
3747 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003748 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003749 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3750 // define the nested loops number.
3751 unsigned NestedLoopCount = CheckOpenMPLoop(
3752 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3753 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003754 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003755 return StmtError();
3756
Alexander Musmana5f070a2014-10-01 06:03:56 +00003757 assert((CurContext->isDependentContext() || B.builtAll()) &&
3758 "omp for loop exprs were not built");
3759
Alexey Bataev54acd402015-08-04 11:18:19 +00003760 if (!CurContext->isDependentContext()) {
3761 // Finalize the clauses that need pre-built expressions for CodeGen.
3762 for (auto C : Clauses) {
3763 if (auto LC = dyn_cast<OMPLinearClause>(C))
3764 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3765 B.NumIterations, *this, CurScope))
3766 return StmtError();
3767 }
3768 }
3769
Alexey Bataevf29276e2014-06-18 04:14:57 +00003770 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003771 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003772 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00003773}
3774
Alexander Musmanf82886e2014-09-18 05:12:34 +00003775StmtResult Sema::ActOnOpenMPForSimdDirective(
3776 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3777 SourceLocation EndLoc,
3778 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003779 if (!AStmt)
3780 return StmtError();
3781
3782 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003783 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003784 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3785 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00003786 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00003787 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
3788 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
3789 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003790 if (NestedLoopCount == 0)
3791 return StmtError();
3792
Alexander Musmanc6388682014-12-15 07:07:06 +00003793 assert((CurContext->isDependentContext() || B.builtAll()) &&
3794 "omp for simd loop exprs were not built");
3795
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00003796 if (!CurContext->isDependentContext()) {
3797 // Finalize the clauses that need pre-built expressions for CodeGen.
3798 for (auto C : Clauses) {
3799 if (auto LC = dyn_cast<OMPLinearClause>(C))
3800 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3801 B.NumIterations, *this, CurScope))
3802 return StmtError();
3803 }
3804 }
3805
Alexey Bataev66b15b52015-08-21 11:14:16 +00003806 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3807 // If both simdlen and safelen clauses are specified, the value of the simdlen
3808 // parameter must be less than or equal to the value of the safelen parameter.
3809 OMPSafelenClause *Safelen = nullptr;
3810 OMPSimdlenClause *Simdlen = nullptr;
3811 for (auto *Clause : Clauses) {
3812 if (Clause->getClauseKind() == OMPC_safelen)
3813 Safelen = cast<OMPSafelenClause>(Clause);
3814 else if (Clause->getClauseKind() == OMPC_simdlen)
3815 Simdlen = cast<OMPSimdlenClause>(Clause);
3816 if (Safelen && Simdlen)
3817 break;
3818 }
3819 if (Simdlen && Safelen &&
3820 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3821 Safelen->getSafelen()))
3822 return StmtError();
3823
Alexander Musmanf82886e2014-09-18 05:12:34 +00003824 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003825 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3826 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003827}
3828
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003829StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3830 Stmt *AStmt,
3831 SourceLocation StartLoc,
3832 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003833 if (!AStmt)
3834 return StmtError();
3835
3836 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003837 auto BaseStmt = AStmt;
3838 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3839 BaseStmt = CS->getCapturedStmt();
3840 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3841 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00003842 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003843 return StmtError();
3844 // All associated statements must be '#pragma omp section' except for
3845 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003846 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003847 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3848 if (SectionStmt)
3849 Diag(SectionStmt->getLocStart(),
3850 diag::err_omp_sections_substmt_not_section);
3851 return StmtError();
3852 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00003853 cast<OMPSectionDirective>(SectionStmt)
3854 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003855 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003856 } else {
3857 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3858 return StmtError();
3859 }
3860
3861 getCurFunction()->setHasBranchProtectedScope();
3862
Alexey Bataev25e5b442015-09-15 12:52:43 +00003863 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3864 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003865}
3866
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003867StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3868 SourceLocation StartLoc,
3869 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003870 if (!AStmt)
3871 return StmtError();
3872
3873 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003874
3875 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00003876 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003877
Alexey Bataev25e5b442015-09-15 12:52:43 +00003878 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
3879 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003880}
3881
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003882StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3883 Stmt *AStmt,
3884 SourceLocation StartLoc,
3885 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003886 if (!AStmt)
3887 return StmtError();
3888
3889 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00003890
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003891 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003892
Alexey Bataev3255bf32015-01-19 05:20:46 +00003893 // OpenMP [2.7.3, single Construct, Restrictions]
3894 // The copyprivate clause must not be used with the nowait clause.
3895 OMPClause *Nowait = nullptr;
3896 OMPClause *Copyprivate = nullptr;
3897 for (auto *Clause : Clauses) {
3898 if (Clause->getClauseKind() == OMPC_nowait)
3899 Nowait = Clause;
3900 else if (Clause->getClauseKind() == OMPC_copyprivate)
3901 Copyprivate = Clause;
3902 if (Copyprivate && Nowait) {
3903 Diag(Copyprivate->getLocStart(),
3904 diag::err_omp_single_copyprivate_with_nowait);
3905 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3906 return StmtError();
3907 }
3908 }
3909
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003910 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3911}
3912
Alexander Musman80c22892014-07-17 08:54:58 +00003913StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3914 SourceLocation StartLoc,
3915 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003916 if (!AStmt)
3917 return StmtError();
3918
3919 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00003920
3921 getCurFunction()->setHasBranchProtectedScope();
3922
3923 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3924}
3925
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003926StmtResult
3927Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3928 Stmt *AStmt, SourceLocation StartLoc,
3929 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003930 if (!AStmt)
3931 return StmtError();
3932
3933 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003934
3935 getCurFunction()->setHasBranchProtectedScope();
3936
3937 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3938 AStmt);
3939}
3940
Alexey Bataev4acb8592014-07-07 13:01:15 +00003941StmtResult Sema::ActOnOpenMPParallelForDirective(
3942 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3943 SourceLocation EndLoc,
3944 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003945 if (!AStmt)
3946 return StmtError();
3947
Alexey Bataev4acb8592014-07-07 13:01:15 +00003948 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3949 // 1.2.2 OpenMP Language Terminology
3950 // Structured block - An executable statement with a single entry at the
3951 // top and a single exit at the bottom.
3952 // The point of exit cannot be a branch out of the structured block.
3953 // longjmp() and throw() must not violate the entry/exit criteria.
3954 CS->getCapturedDecl()->setNothrow();
3955
Alexander Musmanc6388682014-12-15 07:07:06 +00003956 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003957 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3958 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003959 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00003960 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
3961 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
3962 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003963 if (NestedLoopCount == 0)
3964 return StmtError();
3965
Alexander Musmana5f070a2014-10-01 06:03:56 +00003966 assert((CurContext->isDependentContext() || B.builtAll()) &&
3967 "omp parallel for loop exprs were not built");
3968
Alexey Bataev54acd402015-08-04 11:18:19 +00003969 if (!CurContext->isDependentContext()) {
3970 // Finalize the clauses that need pre-built expressions for CodeGen.
3971 for (auto C : Clauses) {
3972 if (auto LC = dyn_cast<OMPLinearClause>(C))
3973 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3974 B.NumIterations, *this, CurScope))
3975 return StmtError();
3976 }
3977 }
3978
Alexey Bataev4acb8592014-07-07 13:01:15 +00003979 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003980 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003981 NestedLoopCount, Clauses, AStmt, B,
3982 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00003983}
3984
Alexander Musmane4e893b2014-09-23 09:33:00 +00003985StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3986 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3987 SourceLocation EndLoc,
3988 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003989 if (!AStmt)
3990 return StmtError();
3991
Alexander Musmane4e893b2014-09-23 09:33:00 +00003992 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3993 // 1.2.2 OpenMP Language Terminology
3994 // Structured block - An executable statement with a single entry at the
3995 // top and a single exit at the bottom.
3996 // The point of exit cannot be a branch out of the structured block.
3997 // longjmp() and throw() must not violate the entry/exit criteria.
3998 CS->getCapturedDecl()->setNothrow();
3999
Alexander Musmanc6388682014-12-15 07:07:06 +00004000 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004001 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4002 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004003 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004004 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4005 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4006 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004007 if (NestedLoopCount == 0)
4008 return StmtError();
4009
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004010 if (!CurContext->isDependentContext()) {
4011 // Finalize the clauses that need pre-built expressions for CodeGen.
4012 for (auto C : Clauses) {
4013 if (auto LC = dyn_cast<OMPLinearClause>(C))
4014 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4015 B.NumIterations, *this, CurScope))
4016 return StmtError();
4017 }
4018 }
4019
Alexey Bataev66b15b52015-08-21 11:14:16 +00004020 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4021 // If both simdlen and safelen clauses are specified, the value of the simdlen
4022 // parameter must be less than or equal to the value of the safelen parameter.
4023 OMPSafelenClause *Safelen = nullptr;
4024 OMPSimdlenClause *Simdlen = nullptr;
4025 for (auto *Clause : Clauses) {
4026 if (Clause->getClauseKind() == OMPC_safelen)
4027 Safelen = cast<OMPSafelenClause>(Clause);
4028 else if (Clause->getClauseKind() == OMPC_simdlen)
4029 Simdlen = cast<OMPSimdlenClause>(Clause);
4030 if (Safelen && Simdlen)
4031 break;
4032 }
4033 if (Simdlen && Safelen &&
4034 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4035 Safelen->getSafelen()))
4036 return StmtError();
4037
Alexander Musmane4e893b2014-09-23 09:33:00 +00004038 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004039 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004040 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004041}
4042
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004043StmtResult
4044Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4045 Stmt *AStmt, SourceLocation StartLoc,
4046 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004047 if (!AStmt)
4048 return StmtError();
4049
4050 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004051 auto BaseStmt = AStmt;
4052 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4053 BaseStmt = CS->getCapturedStmt();
4054 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4055 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004056 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004057 return StmtError();
4058 // All associated statements must be '#pragma omp section' except for
4059 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004060 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004061 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4062 if (SectionStmt)
4063 Diag(SectionStmt->getLocStart(),
4064 diag::err_omp_parallel_sections_substmt_not_section);
4065 return StmtError();
4066 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004067 cast<OMPSectionDirective>(SectionStmt)
4068 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004069 }
4070 } else {
4071 Diag(AStmt->getLocStart(),
4072 diag::err_omp_parallel_sections_not_compound_stmt);
4073 return StmtError();
4074 }
4075
4076 getCurFunction()->setHasBranchProtectedScope();
4077
Alexey Bataev25e5b442015-09-15 12:52:43 +00004078 return OMPParallelSectionsDirective::Create(
4079 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004080}
4081
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004082StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4083 Stmt *AStmt, SourceLocation StartLoc,
4084 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004085 if (!AStmt)
4086 return StmtError();
4087
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004088 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4089 // 1.2.2 OpenMP Language Terminology
4090 // Structured block - An executable statement with a single entry at the
4091 // top and a single exit at the bottom.
4092 // The point of exit cannot be a branch out of the structured block.
4093 // longjmp() and throw() must not violate the entry/exit criteria.
4094 CS->getCapturedDecl()->setNothrow();
4095
4096 getCurFunction()->setHasBranchProtectedScope();
4097
Alexey Bataev25e5b442015-09-15 12:52:43 +00004098 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4099 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004100}
4101
Alexey Bataev68446b72014-07-18 07:47:19 +00004102StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4103 SourceLocation EndLoc) {
4104 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4105}
4106
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004107StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4108 SourceLocation EndLoc) {
4109 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4110}
4111
Alexey Bataev2df347a2014-07-18 10:17:07 +00004112StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4113 SourceLocation EndLoc) {
4114 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4115}
4116
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004117StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4118 SourceLocation StartLoc,
4119 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004120 if (!AStmt)
4121 return StmtError();
4122
4123 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004124
4125 getCurFunction()->setHasBranchProtectedScope();
4126
4127 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4128}
4129
Alexey Bataev6125da92014-07-21 11:26:11 +00004130StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4131 SourceLocation StartLoc,
4132 SourceLocation EndLoc) {
4133 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4134 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4135}
4136
Alexey Bataev346265e2015-09-25 10:37:12 +00004137StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4138 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004139 SourceLocation StartLoc,
4140 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004141 if (!AStmt)
4142 return StmtError();
4143
4144 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004145
4146 getCurFunction()->setHasBranchProtectedScope();
4147
Alexey Bataev346265e2015-09-25 10:37:12 +00004148 OMPThreadsClause *TC = nullptr;
4149 for (auto *C: Clauses) {
4150 if (C->getClauseKind() == OMPC_threads)
4151 TC = cast<OMPThreadsClause>(C);
4152 }
4153
4154 // TODO: this must happen only if 'threads' clause specified or if no clauses
4155 // is specified.
4156 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4157 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4158 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) << (TC != nullptr);
4159 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4160 return StmtError();
4161 }
4162
4163 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004164}
4165
Alexey Bataev1d160b12015-03-13 12:27:31 +00004166namespace {
4167/// \brief Helper class for checking expression in 'omp atomic [update]'
4168/// construct.
4169class OpenMPAtomicUpdateChecker {
4170 /// \brief Error results for atomic update expressions.
4171 enum ExprAnalysisErrorCode {
4172 /// \brief A statement is not an expression statement.
4173 NotAnExpression,
4174 /// \brief Expression is not builtin binary or unary operation.
4175 NotABinaryOrUnaryExpression,
4176 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4177 NotAnUnaryIncDecExpression,
4178 /// \brief An expression is not of scalar type.
4179 NotAScalarType,
4180 /// \brief A binary operation is not an assignment operation.
4181 NotAnAssignmentOp,
4182 /// \brief RHS part of the binary operation is not a binary expression.
4183 NotABinaryExpression,
4184 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4185 /// expression.
4186 NotABinaryOperator,
4187 /// \brief RHS binary operation does not have reference to the updated LHS
4188 /// part.
4189 NotAnUpdateExpression,
4190 /// \brief No errors is found.
4191 NoError
4192 };
4193 /// \brief Reference to Sema.
4194 Sema &SemaRef;
4195 /// \brief A location for note diagnostics (when error is found).
4196 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004197 /// \brief 'x' lvalue part of the source atomic expression.
4198 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004199 /// \brief 'expr' rvalue part of the source atomic expression.
4200 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004201 /// \brief Helper expression of the form
4202 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4203 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4204 Expr *UpdateExpr;
4205 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4206 /// important for non-associative operations.
4207 bool IsXLHSInRHSPart;
4208 BinaryOperatorKind Op;
4209 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004210 /// \brief true if the source expression is a postfix unary operation, false
4211 /// if it is a prefix unary operation.
4212 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004213
4214public:
4215 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004216 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004217 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004218 /// \brief Check specified statement that it is suitable for 'atomic update'
4219 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004220 /// expression. If DiagId and NoteId == 0, then only check is performed
4221 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004222 /// \param DiagId Diagnostic which should be emitted if error is found.
4223 /// \param NoteId Diagnostic note for the main error message.
4224 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004225 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004226 /// \brief Return the 'x' lvalue part of the source atomic expression.
4227 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004228 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4229 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004230 /// \brief Return the update expression used in calculation of the updated
4231 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4232 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4233 Expr *getUpdateExpr() const { return UpdateExpr; }
4234 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4235 /// false otherwise.
4236 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4237
Alexey Bataevb78ca832015-04-01 03:33:17 +00004238 /// \brief true if the source expression is a postfix unary operation, false
4239 /// if it is a prefix unary operation.
4240 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4241
Alexey Bataev1d160b12015-03-13 12:27:31 +00004242private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004243 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4244 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004245};
4246} // namespace
4247
4248bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4249 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4250 ExprAnalysisErrorCode ErrorFound = NoError;
4251 SourceLocation ErrorLoc, NoteLoc;
4252 SourceRange ErrorRange, NoteRange;
4253 // Allowed constructs are:
4254 // x = x binop expr;
4255 // x = expr binop x;
4256 if (AtomicBinOp->getOpcode() == BO_Assign) {
4257 X = AtomicBinOp->getLHS();
4258 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4259 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4260 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4261 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4262 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004263 Op = AtomicInnerBinOp->getOpcode();
4264 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004265 auto *LHS = AtomicInnerBinOp->getLHS();
4266 auto *RHS = AtomicInnerBinOp->getRHS();
4267 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4268 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4269 /*Canonical=*/true);
4270 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4271 /*Canonical=*/true);
4272 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4273 /*Canonical=*/true);
4274 if (XId == LHSId) {
4275 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004276 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004277 } else if (XId == RHSId) {
4278 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004279 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004280 } else {
4281 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4282 ErrorRange = AtomicInnerBinOp->getSourceRange();
4283 NoteLoc = X->getExprLoc();
4284 NoteRange = X->getSourceRange();
4285 ErrorFound = NotAnUpdateExpression;
4286 }
4287 } else {
4288 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4289 ErrorRange = AtomicInnerBinOp->getSourceRange();
4290 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4291 NoteRange = SourceRange(NoteLoc, NoteLoc);
4292 ErrorFound = NotABinaryOperator;
4293 }
4294 } else {
4295 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4296 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4297 ErrorFound = NotABinaryExpression;
4298 }
4299 } else {
4300 ErrorLoc = AtomicBinOp->getExprLoc();
4301 ErrorRange = AtomicBinOp->getSourceRange();
4302 NoteLoc = AtomicBinOp->getOperatorLoc();
4303 NoteRange = SourceRange(NoteLoc, NoteLoc);
4304 ErrorFound = NotAnAssignmentOp;
4305 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004306 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004307 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4308 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4309 return true;
4310 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004311 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004312 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004313}
4314
4315bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4316 unsigned NoteId) {
4317 ExprAnalysisErrorCode ErrorFound = NoError;
4318 SourceLocation ErrorLoc, NoteLoc;
4319 SourceRange ErrorRange, NoteRange;
4320 // Allowed constructs are:
4321 // x++;
4322 // x--;
4323 // ++x;
4324 // --x;
4325 // x binop= expr;
4326 // x = x binop expr;
4327 // x = expr binop x;
4328 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4329 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4330 if (AtomicBody->getType()->isScalarType() ||
4331 AtomicBody->isInstantiationDependent()) {
4332 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4333 AtomicBody->IgnoreParenImpCasts())) {
4334 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004335 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004336 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004337 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004338 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004339 X = AtomicCompAssignOp->getLHS();
4340 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004341 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4342 AtomicBody->IgnoreParenImpCasts())) {
4343 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004344 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4345 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004346 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00004347 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
4348 // Check for Unary Operation
4349 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004350 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004351 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4352 OpLoc = AtomicUnaryOp->getOperatorLoc();
4353 X = AtomicUnaryOp->getSubExpr();
4354 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4355 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004356 } else {
4357 ErrorFound = NotAnUnaryIncDecExpression;
4358 ErrorLoc = AtomicUnaryOp->getExprLoc();
4359 ErrorRange = AtomicUnaryOp->getSourceRange();
4360 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4361 NoteRange = SourceRange(NoteLoc, NoteLoc);
4362 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004363 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004364 ErrorFound = NotABinaryOrUnaryExpression;
4365 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4366 NoteRange = ErrorRange = AtomicBody->getSourceRange();
4367 }
4368 } else {
4369 ErrorFound = NotAScalarType;
4370 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4371 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4372 }
4373 } else {
4374 ErrorFound = NotAnExpression;
4375 NoteLoc = ErrorLoc = S->getLocStart();
4376 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4377 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004378 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004379 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4380 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4381 return true;
4382 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004383 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004384 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004385 // Build an update expression of form 'OpaqueValueExpr(x) binop
4386 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4387 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4388 auto *OVEX = new (SemaRef.getASTContext())
4389 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4390 auto *OVEExpr = new (SemaRef.getASTContext())
4391 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4392 auto Update =
4393 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4394 IsXLHSInRHSPart ? OVEExpr : OVEX);
4395 if (Update.isInvalid())
4396 return true;
4397 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4398 Sema::AA_Casting);
4399 if (Update.isInvalid())
4400 return true;
4401 UpdateExpr = Update.get();
4402 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00004403 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004404}
4405
Alexey Bataev0162e452014-07-22 10:10:35 +00004406StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4407 Stmt *AStmt,
4408 SourceLocation StartLoc,
4409 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004410 if (!AStmt)
4411 return StmtError();
4412
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004413 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00004414 // 1.2.2 OpenMP Language Terminology
4415 // Structured block - An executable statement with a single entry at the
4416 // top and a single exit at the bottom.
4417 // The point of exit cannot be a branch out of the structured block.
4418 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00004419 OpenMPClauseKind AtomicKind = OMPC_unknown;
4420 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004421 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00004422 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00004423 C->getClauseKind() == OMPC_update ||
4424 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00004425 if (AtomicKind != OMPC_unknown) {
4426 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4427 << SourceRange(C->getLocStart(), C->getLocEnd());
4428 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4429 << getOpenMPClauseName(AtomicKind);
4430 } else {
4431 AtomicKind = C->getClauseKind();
4432 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004433 }
4434 }
4435 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004436
Alexey Bataev459dec02014-07-24 06:46:57 +00004437 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00004438 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4439 Body = EWC->getSubExpr();
4440
Alexey Bataev62cec442014-11-18 10:14:22 +00004441 Expr *X = nullptr;
4442 Expr *V = nullptr;
4443 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004444 Expr *UE = nullptr;
4445 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004446 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00004447 // OpenMP [2.12.6, atomic Construct]
4448 // In the next expressions:
4449 // * x and v (as applicable) are both l-value expressions with scalar type.
4450 // * During the execution of an atomic region, multiple syntactic
4451 // occurrences of x must designate the same storage location.
4452 // * Neither of v and expr (as applicable) may access the storage location
4453 // designated by x.
4454 // * Neither of x and expr (as applicable) may access the storage location
4455 // designated by v.
4456 // * expr is an expression with scalar type.
4457 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
4458 // * binop, binop=, ++, and -- are not overloaded operators.
4459 // * The expression x binop expr must be numerically equivalent to x binop
4460 // (expr). This requirement is satisfied if the operators in expr have
4461 // precedence greater than binop, or by using parentheses around expr or
4462 // subexpressions of expr.
4463 // * The expression expr binop x must be numerically equivalent to (expr)
4464 // binop x. This requirement is satisfied if the operators in expr have
4465 // precedence equal to or greater than binop, or by using parentheses around
4466 // expr or subexpressions of expr.
4467 // * For forms that allow multiple occurrences of x, the number of times
4468 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00004469 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004470 enum {
4471 NotAnExpression,
4472 NotAnAssignmentOp,
4473 NotAScalarType,
4474 NotAnLValue,
4475 NoError
4476 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00004477 SourceLocation ErrorLoc, NoteLoc;
4478 SourceRange ErrorRange, NoteRange;
4479 // If clause is read:
4480 // v = x;
4481 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4482 auto AtomicBinOp =
4483 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4484 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4485 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4486 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
4487 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4488 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
4489 if (!X->isLValue() || !V->isLValue()) {
4490 auto NotLValueExpr = X->isLValue() ? V : X;
4491 ErrorFound = NotAnLValue;
4492 ErrorLoc = AtomicBinOp->getExprLoc();
4493 ErrorRange = AtomicBinOp->getSourceRange();
4494 NoteLoc = NotLValueExpr->getExprLoc();
4495 NoteRange = NotLValueExpr->getSourceRange();
4496 }
4497 } else if (!X->isInstantiationDependent() ||
4498 !V->isInstantiationDependent()) {
4499 auto NotScalarExpr =
4500 (X->isInstantiationDependent() || X->getType()->isScalarType())
4501 ? V
4502 : X;
4503 ErrorFound = NotAScalarType;
4504 ErrorLoc = AtomicBinOp->getExprLoc();
4505 ErrorRange = AtomicBinOp->getSourceRange();
4506 NoteLoc = NotScalarExpr->getExprLoc();
4507 NoteRange = NotScalarExpr->getSourceRange();
4508 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004509 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00004510 ErrorFound = NotAnAssignmentOp;
4511 ErrorLoc = AtomicBody->getExprLoc();
4512 ErrorRange = AtomicBody->getSourceRange();
4513 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4514 : AtomicBody->getExprLoc();
4515 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4516 : AtomicBody->getSourceRange();
4517 }
4518 } else {
4519 ErrorFound = NotAnExpression;
4520 NoteLoc = ErrorLoc = Body->getLocStart();
4521 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004522 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004523 if (ErrorFound != NoError) {
4524 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
4525 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004526 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4527 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00004528 return StmtError();
4529 } else if (CurContext->isDependentContext())
4530 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00004531 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004532 enum {
4533 NotAnExpression,
4534 NotAnAssignmentOp,
4535 NotAScalarType,
4536 NotAnLValue,
4537 NoError
4538 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004539 SourceLocation ErrorLoc, NoteLoc;
4540 SourceRange ErrorRange, NoteRange;
4541 // If clause is write:
4542 // x = expr;
4543 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4544 auto AtomicBinOp =
4545 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4546 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00004547 X = AtomicBinOp->getLHS();
4548 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00004549 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4550 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
4551 if (!X->isLValue()) {
4552 ErrorFound = NotAnLValue;
4553 ErrorLoc = AtomicBinOp->getExprLoc();
4554 ErrorRange = AtomicBinOp->getSourceRange();
4555 NoteLoc = X->getExprLoc();
4556 NoteRange = X->getSourceRange();
4557 }
4558 } else if (!X->isInstantiationDependent() ||
4559 !E->isInstantiationDependent()) {
4560 auto NotScalarExpr =
4561 (X->isInstantiationDependent() || X->getType()->isScalarType())
4562 ? E
4563 : X;
4564 ErrorFound = NotAScalarType;
4565 ErrorLoc = AtomicBinOp->getExprLoc();
4566 ErrorRange = AtomicBinOp->getSourceRange();
4567 NoteLoc = NotScalarExpr->getExprLoc();
4568 NoteRange = NotScalarExpr->getSourceRange();
4569 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004570 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00004571 ErrorFound = NotAnAssignmentOp;
4572 ErrorLoc = AtomicBody->getExprLoc();
4573 ErrorRange = AtomicBody->getSourceRange();
4574 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4575 : AtomicBody->getExprLoc();
4576 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4577 : AtomicBody->getSourceRange();
4578 }
4579 } else {
4580 ErrorFound = NotAnExpression;
4581 NoteLoc = ErrorLoc = Body->getLocStart();
4582 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004583 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00004584 if (ErrorFound != NoError) {
4585 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
4586 << ErrorRange;
4587 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4588 << NoteRange;
4589 return StmtError();
4590 } else if (CurContext->isDependentContext())
4591 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004592 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004593 // If clause is update:
4594 // x++;
4595 // x--;
4596 // ++x;
4597 // --x;
4598 // x binop= expr;
4599 // x = x binop expr;
4600 // x = expr binop x;
4601 OpenMPAtomicUpdateChecker Checker(*this);
4602 if (Checker.checkStatement(
4603 Body, (AtomicKind == OMPC_update)
4604 ? diag::err_omp_atomic_update_not_expression_statement
4605 : diag::err_omp_atomic_not_expression_statement,
4606 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00004607 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004608 if (!CurContext->isDependentContext()) {
4609 E = Checker.getExpr();
4610 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004611 UE = Checker.getUpdateExpr();
4612 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00004613 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004614 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004615 enum {
4616 NotAnAssignmentOp,
4617 NotACompoundStatement,
4618 NotTwoSubstatements,
4619 NotASpecificExpression,
4620 NoError
4621 } ErrorFound = NoError;
4622 SourceLocation ErrorLoc, NoteLoc;
4623 SourceRange ErrorRange, NoteRange;
4624 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
4625 // If clause is a capture:
4626 // v = x++;
4627 // v = x--;
4628 // v = ++x;
4629 // v = --x;
4630 // v = x binop= expr;
4631 // v = x = x binop expr;
4632 // v = x = expr binop x;
4633 auto *AtomicBinOp =
4634 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4635 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4636 V = AtomicBinOp->getLHS();
4637 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4638 OpenMPAtomicUpdateChecker Checker(*this);
4639 if (Checker.checkStatement(
4640 Body, diag::err_omp_atomic_capture_not_expression_statement,
4641 diag::note_omp_atomic_update))
4642 return StmtError();
4643 E = Checker.getExpr();
4644 X = Checker.getX();
4645 UE = Checker.getUpdateExpr();
4646 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4647 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00004648 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004649 ErrorLoc = AtomicBody->getExprLoc();
4650 ErrorRange = AtomicBody->getSourceRange();
4651 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4652 : AtomicBody->getExprLoc();
4653 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4654 : AtomicBody->getSourceRange();
4655 ErrorFound = NotAnAssignmentOp;
4656 }
4657 if (ErrorFound != NoError) {
4658 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
4659 << ErrorRange;
4660 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4661 return StmtError();
4662 } else if (CurContext->isDependentContext()) {
4663 UE = V = E = X = nullptr;
4664 }
4665 } else {
4666 // If clause is a capture:
4667 // { v = x; x = expr; }
4668 // { v = x; x++; }
4669 // { v = x; x--; }
4670 // { v = x; ++x; }
4671 // { v = x; --x; }
4672 // { v = x; x binop= expr; }
4673 // { v = x; x = x binop expr; }
4674 // { v = x; x = expr binop x; }
4675 // { x++; v = x; }
4676 // { x--; v = x; }
4677 // { ++x; v = x; }
4678 // { --x; v = x; }
4679 // { x binop= expr; v = x; }
4680 // { x = x binop expr; v = x; }
4681 // { x = expr binop x; v = x; }
4682 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4683 // Check that this is { expr1; expr2; }
4684 if (CS->size() == 2) {
4685 auto *First = CS->body_front();
4686 auto *Second = CS->body_back();
4687 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4688 First = EWC->getSubExpr()->IgnoreParenImpCasts();
4689 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4690 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4691 // Need to find what subexpression is 'v' and what is 'x'.
4692 OpenMPAtomicUpdateChecker Checker(*this);
4693 bool IsUpdateExprFound = !Checker.checkStatement(Second);
4694 BinaryOperator *BinOp = nullptr;
4695 if (IsUpdateExprFound) {
4696 BinOp = dyn_cast<BinaryOperator>(First);
4697 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4698 }
4699 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4700 // { v = x; x++; }
4701 // { v = x; x--; }
4702 // { v = x; ++x; }
4703 // { v = x; --x; }
4704 // { v = x; x binop= expr; }
4705 // { v = x; x = x binop expr; }
4706 // { v = x; x = expr binop x; }
4707 // Check that the first expression has form v = x.
4708 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4709 llvm::FoldingSetNodeID XId, PossibleXId;
4710 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4711 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4712 IsUpdateExprFound = XId == PossibleXId;
4713 if (IsUpdateExprFound) {
4714 V = BinOp->getLHS();
4715 X = Checker.getX();
4716 E = Checker.getExpr();
4717 UE = Checker.getUpdateExpr();
4718 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004719 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004720 }
4721 }
4722 if (!IsUpdateExprFound) {
4723 IsUpdateExprFound = !Checker.checkStatement(First);
4724 BinOp = nullptr;
4725 if (IsUpdateExprFound) {
4726 BinOp = dyn_cast<BinaryOperator>(Second);
4727 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4728 }
4729 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4730 // { x++; v = x; }
4731 // { x--; v = x; }
4732 // { ++x; v = x; }
4733 // { --x; v = x; }
4734 // { x binop= expr; v = x; }
4735 // { x = x binop expr; v = x; }
4736 // { x = expr binop x; v = x; }
4737 // Check that the second expression has form v = x.
4738 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4739 llvm::FoldingSetNodeID XId, PossibleXId;
4740 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4741 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4742 IsUpdateExprFound = XId == PossibleXId;
4743 if (IsUpdateExprFound) {
4744 V = BinOp->getLHS();
4745 X = Checker.getX();
4746 E = Checker.getExpr();
4747 UE = Checker.getUpdateExpr();
4748 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004749 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004750 }
4751 }
4752 }
4753 if (!IsUpdateExprFound) {
4754 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00004755 auto *FirstExpr = dyn_cast<Expr>(First);
4756 auto *SecondExpr = dyn_cast<Expr>(Second);
4757 if (!FirstExpr || !SecondExpr ||
4758 !(FirstExpr->isInstantiationDependent() ||
4759 SecondExpr->isInstantiationDependent())) {
4760 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4761 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004762 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00004763 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4764 : First->getLocStart();
4765 NoteRange = ErrorRange = FirstBinOp
4766 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00004767 : SourceRange(ErrorLoc, ErrorLoc);
4768 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004769 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4770 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4771 ErrorFound = NotAnAssignmentOp;
4772 NoteLoc = ErrorLoc = SecondBinOp
4773 ? SecondBinOp->getOperatorLoc()
4774 : Second->getLocStart();
4775 NoteRange = ErrorRange =
4776 SecondBinOp ? SecondBinOp->getSourceRange()
4777 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00004778 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004779 auto *PossibleXRHSInFirst =
4780 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4781 auto *PossibleXLHSInSecond =
4782 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4783 llvm::FoldingSetNodeID X1Id, X2Id;
4784 PossibleXRHSInFirst->Profile(X1Id, Context,
4785 /*Canonical=*/true);
4786 PossibleXLHSInSecond->Profile(X2Id, Context,
4787 /*Canonical=*/true);
4788 IsUpdateExprFound = X1Id == X2Id;
4789 if (IsUpdateExprFound) {
4790 V = FirstBinOp->getLHS();
4791 X = SecondBinOp->getLHS();
4792 E = SecondBinOp->getRHS();
4793 UE = nullptr;
4794 IsXLHSInRHSPart = false;
4795 IsPostfixUpdate = true;
4796 } else {
4797 ErrorFound = NotASpecificExpression;
4798 ErrorLoc = FirstBinOp->getExprLoc();
4799 ErrorRange = FirstBinOp->getSourceRange();
4800 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4801 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4802 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004803 }
4804 }
4805 }
4806 }
4807 } else {
4808 NoteLoc = ErrorLoc = Body->getLocStart();
4809 NoteRange = ErrorRange =
4810 SourceRange(Body->getLocStart(), Body->getLocStart());
4811 ErrorFound = NotTwoSubstatements;
4812 }
4813 } else {
4814 NoteLoc = ErrorLoc = Body->getLocStart();
4815 NoteRange = ErrorRange =
4816 SourceRange(Body->getLocStart(), Body->getLocStart());
4817 ErrorFound = NotACompoundStatement;
4818 }
4819 if (ErrorFound != NoError) {
4820 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4821 << ErrorRange;
4822 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4823 return StmtError();
4824 } else if (CurContext->isDependentContext()) {
4825 UE = V = E = X = nullptr;
4826 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004827 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004828 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004829
4830 getCurFunction()->setHasBranchProtectedScope();
4831
Alexey Bataev62cec442014-11-18 10:14:22 +00004832 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004833 X, V, E, UE, IsXLHSInRHSPart,
4834 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004835}
4836
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004837StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4838 Stmt *AStmt,
4839 SourceLocation StartLoc,
4840 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004841 if (!AStmt)
4842 return StmtError();
4843
4844 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004845
Alexey Bataev13314bf2014-10-09 04:18:56 +00004846 // OpenMP [2.16, Nesting of Regions]
4847 // If specified, a teams construct must be contained within a target
4848 // construct. That target construct must contain no statements or directives
4849 // outside of the teams construct.
4850 if (DSAStack->hasInnerTeamsRegion()) {
4851 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4852 bool OMPTeamsFound = true;
4853 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4854 auto I = CS->body_begin();
4855 while (I != CS->body_end()) {
4856 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4857 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4858 OMPTeamsFound = false;
4859 break;
4860 }
4861 ++I;
4862 }
4863 assert(I != CS->body_end() && "Not found statement");
4864 S = *I;
4865 }
4866 if (!OMPTeamsFound) {
4867 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4868 Diag(DSAStack->getInnerTeamsRegionLoc(),
4869 diag::note_omp_nested_teams_construct_here);
4870 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4871 << isa<OMPExecutableDirective>(S);
4872 return StmtError();
4873 }
4874 }
4875
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004876 getCurFunction()->setHasBranchProtectedScope();
4877
4878 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4879}
4880
Michael Wong65f367f2015-07-21 13:44:28 +00004881StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
4882 Stmt *AStmt,
4883 SourceLocation StartLoc,
4884 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004885 if (!AStmt)
4886 return StmtError();
4887
4888 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4889
Michael Wong65f367f2015-07-21 13:44:28 +00004890 getCurFunction()->setHasBranchProtectedScope();
4891
4892 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
4893 AStmt);
4894}
4895
Alexey Bataev13314bf2014-10-09 04:18:56 +00004896StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4897 Stmt *AStmt, SourceLocation StartLoc,
4898 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004899 if (!AStmt)
4900 return StmtError();
4901
Alexey Bataev13314bf2014-10-09 04:18:56 +00004902 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4903 // 1.2.2 OpenMP Language Terminology
4904 // Structured block - An executable statement with a single entry at the
4905 // top and a single exit at the bottom.
4906 // The point of exit cannot be a branch out of the structured block.
4907 // longjmp() and throw() must not violate the entry/exit criteria.
4908 CS->getCapturedDecl()->setNothrow();
4909
4910 getCurFunction()->setHasBranchProtectedScope();
4911
4912 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4913}
4914
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004915StmtResult
4916Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
4917 SourceLocation EndLoc,
4918 OpenMPDirectiveKind CancelRegion) {
4919 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4920 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4921 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4922 << getOpenMPDirectiveName(CancelRegion);
4923 return StmtError();
4924 }
4925 if (DSAStack->isParentNowaitRegion()) {
4926 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
4927 return StmtError();
4928 }
4929 if (DSAStack->isParentOrderedRegion()) {
4930 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
4931 return StmtError();
4932 }
4933 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
4934 CancelRegion);
4935}
4936
Alexey Bataev87933c72015-09-18 08:07:34 +00004937StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
4938 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00004939 SourceLocation EndLoc,
4940 OpenMPDirectiveKind CancelRegion) {
4941 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4942 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4943 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4944 << getOpenMPDirectiveName(CancelRegion);
4945 return StmtError();
4946 }
4947 if (DSAStack->isParentNowaitRegion()) {
4948 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
4949 return StmtError();
4950 }
4951 if (DSAStack->isParentOrderedRegion()) {
4952 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
4953 return StmtError();
4954 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004955 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00004956 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
4957 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00004958}
4959
Alexey Bataeved09d242014-05-28 05:53:51 +00004960OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004961 SourceLocation StartLoc,
4962 SourceLocation LParenLoc,
4963 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00004964 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004965 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00004966 case OMPC_final:
4967 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4968 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00004969 case OMPC_num_threads:
4970 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4971 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00004972 case OMPC_safelen:
4973 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4974 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00004975 case OMPC_simdlen:
4976 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
4977 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00004978 case OMPC_collapse:
4979 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4980 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004981 case OMPC_ordered:
4982 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
4983 break;
Michael Wonge710d542015-08-07 16:16:36 +00004984 case OMPC_device:
4985 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
4986 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004987 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004988 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00004989 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00004990 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004991 case OMPC_private:
4992 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00004993 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00004994 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00004995 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00004996 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00004997 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00004998 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00004999 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00005000 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005001 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005002 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005003 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005004 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005005 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005006 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005007 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005008 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005009 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005010 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00005011 case OMPC_threads:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005012 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005013 llvm_unreachable("Clause is not allowed.");
5014 }
5015 return Res;
5016}
5017
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005018OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
5019 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005020 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005021 SourceLocation NameModifierLoc,
5022 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005023 SourceLocation EndLoc) {
5024 Expr *ValExpr = Condition;
5025 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5026 !Condition->isInstantiationDependent() &&
5027 !Condition->containsUnexpandedParameterPack()) {
5028 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00005029 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005030 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005031 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005032
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005033 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005034 }
5035
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005036 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
5037 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005038}
5039
Alexey Bataev3778b602014-07-17 07:32:53 +00005040OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
5041 SourceLocation StartLoc,
5042 SourceLocation LParenLoc,
5043 SourceLocation EndLoc) {
5044 Expr *ValExpr = Condition;
5045 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5046 !Condition->isInstantiationDependent() &&
5047 !Condition->containsUnexpandedParameterPack()) {
5048 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5049 Condition->getExprLoc(), Condition);
5050 if (Val.isInvalid())
5051 return nullptr;
5052
5053 ValExpr = Val.get();
5054 }
5055
5056 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5057}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005058ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
5059 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00005060 if (!Op)
5061 return ExprError();
5062
5063 class IntConvertDiagnoser : public ICEConvertDiagnoser {
5064 public:
5065 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00005066 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00005067 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
5068 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005069 return S.Diag(Loc, diag::err_omp_not_integral) << T;
5070 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005071 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
5072 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005073 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
5074 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005075 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
5076 QualType T,
5077 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005078 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
5079 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005080 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
5081 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005082 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005083 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005084 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005085 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
5086 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005087 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
5088 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005089 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
5090 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005091 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005092 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005093 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005094 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
5095 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005096 llvm_unreachable("conversion functions are permitted");
5097 }
5098 } ConvertDiagnoser;
5099 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
5100}
5101
5102OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
5103 SourceLocation StartLoc,
5104 SourceLocation LParenLoc,
5105 SourceLocation EndLoc) {
5106 Expr *ValExpr = NumThreads;
5107 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00005108 !NumThreads->containsUnexpandedParameterPack()) {
5109 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
5110 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005111 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00005112 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005113 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00005114
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005115 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00005116
5117 // OpenMP [2.5, Restrictions]
5118 // The num_threads expression must evaluate to a positive integer value.
5119 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00005120 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
5121 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00005122 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
5123 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005124 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00005125 }
5126 }
5127
Alexey Bataeved09d242014-05-28 05:53:51 +00005128 return new (Context)
5129 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00005130}
5131
Alexey Bataev62c87d22014-03-21 04:51:18 +00005132ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
5133 OpenMPClauseKind CKind) {
5134 if (!E)
5135 return ExprError();
5136 if (E->isValueDependent() || E->isTypeDependent() ||
5137 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005138 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005139 llvm::APSInt Result;
5140 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
5141 if (ICE.isInvalid())
5142 return ExprError();
5143 if (!Result.isStrictlyPositive()) {
5144 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
5145 << getOpenMPClauseName(CKind) << E->getSourceRange();
5146 return ExprError();
5147 }
Alexander Musman09184fe2014-09-30 05:29:28 +00005148 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
5149 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
5150 << E->getSourceRange();
5151 return ExprError();
5152 }
Alexey Bataev9c821032015-04-30 04:23:23 +00005153 if (CKind == OMPC_collapse) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005154 DSAStack->setCollapseNumber(DSAStack->getCollapseNumber() - 1 +
5155 Result.getExtValue());
5156 } else if (CKind == OMPC_ordered) {
5157 DSAStack->setCollapseNumber(DSAStack->getCollapseNumber() - 1 +
5158 Result.getExtValue());
Alexey Bataev9c821032015-04-30 04:23:23 +00005159 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00005160 return ICE;
5161}
5162
5163OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
5164 SourceLocation LParenLoc,
5165 SourceLocation EndLoc) {
5166 // OpenMP [2.8.1, simd construct, Description]
5167 // The parameter of the safelen clause must be a constant
5168 // positive integer expression.
5169 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
5170 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005171 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005172 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005173 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00005174}
5175
Alexey Bataev66b15b52015-08-21 11:14:16 +00005176OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
5177 SourceLocation LParenLoc,
5178 SourceLocation EndLoc) {
5179 // OpenMP [2.8.1, simd construct, Description]
5180 // The parameter of the simdlen clause must be a constant
5181 // positive integer expression.
5182 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
5183 if (Simdlen.isInvalid())
5184 return nullptr;
5185 return new (Context)
5186 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
5187}
5188
Alexander Musman64d33f12014-06-04 07:53:32 +00005189OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
5190 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00005191 SourceLocation LParenLoc,
5192 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00005193 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005194 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00005195 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005196 // The parameter of the collapse clause must be a constant
5197 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00005198 ExprResult NumForLoopsResult =
5199 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
5200 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00005201 return nullptr;
5202 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00005203 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00005204}
5205
Alexey Bataev10e775f2015-07-30 11:36:16 +00005206OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5207 SourceLocation EndLoc,
5208 SourceLocation LParenLoc,
5209 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005210 // OpenMP [2.7.1, loop construct, Description]
5211 // OpenMP [2.8.1, simd construct, Description]
5212 // OpenMP [2.9.6, distribute construct, Description]
5213 // The parameter of the ordered clause must be a constant
5214 // positive integer expression if any.
5215 if (NumForLoops && LParenLoc.isValid()) {
5216 ExprResult NumForLoopsResult =
5217 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
5218 if (NumForLoopsResult.isInvalid())
5219 return nullptr;
5220 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00005221 } else
5222 NumForLoops = nullptr;
5223 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00005224 return new (Context)
5225 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
5226}
5227
Alexey Bataeved09d242014-05-28 05:53:51 +00005228OMPClause *Sema::ActOnOpenMPSimpleClause(
5229 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
5230 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005231 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005232 switch (Kind) {
5233 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005234 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00005235 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
5236 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005237 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005238 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00005239 Res = ActOnOpenMPProcBindClause(
5240 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
5241 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005242 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005243 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005244 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005245 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005246 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005247 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005248 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005249 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005250 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005251 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005252 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005253 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005254 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005255 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005256 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005257 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005258 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005259 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005260 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005261 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005262 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005263 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005264 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005265 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005266 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005267 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005268 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005269 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005270 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005271 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005272 case OMPC_threads:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005273 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005274 llvm_unreachable("Clause is not allowed.");
5275 }
5276 return Res;
5277}
5278
5279OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
5280 SourceLocation KindKwLoc,
5281 SourceLocation StartLoc,
5282 SourceLocation LParenLoc,
5283 SourceLocation EndLoc) {
5284 if (Kind == OMPC_DEFAULT_unknown) {
5285 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005286 static_assert(OMPC_DEFAULT_unknown > 0,
5287 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00005288 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005289 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005290 Values += "'";
5291 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
5292 Values += "'";
5293 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005294 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005295 Values += " or ";
5296 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005297 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005298 break;
5299 default:
5300 Values += Sep;
5301 break;
5302 }
5303 }
5304 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005305 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005306 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005307 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00005308 switch (Kind) {
5309 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005310 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005311 break;
5312 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005313 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005314 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005315 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005316 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00005317 break;
5318 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005319 return new (Context)
5320 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005321}
5322
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005323OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
5324 SourceLocation KindKwLoc,
5325 SourceLocation StartLoc,
5326 SourceLocation LParenLoc,
5327 SourceLocation EndLoc) {
5328 if (Kind == OMPC_PROC_BIND_unknown) {
5329 std::string Values;
5330 std::string Sep(", ");
5331 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
5332 Values += "'";
5333 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
5334 Values += "'";
5335 switch (i) {
5336 case OMPC_PROC_BIND_unknown - 2:
5337 Values += " or ";
5338 break;
5339 case OMPC_PROC_BIND_unknown - 1:
5340 break;
5341 default:
5342 Values += Sep;
5343 break;
5344 }
5345 }
5346 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005347 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005348 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005349 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005350 return new (Context)
5351 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005352}
5353
Alexey Bataev56dafe82014-06-20 07:16:17 +00005354OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
5355 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
5356 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005357 SourceLocation ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00005358 SourceLocation EndLoc) {
5359 OMPClause *Res = nullptr;
5360 switch (Kind) {
5361 case OMPC_schedule:
5362 Res = ActOnOpenMPScheduleClause(
5363 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005364 LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005365 break;
5366 case OMPC_if:
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005367 Res =
5368 ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument), Expr,
5369 StartLoc, LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
5370 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00005371 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005372 case OMPC_num_threads:
5373 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005374 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005375 case OMPC_collapse:
5376 case OMPC_default:
5377 case OMPC_proc_bind:
5378 case OMPC_private:
5379 case OMPC_firstprivate:
5380 case OMPC_lastprivate:
5381 case OMPC_shared:
5382 case OMPC_reduction:
5383 case OMPC_linear:
5384 case OMPC_aligned:
5385 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005386 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005387 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005388 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005389 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005390 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005391 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005392 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005393 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005394 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005395 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005396 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005397 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005398 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005399 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005400 case OMPC_threads:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005401 case OMPC_unknown:
5402 llvm_unreachable("Clause is not allowed.");
5403 }
5404 return Res;
5405}
5406
5407OMPClause *Sema::ActOnOpenMPScheduleClause(
5408 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
5409 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
5410 SourceLocation EndLoc) {
5411 if (Kind == OMPC_SCHEDULE_unknown) {
5412 std::string Values;
5413 std::string Sep(", ");
5414 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
5415 Values += "'";
5416 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
5417 Values += "'";
5418 switch (i) {
5419 case OMPC_SCHEDULE_unknown - 2:
5420 Values += " or ";
5421 break;
5422 case OMPC_SCHEDULE_unknown - 1:
5423 break;
5424 default:
5425 Values += Sep;
5426 break;
5427 }
5428 }
5429 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
5430 << Values << getOpenMPClauseName(OMPC_schedule);
5431 return nullptr;
5432 }
5433 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00005434 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005435 if (ChunkSize) {
5436 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
5437 !ChunkSize->isInstantiationDependent() &&
5438 !ChunkSize->containsUnexpandedParameterPack()) {
5439 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
5440 ExprResult Val =
5441 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
5442 if (Val.isInvalid())
5443 return nullptr;
5444
5445 ValExpr = Val.get();
5446
5447 // OpenMP [2.7.1, Restrictions]
5448 // chunk_size must be a loop invariant integer expression with a positive
5449 // value.
5450 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00005451 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
5452 if (Result.isSigned() && !Result.isStrictlyPositive()) {
5453 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
5454 << "schedule" << ChunkSize->getSourceRange();
5455 return nullptr;
5456 }
5457 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
5458 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
5459 ChunkSize->getType(), ".chunk.");
5460 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
5461 ChunkSize->getExprLoc(),
5462 /*RefersToCapture=*/true);
5463 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005464 }
5465 }
5466 }
5467
5468 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00005469 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005470}
5471
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005472OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
5473 SourceLocation StartLoc,
5474 SourceLocation EndLoc) {
5475 OMPClause *Res = nullptr;
5476 switch (Kind) {
5477 case OMPC_ordered:
5478 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
5479 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00005480 case OMPC_nowait:
5481 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
5482 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005483 case OMPC_untied:
5484 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
5485 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005486 case OMPC_mergeable:
5487 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
5488 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005489 case OMPC_read:
5490 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
5491 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00005492 case OMPC_write:
5493 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
5494 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005495 case OMPC_update:
5496 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
5497 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00005498 case OMPC_capture:
5499 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
5500 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005501 case OMPC_seq_cst:
5502 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
5503 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00005504 case OMPC_threads:
5505 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
5506 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005507 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005508 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005509 case OMPC_num_threads:
5510 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005511 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005512 case OMPC_collapse:
5513 case OMPC_schedule:
5514 case OMPC_private:
5515 case OMPC_firstprivate:
5516 case OMPC_lastprivate:
5517 case OMPC_shared:
5518 case OMPC_reduction:
5519 case OMPC_linear:
5520 case OMPC_aligned:
5521 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005522 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005523 case OMPC_default:
5524 case OMPC_proc_bind:
5525 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005526 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005527 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005528 case OMPC_device:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005529 case OMPC_unknown:
5530 llvm_unreachable("Clause is not allowed.");
5531 }
5532 return Res;
5533}
5534
Alexey Bataev236070f2014-06-20 11:19:47 +00005535OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
5536 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005537 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00005538 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
5539}
5540
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005541OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
5542 SourceLocation EndLoc) {
5543 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
5544}
5545
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005546OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
5547 SourceLocation EndLoc) {
5548 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
5549}
5550
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005551OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
5552 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005553 return new (Context) OMPReadClause(StartLoc, EndLoc);
5554}
5555
Alexey Bataevdea47612014-07-23 07:46:59 +00005556OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
5557 SourceLocation EndLoc) {
5558 return new (Context) OMPWriteClause(StartLoc, EndLoc);
5559}
5560
Alexey Bataev67a4f222014-07-23 10:25:33 +00005561OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
5562 SourceLocation EndLoc) {
5563 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
5564}
5565
Alexey Bataev459dec02014-07-24 06:46:57 +00005566OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
5567 SourceLocation EndLoc) {
5568 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
5569}
5570
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005571OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
5572 SourceLocation EndLoc) {
5573 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
5574}
5575
Alexey Bataev346265e2015-09-25 10:37:12 +00005576OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
5577 SourceLocation EndLoc) {
5578 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
5579}
5580
Alexey Bataevc5e02582014-06-16 07:08:35 +00005581OMPClause *Sema::ActOnOpenMPVarListClause(
5582 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
5583 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
5584 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005585 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Alexey Bataev182227b2015-08-20 10:54:39 +00005586 OpenMPLinearClauseKind LinKind, SourceLocation DepLinLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005587 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005588 switch (Kind) {
5589 case OMPC_private:
5590 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5591 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005592 case OMPC_firstprivate:
5593 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5594 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005595 case OMPC_lastprivate:
5596 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5597 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005598 case OMPC_shared:
5599 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
5600 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005601 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00005602 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
5603 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005604 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00005605 case OMPC_linear:
5606 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Alexey Bataev182227b2015-08-20 10:54:39 +00005607 LinKind, DepLinLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00005608 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005609 case OMPC_aligned:
5610 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
5611 ColonLoc, EndLoc);
5612 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005613 case OMPC_copyin:
5614 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
5615 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005616 case OMPC_copyprivate:
5617 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5618 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00005619 case OMPC_flush:
5620 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
5621 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005622 case OMPC_depend:
Alexey Bataev182227b2015-08-20 10:54:39 +00005623 Res = ActOnOpenMPDependClause(DepKind, DepLinLoc, ColonLoc, VarList, StartLoc,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005624 LParenLoc, EndLoc);
5625 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005626 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005627 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005628 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005629 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005630 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005631 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005632 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005633 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005634 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005635 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005636 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005637 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005638 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005639 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005640 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005641 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005642 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005643 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005644 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00005645 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005646 case OMPC_threads:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005647 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005648 llvm_unreachable("Clause is not allowed.");
5649 }
5650 return Res;
5651}
5652
5653OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
5654 SourceLocation StartLoc,
5655 SourceLocation LParenLoc,
5656 SourceLocation EndLoc) {
5657 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00005658 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00005659 for (auto &RefExpr : VarList) {
5660 assert(RefExpr && "NULL expr in OpenMP private clause.");
5661 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005662 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005663 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005664 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005665 continue;
5666 }
5667
Alexey Bataeved09d242014-05-28 05:53:51 +00005668 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005669 // OpenMP [2.1, C/C++]
5670 // A list item is a variable name.
5671 // OpenMP [2.9.3.3, Restrictions, p.1]
5672 // A variable that is part of another variable (as an array or
5673 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005674 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005675 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005676 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005677 continue;
5678 }
5679 Decl *D = DE->getDecl();
5680 VarDecl *VD = cast<VarDecl>(D);
5681
5682 QualType Type = VD->getType();
5683 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5684 // It will be analyzed later.
5685 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005686 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005687 continue;
5688 }
5689
5690 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5691 // A variable that appears in a private clause must not have an incomplete
5692 // type or a reference type.
5693 if (RequireCompleteType(ELoc, Type,
5694 diag::err_omp_private_incomplete_type)) {
5695 continue;
5696 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005697 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005698
Alexey Bataev758e55e2013-09-06 18:03:48 +00005699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5700 // in a Construct]
5701 // Variables with the predetermined data-sharing attributes may not be
5702 // listed in data-sharing attributes clauses, except for the cases
5703 // listed below. For these exceptions only, listing a predetermined
5704 // variable in a data-sharing attribute clause is allowed and overrides
5705 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005706 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005707 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005708 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5709 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005710 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005711 continue;
5712 }
5713
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005714 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005715 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005716 DSAStack->getCurrentDirective() == OMPD_task) {
5717 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5718 << getOpenMPClauseName(OMPC_private) << Type
5719 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5720 bool IsDecl =
5721 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5722 Diag(VD->getLocation(),
5723 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5724 << VD;
5725 continue;
5726 }
5727
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005728 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
5729 // A variable of class type (or array thereof) that appears in a private
5730 // clause requires an accessible, unambiguous default constructor for the
5731 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00005732 // Generate helper private variable and initialize it with the default
5733 // value. The address of the original variable is replaced by the address of
5734 // the new private variable in CodeGen. This new variable is not added to
5735 // IdResolver, so the code in the OpenMP region uses original variable for
5736 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005737 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00005738 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(),
5739 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005740 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005741 if (VDPrivate->isInvalidDecl())
5742 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005743 auto VDPrivateRefExpr = buildDeclRefExpr(
5744 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00005745
Alexey Bataev758e55e2013-09-06 18:03:48 +00005746 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005747 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005748 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005749 }
5750
Alexey Bataeved09d242014-05-28 05:53:51 +00005751 if (Vars.empty())
5752 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005753
Alexey Bataev03b340a2014-10-21 03:16:40 +00005754 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
5755 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005756}
5757
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005758namespace {
5759class DiagsUninitializedSeveretyRAII {
5760private:
5761 DiagnosticsEngine &Diags;
5762 SourceLocation SavedLoc;
5763 bool IsIgnored;
5764
5765public:
5766 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
5767 bool IsIgnored)
5768 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
5769 if (!IsIgnored) {
5770 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
5771 /*Map*/ diag::Severity::Ignored, Loc);
5772 }
5773 }
5774 ~DiagsUninitializedSeveretyRAII() {
5775 if (!IsIgnored)
5776 Diags.popMappings(SavedLoc);
5777 }
5778};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005779}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005780
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005781OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
5782 SourceLocation StartLoc,
5783 SourceLocation LParenLoc,
5784 SourceLocation EndLoc) {
5785 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005786 SmallVector<Expr *, 8> PrivateCopies;
5787 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005788 bool IsImplicitClause =
5789 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
5790 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
5791
Alexey Bataeved09d242014-05-28 05:53:51 +00005792 for (auto &RefExpr : VarList) {
5793 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
5794 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005795 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005796 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005797 PrivateCopies.push_back(nullptr);
5798 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005799 continue;
5800 }
5801
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005802 SourceLocation ELoc =
5803 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005804 // OpenMP [2.1, C/C++]
5805 // A list item is a variable name.
5806 // OpenMP [2.9.3.3, Restrictions, p.1]
5807 // A variable that is part of another variable (as an array or
5808 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005809 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005810 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005811 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005812 continue;
5813 }
5814 Decl *D = DE->getDecl();
5815 VarDecl *VD = cast<VarDecl>(D);
5816
5817 QualType Type = VD->getType();
5818 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5819 // It will be analyzed later.
5820 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005821 PrivateCopies.push_back(nullptr);
5822 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005823 continue;
5824 }
5825
5826 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5827 // A variable that appears in a private clause must not have an incomplete
5828 // type or a reference type.
5829 if (RequireCompleteType(ELoc, Type,
5830 diag::err_omp_firstprivate_incomplete_type)) {
5831 continue;
5832 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005833 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005834
5835 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5836 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00005837 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005838 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005839 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005840
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005841 // If an implicit firstprivate variable found it was checked already.
5842 if (!IsImplicitClause) {
5843 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005844 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005845 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5846 // A list item that specifies a given variable may not appear in more
5847 // than one clause on the same directive, except that a variable may be
5848 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005849 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00005850 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005851 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005852 << getOpenMPClauseName(DVar.CKind)
5853 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005854 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005855 continue;
5856 }
5857
5858 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5859 // in a Construct]
5860 // Variables with the predetermined data-sharing attributes may not be
5861 // listed in data-sharing attributes clauses, except for the cases
5862 // listed below. For these exceptions only, listing a predetermined
5863 // variable in a data-sharing attribute clause is allowed and overrides
5864 // the variable's predetermined data-sharing attributes.
5865 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5866 // in a Construct, C/C++, p.2]
5867 // Variables with const-qualified type having no mutable member may be
5868 // listed in a firstprivate clause, even if they are static data members.
5869 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5870 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
5871 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005872 << getOpenMPClauseName(DVar.CKind)
5873 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005874 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005875 continue;
5876 }
5877
Alexey Bataevf29276e2014-06-18 04:14:57 +00005878 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005879 // OpenMP [2.9.3.4, Restrictions, p.2]
5880 // A list item that is private within a parallel region must not appear
5881 // in a firstprivate clause on a worksharing construct if any of the
5882 // worksharing regions arising from the worksharing construct ever bind
5883 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00005884 if (isOpenMPWorksharingDirective(CurrDir) &&
5885 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005886 DVar = DSAStack->getImplicitDSA(VD, true);
5887 if (DVar.CKind != OMPC_shared &&
5888 (isOpenMPParallelDirective(DVar.DKind) ||
5889 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00005890 Diag(ELoc, diag::err_omp_required_access)
5891 << getOpenMPClauseName(OMPC_firstprivate)
5892 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005893 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00005894 continue;
5895 }
5896 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005897 // OpenMP [2.9.3.4, Restrictions, p.3]
5898 // A list item that appears in a reduction clause of a parallel construct
5899 // must not appear in a firstprivate clause on a worksharing or task
5900 // construct if any of the worksharing or task regions arising from the
5901 // worksharing or task construct ever bind to any of the parallel regions
5902 // arising from the parallel construct.
5903 // OpenMP [2.9.3.4, Restrictions, p.4]
5904 // A list item that appears in a reduction clause in worksharing
5905 // construct must not appear in a firstprivate clause in a task construct
5906 // encountered during execution of any of the worksharing regions arising
5907 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005908 if (CurrDir == OMPD_task) {
5909 DVar =
5910 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5911 [](OpenMPDirectiveKind K) -> bool {
5912 return isOpenMPParallelDirective(K) ||
5913 isOpenMPWorksharingDirective(K);
5914 },
5915 false);
5916 if (DVar.CKind == OMPC_reduction &&
5917 (isOpenMPParallelDirective(DVar.DKind) ||
5918 isOpenMPWorksharingDirective(DVar.DKind))) {
5919 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5920 << getOpenMPDirectiveName(DVar.DKind);
5921 ReportOriginalDSA(*this, DSAStack, VD, DVar);
5922 continue;
5923 }
5924 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005925 }
5926
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005927 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005928 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005929 DSAStack->getCurrentDirective() == OMPD_task) {
5930 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5931 << getOpenMPClauseName(OMPC_firstprivate) << Type
5932 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5933 bool IsDecl =
5934 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5935 Diag(VD->getLocation(),
5936 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5937 << VD;
5938 continue;
5939 }
5940
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005941 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00005942 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
5943 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005944 // Generate helper private variable and initialize it with the value of the
5945 // original variable. The address of the original variable is replaced by
5946 // the address of the new private variable in the CodeGen. This new variable
5947 // is not added to IdResolver, so the code in the OpenMP region uses
5948 // original variable for proper diagnostics and variable capturing.
5949 Expr *VDInitRefExpr = nullptr;
5950 // For arrays generate initializer for single element and replace it by the
5951 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005952 if (Type->isArrayType()) {
5953 auto VDInit =
5954 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5955 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005956 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005957 ElemType = ElemType.getUnqualifiedType();
5958 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5959 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00005960 InitializedEntity Entity =
5961 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005962 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5963
5964 InitializationSequence InitSeq(*this, Entity, Kind, Init);
5965 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5966 if (Result.isInvalid())
5967 VDPrivate->setInvalidDecl();
5968 else
5969 VDPrivate->setInit(Result.getAs<Expr>());
5970 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00005971 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00005972 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005973 VDInitRefExpr =
5974 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00005975 AddInitializerToDecl(VDPrivate,
5976 DefaultLvalueConversion(VDInitRefExpr).get(),
5977 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005978 }
5979 if (VDPrivate->isInvalidDecl()) {
5980 if (IsImplicitClause) {
5981 Diag(DE->getExprLoc(),
5982 diag::note_omp_task_predetermined_firstprivate_here);
5983 }
5984 continue;
5985 }
5986 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005987 auto VDPrivateRefExpr = buildDeclRefExpr(
5988 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005989 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5990 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005991 PrivateCopies.push_back(VDPrivateRefExpr);
5992 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005993 }
5994
Alexey Bataeved09d242014-05-28 05:53:51 +00005995 if (Vars.empty())
5996 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005997
5998 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005999 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006000}
6001
Alexander Musman1bb328c2014-06-04 13:06:39 +00006002OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
6003 SourceLocation StartLoc,
6004 SourceLocation LParenLoc,
6005 SourceLocation EndLoc) {
6006 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00006007 SmallVector<Expr *, 8> SrcExprs;
6008 SmallVector<Expr *, 8> DstExprs;
6009 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006010 for (auto &RefExpr : VarList) {
6011 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
6012 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6013 // It will be analyzed later.
6014 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006015 SrcExprs.push_back(nullptr);
6016 DstExprs.push_back(nullptr);
6017 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006018 continue;
6019 }
6020
6021 SourceLocation ELoc = RefExpr->getExprLoc();
6022 // OpenMP [2.1, C/C++]
6023 // A list item is a variable name.
6024 // OpenMP [2.14.3.5, Restrictions, p.1]
6025 // A variable that is part of another variable (as an array or structure
6026 // element) cannot appear in a lastprivate clause.
6027 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6028 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6029 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6030 continue;
6031 }
6032 Decl *D = DE->getDecl();
6033 VarDecl *VD = cast<VarDecl>(D);
6034
6035 QualType Type = VD->getType();
6036 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6037 // It will be analyzed later.
6038 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006039 SrcExprs.push_back(nullptr);
6040 DstExprs.push_back(nullptr);
6041 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006042 continue;
6043 }
6044
6045 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
6046 // A variable that appears in a lastprivate clause must not have an
6047 // incomplete type or a reference type.
6048 if (RequireCompleteType(ELoc, Type,
6049 diag::err_omp_lastprivate_incomplete_type)) {
6050 continue;
6051 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006052 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00006053
6054 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6055 // in a Construct]
6056 // Variables with the predetermined data-sharing attributes may not be
6057 // listed in data-sharing attributes clauses, except for the cases
6058 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006059 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006060 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
6061 DVar.CKind != OMPC_firstprivate &&
6062 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
6063 Diag(ELoc, diag::err_omp_wrong_dsa)
6064 << getOpenMPClauseName(DVar.CKind)
6065 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006066 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006067 continue;
6068 }
6069
Alexey Bataevf29276e2014-06-18 04:14:57 +00006070 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6071 // OpenMP [2.14.3.5, Restrictions, p.2]
6072 // A list item that is private within a parallel region, or that appears in
6073 // the reduction clause of a parallel construct, must not appear in a
6074 // lastprivate clause on a worksharing construct if any of the corresponding
6075 // worksharing regions ever binds to any of the corresponding parallel
6076 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006077 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00006078 if (isOpenMPWorksharingDirective(CurrDir) &&
6079 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006080 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006081 if (DVar.CKind != OMPC_shared) {
6082 Diag(ELoc, diag::err_omp_required_access)
6083 << getOpenMPClauseName(OMPC_lastprivate)
6084 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006085 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006086 continue;
6087 }
6088 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00006089 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00006090 // A variable of class type (or array thereof) that appears in a
6091 // lastprivate clause requires an accessible, unambiguous default
6092 // constructor for the class type, unless the list item is also specified
6093 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00006094 // A variable of class type (or array thereof) that appears in a
6095 // lastprivate clause requires an accessible, unambiguous copy assignment
6096 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00006097 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006098 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006099 Type.getUnqualifiedType(), ".lastprivate.src",
6100 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006101 auto *PseudoSrcExpr = buildDeclRefExpr(
6102 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006103 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006104 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
6105 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006106 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006107 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006108 // For arrays generate assignment operation for single element and replace
6109 // it by the original array element in CodeGen.
6110 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6111 PseudoDstExpr, PseudoSrcExpr);
6112 if (AssignmentOp.isInvalid())
6113 continue;
6114 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6115 /*DiscardedValue=*/true);
6116 if (AssignmentOp.isInvalid())
6117 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006118
Alexey Bataev39f915b82015-05-08 10:41:21 +00006119 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006120 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006121 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006122 SrcExprs.push_back(PseudoSrcExpr);
6123 DstExprs.push_back(PseudoDstExpr);
6124 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00006125 }
6126
6127 if (Vars.empty())
6128 return nullptr;
6129
6130 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00006131 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006132}
6133
Alexey Bataev758e55e2013-09-06 18:03:48 +00006134OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
6135 SourceLocation StartLoc,
6136 SourceLocation LParenLoc,
6137 SourceLocation EndLoc) {
6138 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00006139 for (auto &RefExpr : VarList) {
6140 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6141 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00006142 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006143 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006144 continue;
6145 }
6146
Alexey Bataeved09d242014-05-28 05:53:51 +00006147 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006148 // OpenMP [2.1, C/C++]
6149 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00006150 // OpenMP [2.14.3.2, Restrictions, p.1]
6151 // A variable that is part of another variable (as an array or structure
6152 // element) cannot appear in a shared unless it is a static data member
6153 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00006154 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006155 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006156 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006157 continue;
6158 }
6159 Decl *D = DE->getDecl();
6160 VarDecl *VD = cast<VarDecl>(D);
6161
6162 QualType Type = VD->getType();
6163 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6164 // It will be analyzed later.
6165 Vars.push_back(DE);
6166 continue;
6167 }
6168
6169 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6170 // in a Construct]
6171 // Variables with the predetermined data-sharing attributes may not be
6172 // listed in data-sharing attributes clauses, except for the cases
6173 // listed below. For these exceptions only, listing a predetermined
6174 // variable in a data-sharing attribute clause is allowed and overrides
6175 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006176 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00006177 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
6178 DVar.RefExpr) {
6179 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6180 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006181 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006182 continue;
6183 }
6184
6185 DSAStack->addDSA(VD, DE, OMPC_shared);
6186 Vars.push_back(DE);
6187 }
6188
Alexey Bataeved09d242014-05-28 05:53:51 +00006189 if (Vars.empty())
6190 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00006191
6192 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
6193}
6194
Alexey Bataevc5e02582014-06-16 07:08:35 +00006195namespace {
6196class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
6197 DSAStackTy *Stack;
6198
6199public:
6200 bool VisitDeclRefExpr(DeclRefExpr *E) {
6201 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006202 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006203 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
6204 return false;
6205 if (DVar.CKind != OMPC_unknown)
6206 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00006207 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006208 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006209 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006210 return true;
6211 return false;
6212 }
6213 return false;
6214 }
6215 bool VisitStmt(Stmt *S) {
6216 for (auto Child : S->children()) {
6217 if (Child && Visit(Child))
6218 return true;
6219 }
6220 return false;
6221 }
Alexey Bataev23b69422014-06-18 07:08:49 +00006222 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00006223};
Alexey Bataev23b69422014-06-18 07:08:49 +00006224} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00006225
6226OMPClause *Sema::ActOnOpenMPReductionClause(
6227 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
6228 SourceLocation ColonLoc, SourceLocation EndLoc,
6229 CXXScopeSpec &ReductionIdScopeSpec,
6230 const DeclarationNameInfo &ReductionId) {
6231 // TODO: Allow scope specification search when 'declare reduction' is
6232 // supported.
6233 assert(ReductionIdScopeSpec.isEmpty() &&
6234 "No support for scoped reduction identifiers yet.");
6235
6236 auto DN = ReductionId.getName();
6237 auto OOK = DN.getCXXOverloadedOperator();
6238 BinaryOperatorKind BOK = BO_Comma;
6239
6240 // OpenMP [2.14.3.6, reduction clause]
6241 // C
6242 // reduction-identifier is either an identifier or one of the following
6243 // operators: +, -, *, &, |, ^, && and ||
6244 // C++
6245 // reduction-identifier is either an id-expression or one of the following
6246 // operators: +, -, *, &, |, ^, && and ||
6247 // FIXME: Only 'min' and 'max' identifiers are supported for now.
6248 switch (OOK) {
6249 case OO_Plus:
6250 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006251 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006252 break;
6253 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006254 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006255 break;
6256 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006257 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006258 break;
6259 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006260 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006261 break;
6262 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006263 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006264 break;
6265 case OO_AmpAmp:
6266 BOK = BO_LAnd;
6267 break;
6268 case OO_PipePipe:
6269 BOK = BO_LOr;
6270 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006271 case OO_New:
6272 case OO_Delete:
6273 case OO_Array_New:
6274 case OO_Array_Delete:
6275 case OO_Slash:
6276 case OO_Percent:
6277 case OO_Tilde:
6278 case OO_Exclaim:
6279 case OO_Equal:
6280 case OO_Less:
6281 case OO_Greater:
6282 case OO_LessEqual:
6283 case OO_GreaterEqual:
6284 case OO_PlusEqual:
6285 case OO_MinusEqual:
6286 case OO_StarEqual:
6287 case OO_SlashEqual:
6288 case OO_PercentEqual:
6289 case OO_CaretEqual:
6290 case OO_AmpEqual:
6291 case OO_PipeEqual:
6292 case OO_LessLess:
6293 case OO_GreaterGreater:
6294 case OO_LessLessEqual:
6295 case OO_GreaterGreaterEqual:
6296 case OO_EqualEqual:
6297 case OO_ExclaimEqual:
6298 case OO_PlusPlus:
6299 case OO_MinusMinus:
6300 case OO_Comma:
6301 case OO_ArrowStar:
6302 case OO_Arrow:
6303 case OO_Call:
6304 case OO_Subscript:
6305 case OO_Conditional:
6306 case NUM_OVERLOADED_OPERATORS:
6307 llvm_unreachable("Unexpected reduction identifier");
6308 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006309 if (auto II = DN.getAsIdentifierInfo()) {
6310 if (II->isStr("max"))
6311 BOK = BO_GT;
6312 else if (II->isStr("min"))
6313 BOK = BO_LT;
6314 }
6315 break;
6316 }
6317 SourceRange ReductionIdRange;
6318 if (ReductionIdScopeSpec.isValid()) {
6319 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
6320 }
6321 ReductionIdRange.setEnd(ReductionId.getEndLoc());
6322 if (BOK == BO_Comma) {
6323 // Not allowed reduction identifier is found.
6324 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
6325 << ReductionIdRange;
6326 return nullptr;
6327 }
6328
6329 SmallVector<Expr *, 8> Vars;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006330 SmallVector<Expr *, 8> LHSs;
6331 SmallVector<Expr *, 8> RHSs;
6332 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006333 for (auto RefExpr : VarList) {
6334 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
6335 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6336 // It will be analyzed later.
6337 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006338 LHSs.push_back(nullptr);
6339 RHSs.push_back(nullptr);
6340 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006341 continue;
6342 }
6343
6344 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
6345 RefExpr->isInstantiationDependent() ||
6346 RefExpr->containsUnexpandedParameterPack()) {
6347 // It will be analyzed later.
6348 Vars.push_back(RefExpr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006349 LHSs.push_back(nullptr);
6350 RHSs.push_back(nullptr);
6351 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006352 continue;
6353 }
6354
6355 auto ELoc = RefExpr->getExprLoc();
6356 auto ERange = RefExpr->getSourceRange();
6357 // OpenMP [2.1, C/C++]
6358 // A list item is a variable or array section, subject to the restrictions
6359 // specified in Section 2.4 on page 42 and in each of the sections
6360 // describing clauses and directives for which a list appears.
6361 // OpenMP [2.14.3.3, Restrictions, p.1]
6362 // A variable that is part of another variable (as an array or
6363 // structure element) cannot appear in a private clause.
6364 auto DE = dyn_cast<DeclRefExpr>(RefExpr);
6365 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6366 Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
6367 continue;
6368 }
6369 auto D = DE->getDecl();
6370 auto VD = cast<VarDecl>(D);
6371 auto Type = VD->getType();
6372 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6373 // A variable that appears in a private clause must not have an incomplete
6374 // type or a reference type.
6375 if (RequireCompleteType(ELoc, Type,
6376 diag::err_omp_reduction_incomplete_type))
6377 continue;
6378 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6379 // Arrays may not appear in a reduction clause.
6380 if (Type.getNonReferenceType()->isArrayType()) {
6381 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
6382 bool IsDecl =
6383 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6384 Diag(VD->getLocation(),
6385 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6386 << VD;
6387 continue;
6388 }
6389 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6390 // A list item that appears in a reduction clause must not be
6391 // const-qualified.
6392 if (Type.getNonReferenceType().isConstant(Context)) {
6393 Diag(ELoc, diag::err_omp_const_variable)
6394 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
6395 bool IsDecl =
6396 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6397 Diag(VD->getLocation(),
6398 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6399 << VD;
6400 continue;
6401 }
6402 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
6403 // If a list-item is a reference type then it must bind to the same object
6404 // for all threads of the team.
6405 VarDecl *VDDef = VD->getDefinition();
6406 if (Type->isReferenceType() && VDDef) {
6407 DSARefChecker Check(DSAStack);
6408 if (Check.Visit(VDDef->getInit())) {
6409 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
6410 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
6411 continue;
6412 }
6413 }
6414 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6415 // The type of a list item that appears in a reduction clause must be valid
6416 // for the reduction-identifier. For a max or min reduction in C, the type
6417 // of the list item must be an allowed arithmetic data type: char, int,
6418 // float, double, or _Bool, possibly modified with long, short, signed, or
6419 // unsigned. For a max or min reduction in C++, the type of the list item
6420 // must be an allowed arithmetic data type: char, wchar_t, int, float,
6421 // double, or bool, possibly modified with long, short, signed, or unsigned.
6422 if ((BOK == BO_GT || BOK == BO_LT) &&
6423 !(Type->isScalarType() ||
6424 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
6425 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
6426 << getLangOpts().CPlusPlus;
6427 bool IsDecl =
6428 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6429 Diag(VD->getLocation(),
6430 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6431 << VD;
6432 continue;
6433 }
6434 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
6435 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
6436 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
6437 bool IsDecl =
6438 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6439 Diag(VD->getLocation(),
6440 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6441 << VD;
6442 continue;
6443 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006444 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6445 // in a Construct]
6446 // Variables with the predetermined data-sharing attributes may not be
6447 // listed in data-sharing attributes clauses, except for the cases
6448 // listed below. For these exceptions only, listing a predetermined
6449 // variable in a data-sharing attribute clause is allowed and overrides
6450 // the variable's predetermined data-sharing attributes.
6451 // OpenMP [2.14.3.6, Restrictions, p.3]
6452 // Any number of reduction clauses can be specified on the directive,
6453 // but a list item can appear only once in the reduction clauses for that
6454 // directive.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006455 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006456 if (DVar.CKind == OMPC_reduction) {
6457 Diag(ELoc, diag::err_omp_once_referenced)
6458 << getOpenMPClauseName(OMPC_reduction);
6459 if (DVar.RefExpr) {
6460 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
6461 }
6462 } else if (DVar.CKind != OMPC_unknown) {
6463 Diag(ELoc, diag::err_omp_wrong_dsa)
6464 << getOpenMPClauseName(DVar.CKind)
6465 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006466 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006467 continue;
6468 }
6469
6470 // OpenMP [2.14.3.6, Restrictions, p.1]
6471 // A list item that appears in a reduction clause of a worksharing
6472 // construct must be shared in the parallel regions to which any of the
6473 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf29276e2014-06-18 04:14:57 +00006474 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataev549210e2014-06-24 04:39:47 +00006475 if (isOpenMPWorksharingDirective(CurrDir) &&
6476 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006477 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006478 if (DVar.CKind != OMPC_shared) {
6479 Diag(ELoc, diag::err_omp_required_access)
6480 << getOpenMPClauseName(OMPC_reduction)
6481 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006482 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006483 continue;
6484 }
6485 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006486 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006487 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
6488 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6489 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
6490 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006491 // Add initializer for private variable.
6492 Expr *Init = nullptr;
6493 switch (BOK) {
6494 case BO_Add:
6495 case BO_Xor:
6496 case BO_Or:
6497 case BO_LOr:
6498 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
6499 if (Type->isScalarType() || Type->isAnyComplexType()) {
6500 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006501 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006502 break;
6503 case BO_Mul:
6504 case BO_LAnd:
6505 if (Type->isScalarType() || Type->isAnyComplexType()) {
6506 // '*' and '&&' reduction ops - initializer is '1'.
6507 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
6508 }
6509 break;
6510 case BO_And: {
6511 // '&' reduction op - initializer is '~0'.
6512 QualType OrigType = Type;
6513 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
6514 Type = ComplexTy->getElementType();
6515 }
6516 if (Type->isRealFloatingType()) {
6517 llvm::APFloat InitValue =
6518 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
6519 /*isIEEE=*/true);
6520 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6521 Type, ELoc);
6522 } else if (Type->isScalarType()) {
6523 auto Size = Context.getTypeSize(Type);
6524 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
6525 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
6526 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6527 }
6528 if (Init && OrigType->isAnyComplexType()) {
6529 // Init = 0xFFFF + 0xFFFFi;
6530 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
6531 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
6532 }
6533 Type = OrigType;
6534 break;
6535 }
6536 case BO_LT:
6537 case BO_GT: {
6538 // 'min' reduction op - initializer is 'Largest representable number in
6539 // the reduction list item type'.
6540 // 'max' reduction op - initializer is 'Least representable number in
6541 // the reduction list item type'.
6542 if (Type->isIntegerType() || Type->isPointerType()) {
6543 bool IsSigned = Type->hasSignedIntegerRepresentation();
6544 auto Size = Context.getTypeSize(Type);
6545 QualType IntTy =
6546 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
6547 llvm::APInt InitValue =
6548 (BOK != BO_LT)
6549 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
6550 : llvm::APInt::getMinValue(Size)
6551 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
6552 : llvm::APInt::getMaxValue(Size);
6553 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6554 if (Type->isPointerType()) {
6555 // Cast to pointer type.
6556 auto CastExpr = BuildCStyleCastExpr(
6557 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
6558 SourceLocation(), Init);
6559 if (CastExpr.isInvalid())
6560 continue;
6561 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006562 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006563 } else if (Type->isRealFloatingType()) {
6564 llvm::APFloat InitValue = llvm::APFloat::getLargest(
6565 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
6566 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6567 Type, ELoc);
6568 }
6569 break;
6570 }
6571 case BO_PtrMemD:
6572 case BO_PtrMemI:
6573 case BO_MulAssign:
6574 case BO_Div:
6575 case BO_Rem:
6576 case BO_Sub:
6577 case BO_Shl:
6578 case BO_Shr:
6579 case BO_LE:
6580 case BO_GE:
6581 case BO_EQ:
6582 case BO_NE:
6583 case BO_AndAssign:
6584 case BO_XorAssign:
6585 case BO_OrAssign:
6586 case BO_Assign:
6587 case BO_AddAssign:
6588 case BO_SubAssign:
6589 case BO_DivAssign:
6590 case BO_RemAssign:
6591 case BO_ShlAssign:
6592 case BO_ShrAssign:
6593 case BO_Comma:
6594 llvm_unreachable("Unexpected reduction operation");
6595 }
6596 if (Init) {
6597 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
6598 /*TypeMayContainAuto=*/false);
6599 } else {
6600 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
6601 }
6602 if (!RHSVD->hasInit()) {
6603 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
6604 << ReductionIdRange;
6605 bool IsDecl =
6606 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6607 Diag(VD->getLocation(),
6608 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6609 << VD;
6610 continue;
6611 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00006612 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
6613 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006614 ExprResult ReductionOp =
6615 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
6616 LHSDRE, RHSDRE);
6617 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00006618 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006619 ReductionOp =
6620 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6621 BO_Assign, LHSDRE, ReductionOp.get());
6622 } else {
6623 auto *ConditionalOp = new (Context) ConditionalOperator(
6624 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
6625 RHSDRE, Type, VK_LValue, OK_Ordinary);
6626 ReductionOp =
6627 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6628 BO_Assign, LHSDRE, ConditionalOp);
6629 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006630 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006631 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006632 if (ReductionOp.isInvalid())
6633 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006634
6635 DSAStack->addDSA(VD, DE, OMPC_reduction);
6636 Vars.push_back(DE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006637 LHSs.push_back(LHSDRE);
6638 RHSs.push_back(RHSDRE);
6639 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006640 }
6641
6642 if (Vars.empty())
6643 return nullptr;
6644
6645 return OMPReductionClause::Create(
6646 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006647 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
6648 RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006649}
6650
Alexey Bataev182227b2015-08-20 10:54:39 +00006651OMPClause *Sema::ActOnOpenMPLinearClause(
6652 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
6653 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
6654 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006655 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006656 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00006657 SmallVector<Expr *, 8> Inits;
Alexey Bataev182227b2015-08-20 10:54:39 +00006658 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
6659 LinKind == OMPC_LINEAR_unknown) {
6660 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
6661 LinKind = OMPC_LINEAR_val;
6662 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006663 for (auto &RefExpr : VarList) {
6664 assert(RefExpr && "NULL expr in OpenMP linear clause.");
6665 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006666 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006667 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006668 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006669 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006670 continue;
6671 }
6672
6673 // OpenMP [2.14.3.7, linear clause]
6674 // A list item that appears in a linear clause is subject to the private
6675 // clause semantics described in Section 2.14.3.3 on page 159 except as
6676 // noted. In addition, the value of the new list item on each iteration
6677 // of the associated loop(s) corresponds to the value of the original
6678 // list item before entering the construct plus the logical number of
6679 // the iteration times linear-step.
6680
Alexey Bataeved09d242014-05-28 05:53:51 +00006681 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00006682 // OpenMP [2.1, C/C++]
6683 // A list item is a variable name.
6684 // OpenMP [2.14.3.3, Restrictions, p.1]
6685 // A variable that is part of another variable (as an array or
6686 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00006687 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006688 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006689 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00006690 continue;
6691 }
6692
6693 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6694
6695 // OpenMP [2.14.3.7, linear clause]
6696 // A list-item cannot appear in more than one linear clause.
6697 // A list-item that appears in a linear clause cannot appear in any
6698 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006699 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00006700 if (DVar.RefExpr) {
6701 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6702 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006703 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00006704 continue;
6705 }
6706
6707 QualType QType = VD->getType();
6708 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
6709 // It will be analyzed later.
6710 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006711 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006712 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006713 continue;
6714 }
6715
6716 // A variable must not have an incomplete type or a reference type.
6717 if (RequireCompleteType(ELoc, QType,
6718 diag::err_omp_linear_incomplete_type)) {
6719 continue;
6720 }
Alexey Bataev1185e192015-08-20 12:15:57 +00006721 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
6722 !QType->isReferenceType()) {
6723 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
6724 << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
6725 continue;
6726 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006727 QType = QType.getNonReferenceType();
Alexander Musman8dba6642014-04-22 13:09:42 +00006728
6729 // A list item must not be const-qualified.
6730 if (QType.isConstant(Context)) {
6731 Diag(ELoc, diag::err_omp_const_variable)
6732 << getOpenMPClauseName(OMPC_linear);
6733 bool IsDecl =
6734 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6735 Diag(VD->getLocation(),
6736 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6737 << VD;
6738 continue;
6739 }
6740
6741 // A list item must be of integral or pointer type.
6742 QType = QType.getUnqualifiedType().getCanonicalType();
6743 const Type *Ty = QType.getTypePtrOrNull();
6744 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
6745 !Ty->isPointerType())) {
6746 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
6747 bool IsDecl =
6748 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6749 Diag(VD->getLocation(),
6750 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6751 << VD;
6752 continue;
6753 }
6754
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006755 // Build private copy of original var.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006756 auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
6757 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006758 auto *PrivateRef = buildDeclRefExpr(
6759 *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman3276a272015-03-21 10:12:56 +00006760 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006761 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00006762 Expr *InitExpr;
6763 if (LinKind == OMPC_LINEAR_uval)
6764 InitExpr = VD->getInit();
6765 else
6766 InitExpr = DE;
6767 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexander Musman3276a272015-03-21 10:12:56 +00006768 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006769 auto InitRef = buildDeclRefExpr(
6770 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00006771 DSAStack->addDSA(VD, DE, OMPC_linear);
6772 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006773 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00006774 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00006775 }
6776
6777 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006778 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00006779
6780 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00006781 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00006782 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6783 !Step->isInstantiationDependent() &&
6784 !Step->containsUnexpandedParameterPack()) {
6785 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006786 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00006787 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006788 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006789 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00006790
Alexander Musman3276a272015-03-21 10:12:56 +00006791 // Build var to save the step value.
6792 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006793 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00006794 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006795 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00006796 ExprResult CalcStep =
6797 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006798 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00006799
Alexander Musman8dba6642014-04-22 13:09:42 +00006800 // Warn about zero linear step (it would be probably better specified as
6801 // making corresponding variables 'const').
6802 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00006803 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
6804 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00006805 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
6806 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00006807 if (!IsConstant && CalcStep.isUsable()) {
6808 // Calculate the step beforehand instead of doing this on each iteration.
6809 // (This is not used if the number of iterations may be kfold-ed).
6810 CalcStepExpr = CalcStep.get();
6811 }
Alexander Musman8dba6642014-04-22 13:09:42 +00006812 }
6813
Alexey Bataev182227b2015-08-20 10:54:39 +00006814 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
6815 ColonLoc, EndLoc, Vars, Privates, Inits,
6816 StepExpr, CalcStepExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00006817}
6818
6819static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
6820 Expr *NumIterations, Sema &SemaRef,
6821 Scope *S) {
6822 // Walk the vars and build update/final expressions for the CodeGen.
6823 SmallVector<Expr *, 8> Updates;
6824 SmallVector<Expr *, 8> Finals;
6825 Expr *Step = Clause.getStep();
6826 Expr *CalcStep = Clause.getCalcStep();
6827 // OpenMP [2.14.3.7, linear clause]
6828 // If linear-step is not specified it is assumed to be 1.
6829 if (Step == nullptr)
6830 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6831 else if (CalcStep)
6832 Step = cast<BinaryOperator>(CalcStep)->getLHS();
6833 bool HasErrors = false;
6834 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006835 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00006836 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00006837 for (auto &RefExpr : Clause.varlists()) {
6838 Expr *InitExpr = *CurInit;
6839
6840 // Build privatized reference to the current linear var.
6841 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00006842 Expr *CapturedRef;
6843 if (LinKind == OMPC_LINEAR_uval)
6844 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
6845 else
6846 CapturedRef =
6847 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
6848 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
6849 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00006850
6851 // Build update: Var = InitExpr + IV * Step
6852 ExprResult Update =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006853 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexander Musman3276a272015-03-21 10:12:56 +00006854 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006855 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
6856 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00006857
6858 // Build final: Var = InitExpr + NumIterations * Step
6859 ExprResult Final =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006860 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataev39f915b82015-05-08 10:41:21 +00006861 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006862 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
6863 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00006864 if (!Update.isUsable() || !Final.isUsable()) {
6865 Updates.push_back(nullptr);
6866 Finals.push_back(nullptr);
6867 HasErrors = true;
6868 } else {
6869 Updates.push_back(Update.get());
6870 Finals.push_back(Final.get());
6871 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006872 ++CurInit, ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00006873 }
6874 Clause.setUpdates(Updates);
6875 Clause.setFinals(Finals);
6876 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00006877}
6878
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006879OMPClause *Sema::ActOnOpenMPAlignedClause(
6880 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
6881 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
6882
6883 SmallVector<Expr *, 8> Vars;
6884 for (auto &RefExpr : VarList) {
6885 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
6886 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6887 // It will be analyzed later.
6888 Vars.push_back(RefExpr);
6889 continue;
6890 }
6891
6892 SourceLocation ELoc = RefExpr->getExprLoc();
6893 // OpenMP [2.1, C/C++]
6894 // A list item is a variable name.
6895 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6896 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6897 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6898 continue;
6899 }
6900
6901 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6902
6903 // OpenMP [2.8.1, simd construct, Restrictions]
6904 // The type of list items appearing in the aligned clause must be
6905 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006906 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006907 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006908 const Type *Ty = QType.getTypePtrOrNull();
6909 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6910 !Ty->isPointerType())) {
6911 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6912 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6913 bool IsDecl =
6914 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6915 Diag(VD->getLocation(),
6916 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6917 << VD;
6918 continue;
6919 }
6920
6921 // OpenMP [2.8.1, simd construct, Restrictions]
6922 // A list-item cannot appear in more than one aligned clause.
6923 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6924 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6925 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6926 << getOpenMPClauseName(OMPC_aligned);
6927 continue;
6928 }
6929
6930 Vars.push_back(DE);
6931 }
6932
6933 // OpenMP [2.8.1, simd construct, Description]
6934 // The parameter of the aligned clause, alignment, must be a constant
6935 // positive integer expression.
6936 // If no optional parameter is specified, implementation-defined default
6937 // alignments for SIMD instructions on the target platforms are assumed.
6938 if (Alignment != nullptr) {
6939 ExprResult AlignResult =
6940 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6941 if (AlignResult.isInvalid())
6942 return nullptr;
6943 Alignment = AlignResult.get();
6944 }
6945 if (Vars.empty())
6946 return nullptr;
6947
6948 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6949 EndLoc, Vars, Alignment);
6950}
6951
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006952OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6953 SourceLocation StartLoc,
6954 SourceLocation LParenLoc,
6955 SourceLocation EndLoc) {
6956 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006957 SmallVector<Expr *, 8> SrcExprs;
6958 SmallVector<Expr *, 8> DstExprs;
6959 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00006960 for (auto &RefExpr : VarList) {
6961 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6962 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006963 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006964 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006965 SrcExprs.push_back(nullptr);
6966 DstExprs.push_back(nullptr);
6967 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006968 continue;
6969 }
6970
Alexey Bataeved09d242014-05-28 05:53:51 +00006971 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006972 // OpenMP [2.1, C/C++]
6973 // A list item is a variable name.
6974 // OpenMP [2.14.4.1, Restrictions, p.1]
6975 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00006976 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006977 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006978 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006979 continue;
6980 }
6981
6982 Decl *D = DE->getDecl();
6983 VarDecl *VD = cast<VarDecl>(D);
6984
6985 QualType Type = VD->getType();
6986 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6987 // It will be analyzed later.
6988 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00006989 SrcExprs.push_back(nullptr);
6990 DstExprs.push_back(nullptr);
6991 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006992 continue;
6993 }
6994
6995 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6996 // A list item that appears in a copyin clause must be threadprivate.
6997 if (!DSAStack->isThreadPrivate(VD)) {
6998 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00006999 << getOpenMPClauseName(OMPC_copyin)
7000 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007001 continue;
7002 }
7003
7004 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7005 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00007006 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007007 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007008 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007009 auto *SrcVD =
7010 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
7011 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007012 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007013 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
7014 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007015 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
7016 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007017 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007018 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007019 // For arrays generate assignment operation for single element and replace
7020 // it by the original array element in CodeGen.
7021 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7022 PseudoDstExpr, PseudoSrcExpr);
7023 if (AssignmentOp.isInvalid())
7024 continue;
7025 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7026 /*DiscardedValue=*/true);
7027 if (AssignmentOp.isInvalid())
7028 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007029
7030 DSAStack->addDSA(VD, DE, OMPC_copyin);
7031 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007032 SrcExprs.push_back(PseudoSrcExpr);
7033 DstExprs.push_back(PseudoDstExpr);
7034 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007035 }
7036
Alexey Bataeved09d242014-05-28 05:53:51 +00007037 if (Vars.empty())
7038 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007039
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007040 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7041 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007042}
7043
Alexey Bataevbae9a792014-06-27 10:37:06 +00007044OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7045 SourceLocation StartLoc,
7046 SourceLocation LParenLoc,
7047 SourceLocation EndLoc) {
7048 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00007049 SmallVector<Expr *, 8> SrcExprs;
7050 SmallVector<Expr *, 8> DstExprs;
7051 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007052 for (auto &RefExpr : VarList) {
7053 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
7054 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7055 // It will be analyzed later.
7056 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007057 SrcExprs.push_back(nullptr);
7058 DstExprs.push_back(nullptr);
7059 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007060 continue;
7061 }
7062
7063 SourceLocation ELoc = RefExpr->getExprLoc();
7064 // OpenMP [2.1, C/C++]
7065 // A list item is a variable name.
7066 // OpenMP [2.14.4.1, Restrictions, p.1]
7067 // A list item that appears in a copyin clause must be threadprivate.
7068 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7069 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7070 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7071 continue;
7072 }
7073
7074 Decl *D = DE->getDecl();
7075 VarDecl *VD = cast<VarDecl>(D);
7076
7077 QualType Type = VD->getType();
7078 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7079 // It will be analyzed later.
7080 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007081 SrcExprs.push_back(nullptr);
7082 DstExprs.push_back(nullptr);
7083 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007084 continue;
7085 }
7086
7087 // OpenMP [2.14.4.2, Restrictions, p.2]
7088 // A list item that appears in a copyprivate clause may not appear in a
7089 // private or firstprivate clause on the single construct.
7090 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007091 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007092 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
7093 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00007094 Diag(ELoc, diag::err_omp_wrong_dsa)
7095 << getOpenMPClauseName(DVar.CKind)
7096 << getOpenMPClauseName(OMPC_copyprivate);
7097 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7098 continue;
7099 }
7100
7101 // OpenMP [2.11.4.2, Restrictions, p.1]
7102 // All list items that appear in a copyprivate clause must be either
7103 // threadprivate or private in the enclosing context.
7104 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007105 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007106 if (DVar.CKind == OMPC_shared) {
7107 Diag(ELoc, diag::err_omp_required_access)
7108 << getOpenMPClauseName(OMPC_copyprivate)
7109 << "threadprivate or private in the enclosing context";
7110 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7111 continue;
7112 }
7113 }
7114 }
7115
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007116 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007117 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007118 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007119 << getOpenMPClauseName(OMPC_copyprivate) << Type
7120 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007121 bool IsDecl =
7122 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7123 Diag(VD->getLocation(),
7124 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7125 << VD;
7126 continue;
7127 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007128
Alexey Bataevbae9a792014-06-27 10:37:06 +00007129 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7130 // A variable of class type (or array thereof) that appears in a
7131 // copyin clause requires an accessible, unambiguous copy assignment
7132 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007133 Type = Context.getBaseElementType(Type.getNonReferenceType())
7134 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00007135 auto *SrcVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007136 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
7137 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007138 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007139 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00007140 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007141 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
7142 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007143 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007144 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00007145 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7146 PseudoDstExpr, PseudoSrcExpr);
7147 if (AssignmentOp.isInvalid())
7148 continue;
7149 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7150 /*DiscardedValue=*/true);
7151 if (AssignmentOp.isInvalid())
7152 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007153
7154 // No need to mark vars as copyprivate, they are already threadprivate or
7155 // implicitly private.
7156 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007157 SrcExprs.push_back(PseudoSrcExpr);
7158 DstExprs.push_back(PseudoDstExpr);
7159 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00007160 }
7161
7162 if (Vars.empty())
7163 return nullptr;
7164
Alexey Bataeva63048e2015-03-23 06:18:07 +00007165 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7166 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007167}
7168
Alexey Bataev6125da92014-07-21 11:26:11 +00007169OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
7170 SourceLocation StartLoc,
7171 SourceLocation LParenLoc,
7172 SourceLocation EndLoc) {
7173 if (VarList.empty())
7174 return nullptr;
7175
7176 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
7177}
Alexey Bataevdea47612014-07-23 07:46:59 +00007178
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007179OMPClause *
7180Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
7181 SourceLocation DepLoc, SourceLocation ColonLoc,
7182 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7183 SourceLocation LParenLoc, SourceLocation EndLoc) {
7184 if (DepKind == OMPC_DEPEND_unknown) {
7185 std::string Values;
7186 std::string Sep(", ");
7187 for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
7188 Values += "'";
7189 Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
7190 Values += "'";
7191 switch (i) {
7192 case OMPC_DEPEND_unknown - 2:
7193 Values += " or ";
7194 break;
7195 case OMPC_DEPEND_unknown - 1:
7196 break;
7197 default:
7198 Values += Sep;
7199 break;
7200 }
7201 }
7202 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
7203 << Values << getOpenMPClauseName(OMPC_depend);
7204 return nullptr;
7205 }
7206 SmallVector<Expr *, 8> Vars;
7207 for (auto &RefExpr : VarList) {
7208 assert(RefExpr && "NULL expr in OpenMP shared clause.");
7209 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7210 // It will be analyzed later.
7211 Vars.push_back(RefExpr);
7212 continue;
7213 }
7214
7215 SourceLocation ELoc = RefExpr->getExprLoc();
7216 // OpenMP [2.11.1.1, Restrictions, p.3]
7217 // A variable that is part of another variable (such as a field of a
7218 // structure) but is not an array element or an array section cannot appear
7219 // in a depend clause.
7220 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007221 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
7222 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
7223 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
7224 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
7225 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007226 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
7227 !ASE->getBase()->getType()->isArrayType())) {
7228 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
7229 << RefExpr->getSourceRange();
7230 continue;
7231 }
7232
7233 Vars.push_back(RefExpr->IgnoreParenImpCasts());
7234 }
7235
7236 if (Vars.empty())
7237 return nullptr;
7238
7239 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
7240 DepLoc, ColonLoc, Vars);
7241}
Michael Wonge710d542015-08-07 16:16:36 +00007242
7243OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
7244 SourceLocation LParenLoc,
7245 SourceLocation EndLoc) {
7246 Expr *ValExpr = Device;
7247 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7248 !ValExpr->isInstantiationDependent()) {
7249 SourceLocation Loc = ValExpr->getExprLoc();
7250 ExprResult Value = PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7251 if (Value.isInvalid())
7252 return nullptr;
7253
7254 // OpenMP [2.9.1, Restrictions]
7255 // The device expression must evaluate to a non-negative integer value.
7256 llvm::APSInt Result;
7257 if (Value.get()->isIntegerConstantExpr(Result, Context) &&
7258 Result.isSigned() && !Result.isStrictlyPositive()) {
7259 Diag(Loc, diag::err_omp_negative_expression_in_clause)
7260 << "device" << ValExpr->getSourceRange();
7261 return nullptr;
7262 }
7263 }
Michael Wonge710d542015-08-07 16:16:36 +00007264 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7265}