blob: 079f87aa868e7f2fd92e1b47755cc41b4867a83a [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 {
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +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
Kelvin Li0bff7af2015-11-23 05:32:03 +000080public:
81 struct MapInfo {
82 Expr *RefExpr;
83 };
84
Alexey Bataev758e55e2013-09-06 18:03:48 +000085private:
86 struct DSAInfo {
87 OpenMPClauseKind Attributes;
88 DeclRefExpr *RefExpr;
89 };
90 typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000091 typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
Alexey Bataev9c821032015-04-30 04:23:23 +000092 typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
Kelvin Li0bff7af2015-11-23 05:32:03 +000093 typedef llvm::SmallDenseMap<VarDecl *, MapInfo, 64> MappedDeclsTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000094
95 struct SharingMapTy {
96 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000097 AlignedMapTy AlignedMap;
Kelvin Li0bff7af2015-11-23 05:32:03 +000098 MappedDeclsTy MappedDecls;
Alexey Bataev9c821032015-04-30 04:23:23 +000099 LoopControlVariablesSetTy LCVSet;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000100 DefaultDataSharingAttributes DefaultAttr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000101 SourceLocation DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000102 OpenMPDirectiveKind Directive;
103 DeclarationNameInfo DirectiveName;
104 Scope *CurScope;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000105 SourceLocation ConstructLoc;
Alexey Bataev346265e2015-09-25 10:37:12 +0000106 /// \brief first argument (Expr *) contains optional argument of the
107 /// 'ordered' clause, the second one is true if the regions has 'ordered'
108 /// clause, false otherwise.
109 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000110 bool NowaitRegion;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000111 bool CancelRegion;
Alexey Bataev9c821032015-04-30 04:23:23 +0000112 unsigned CollapseNumber;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000113 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000114 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000115 Scope *CurScope, SourceLocation Loc)
Alexey Bataev9c821032015-04-30 04:23:23 +0000116 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000117 Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
Alexey Bataev346265e2015-09-25 10:37:12 +0000118 ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
Alexey Bataev25e5b442015-09-15 12:52:43 +0000119 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 SharingMapTy()
Alexey Bataev9c821032015-04-30 04:23:23 +0000121 : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
Alexey Bataevbae9a792014-06-27 10:37:06 +0000122 Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
Alexey Bataev346265e2015-09-25 10:37:12 +0000123 ConstructLoc(), OrderedRegion(), NowaitRegion(false),
Alexey Bataev25e5b442015-09-15 12:52:43 +0000124 CancelRegion(false), CollapseNumber(1), InnerTeamsRegionLoc() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000125 };
126
127 typedef SmallVector<SharingMapTy, 64> StackTy;
128
129 /// \brief Stack of used declaration and their data-sharing attributes.
130 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000131 /// \brief true, if check for DSA must be from parent directive, false, if
132 /// from current directive.
Alexey Bataevaac108a2015-06-23 04:51:00 +0000133 OpenMPClauseKind ClauseKindMode;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000134 Sema &SemaRef;
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000135 bool ForceCapturing;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136
137 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
138
139 DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000140
141 /// \brief Checks if the variable is a local for OpenMP region.
142 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000143
Alexey Bataev758e55e2013-09-06 18:03:48 +0000144public:
Alexey Bataevaac108a2015-06-23 04:51:00 +0000145 explicit DSAStackTy(Sema &S)
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000146 : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
147 ForceCapturing(false) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000148
Alexey Bataevaac108a2015-06-23 04:51:00 +0000149 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
150 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000151
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000152 bool isForceVarCapturing() const { return ForceCapturing; }
153 void setForceVarCapturing(bool V) { ForceCapturing = V; }
154
Alexey Bataev758e55e2013-09-06 18:03:48 +0000155 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000156 Scope *CurScope, SourceLocation Loc) {
157 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
158 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000159 }
160
161 void pop() {
162 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
163 Stack.pop_back();
164 }
165
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
169 DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
172 void addLoopControlVariable(VarDecl *D);
173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
175 bool isLoopControlVariable(VarDecl *D);
176
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177 /// \brief Adds explicit data sharing attribute to the specified declaration.
178 void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
179
Alexey Bataev758e55e2013-09-06 18:03:48 +0000180 /// \brief Returns data sharing attributes from top of the stack for the
181 /// specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000182 DSAVarData getTopDSA(VarDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000183 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000184 DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000185 /// \brief Checks if the specified variables has data-sharing attributes which
186 /// match specified \a CPred predicate in any directive which matches \a DPred
187 /// predicate.
188 template <class ClausesPredicate, class DirectivesPredicate>
189 DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000190 DirectivesPredicate DPred, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000191 /// \brief Checks if the specified variables has data-sharing attributes which
192 /// match specified \a CPred predicate in any innermost directive which
193 /// matches \a DPred predicate.
194 template <class ClausesPredicate, class DirectivesPredicate>
195 DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000196 DirectivesPredicate DPred,
197 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000198 /// \brief Checks if the specified variables has explicit data-sharing
199 /// attributes which match specified \a CPred predicate at the specified
200 /// OpenMP region.
201 bool hasExplicitDSA(VarDecl *D,
202 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
203 unsigned Level);
Samuel Antao4be30e92015-10-02 17:14:03 +0000204
205 /// \brief Returns true if the directive at level \Level matches in the
206 /// specified \a DPred predicate.
207 bool hasExplicitDirective(
208 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
209 unsigned Level);
210
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000211 /// \brief Finds a directive which matches specified \a DPred predicate.
212 template <class NamedDirectivesPredicate>
213 bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000214
Alexey Bataev758e55e2013-09-06 18:03:48 +0000215 /// \brief Returns currently analyzed directive.
216 OpenMPDirectiveKind getCurrentDirective() const {
217 return Stack.back().Directive;
218 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000219 /// \brief Returns parent directive.
220 OpenMPDirectiveKind getParentDirective() const {
221 if (Stack.size() > 2)
222 return Stack[Stack.size() - 2].Directive;
223 return OMPD_unknown;
224 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000225
226 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000227 void setDefaultDSANone(SourceLocation Loc) {
228 Stack.back().DefaultAttr = DSA_none;
229 Stack.back().DefaultAttrLoc = Loc;
230 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000231 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000232 void setDefaultDSAShared(SourceLocation Loc) {
233 Stack.back().DefaultAttr = DSA_shared;
234 Stack.back().DefaultAttrLoc = Loc;
235 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000236
237 DefaultDataSharingAttributes getDefaultDSA() const {
238 return Stack.back().DefaultAttr;
239 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000240 SourceLocation getDefaultDSALocation() const {
241 return Stack.back().DefaultAttrLoc;
242 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000243
Alexey Bataevf29276e2014-06-18 04:14:57 +0000244 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000245 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000246 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000247 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000248 }
249
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000250 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000251 void setOrderedRegion(bool IsOrdered, Expr *Param) {
252 Stack.back().OrderedRegion.setInt(IsOrdered);
253 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000254 }
255 /// \brief Returns true, if parent region is ordered (has associated
256 /// 'ordered' clause), false - otherwise.
257 bool isParentOrderedRegion() const {
258 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000259 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000260 return false;
261 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000262 /// \brief Returns optional parameter for the ordered region.
263 Expr *getParentOrderedRegionParam() const {
264 if (Stack.size() > 2)
265 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
266 return nullptr;
267 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000268 /// \brief Marks current region as nowait (it has a 'nowait' clause).
269 void setNowaitRegion(bool IsNowait = true) {
270 Stack.back().NowaitRegion = IsNowait;
271 }
272 /// \brief Returns true, if parent region is nowait (has associated
273 /// 'nowait' clause), false - otherwise.
274 bool isParentNowaitRegion() const {
275 if (Stack.size() > 2)
276 return Stack[Stack.size() - 2].NowaitRegion;
277 return false;
278 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000279 /// \brief Marks parent region as cancel region.
280 void setParentCancelRegion(bool Cancel = true) {
281 if (Stack.size() > 2)
282 Stack[Stack.size() - 2].CancelRegion =
283 Stack[Stack.size() - 2].CancelRegion || Cancel;
284 }
285 /// \brief Return true if current region has inner cancel construct.
286 bool isCancelRegion() const {
287 return Stack.back().CancelRegion;
288 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000289
Alexey Bataev9c821032015-04-30 04:23:23 +0000290 /// \brief Set collapse value for the region.
291 void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
292 /// \brief Return collapse value for region.
293 unsigned getCollapseNumber() const {
294 return Stack.back().CollapseNumber;
295 }
296
Alexey Bataev13314bf2014-10-09 04:18:56 +0000297 /// \brief Marks current target region as one with closely nested teams
298 /// region.
299 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
300 if (Stack.size() > 2)
301 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
302 }
303 /// \brief Returns true, if current region has closely nested teams region.
304 bool hasInnerTeamsRegion() const {
305 return getInnerTeamsRegionLoc().isValid();
306 }
307 /// \brief Returns location of the nested teams region (if any).
308 SourceLocation getInnerTeamsRegionLoc() const {
309 if (Stack.size() > 1)
310 return Stack.back().InnerTeamsRegionLoc;
311 return SourceLocation();
312 }
313
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000314 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000315 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000316 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000317
318 MapInfo getMapInfoForVar(VarDecl *VD) {
319 MapInfo VarMI = {0};
320 for (auto Cnt = Stack.size() - 1; Cnt > 0; --Cnt) {
321 if (Stack[Cnt].MappedDecls.count(VD)) {
322 VarMI = Stack[Cnt].MappedDecls[VD];
323 break;
324 }
325 }
326 return VarMI;
327 }
328
329 void addMapInfoForVar(VarDecl *VD, MapInfo MI) {
330 if (Stack.size() > 1) {
331 Stack.back().MappedDecls[VD] = MI;
332 }
333 }
334
335 MapInfo IsMappedInCurrentRegion(VarDecl *VD) {
336 assert(Stack.size() > 1 && "Target level is 0");
337 MapInfo VarMI = {0};
338 if (Stack.size() > 1 && Stack.back().MappedDecls.count(VD)) {
339 VarMI = Stack.back().MappedDecls[VD];
340 }
341 return VarMI;
342 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000343};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000344bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
345 return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000346 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000347}
Alexey Bataeved09d242014-05-28 05:53:51 +0000348} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000349
350DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
351 VarDecl *D) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000352 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000353 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000354 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000355 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
356 // in a region but not in construct]
357 // File-scope or namespace-scope variables referenced in called routines
358 // in the region are shared unless they appear in a threadprivate
359 // directive.
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000360 if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000361 DVar.CKind = OMPC_shared;
362
363 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
364 // in a region but not in construct]
365 // Variables with static storage duration that are declared in called
366 // routines in the region are shared.
367 if (D->hasGlobalStorage())
368 DVar.CKind = OMPC_shared;
369
Alexey Bataev758e55e2013-09-06 18:03:48 +0000370 return DVar;
371 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000372
Alexey Bataev758e55e2013-09-06 18:03:48 +0000373 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000374 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
375 // in a Construct, C/C++, predetermined, p.1]
376 // Variables with automatic storage duration that are declared in a scope
377 // inside the construct are private.
Alexey Bataevf29276e2014-06-18 04:14:57 +0000378 if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
379 (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
380 DVar.CKind = OMPC_private;
381 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000382 }
383
Alexey Bataev758e55e2013-09-06 18:03:48 +0000384 // Explicitly specified attributes and local variables with predetermined
385 // attributes.
386 if (Iter->SharingMap.count(D)) {
387 DVar.RefExpr = Iter->SharingMap[D].RefExpr;
388 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000389 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000390 return DVar;
391 }
392
393 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
394 // in a Construct, C/C++, implicitly determined, p.1]
395 // In a parallel or task construct, the data-sharing attributes of these
396 // variables are determined by the default clause, if present.
397 switch (Iter->DefaultAttr) {
398 case DSA_shared:
399 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000400 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000401 return DVar;
402 case DSA_none:
403 return DVar;
404 case DSA_unspecified:
405 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
406 // in a Construct, implicitly determined, p.2]
407 // In a parallel construct, if no default clause is present, these
408 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000409 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000410 if (isOpenMPParallelDirective(DVar.DKind) ||
411 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000412 DVar.CKind = OMPC_shared;
413 return DVar;
414 }
415
416 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
417 // in a Construct, implicitly determined, p.4]
418 // In a task construct, if no default clause is present, a variable that in
419 // the enclosing context is determined to be shared by all implicit tasks
420 // bound to the current team is shared.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000421 if (DVar.DKind == OMPD_task) {
422 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000423 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000424 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000425 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
426 // Referenced
Alexey Bataev758e55e2013-09-06 18:03:48 +0000427 // in a Construct, implicitly determined, p.6]
428 // In a task construct, if no default clause is present, a variable
429 // whose data-sharing attribute is not determined by the rules above is
430 // firstprivate.
431 DVarTemp = getDSA(I, D);
432 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000433 DVar.RefExpr = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000434 DVar.DKind = OMPD_task;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000435 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000436 return DVar;
437 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000438 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000439 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000440 }
441 DVar.DKind = OMPD_task;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000443 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000444 return DVar;
445 }
446 }
447 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
448 // in a Construct, implicitly determined, p.3]
449 // For constructs other than task, if no default clause is present, these
450 // variables inherit their data-sharing attributes from the enclosing
451 // context.
Benjamin Kramer167e9992014-03-02 12:20:24 +0000452 return getDSA(std::next(Iter), D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453}
454
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000455DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
456 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000457 D = D->getCanonicalDecl();
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000458 auto It = Stack.back().AlignedMap.find(D);
459 if (It == Stack.back().AlignedMap.end()) {
460 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
461 Stack.back().AlignedMap[D] = NewDE;
462 return nullptr;
463 } else {
464 assert(It->second && "Unexpected nullptr expr in the aligned map");
465 return It->second;
466 }
467 return nullptr;
468}
469
Alexey Bataev9c821032015-04-30 04:23:23 +0000470void DSAStackTy::addLoopControlVariable(VarDecl *D) {
471 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
472 D = D->getCanonicalDecl();
473 Stack.back().LCVSet.insert(D);
474}
475
476bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
477 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
478 D = D->getCanonicalDecl();
479 return Stack.back().LCVSet.count(D) > 0;
480}
481
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000483 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000484 if (A == OMPC_threadprivate) {
485 Stack[0].SharingMap[D].Attributes = A;
486 Stack[0].SharingMap[D].RefExpr = E;
487 } else {
488 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
489 Stack.back().SharingMap[D].Attributes = A;
490 Stack.back().SharingMap[D].RefExpr = E;
491 }
492}
493
Alexey Bataeved09d242014-05-28 05:53:51 +0000494bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000495 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000496 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000497 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000498 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000499 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000500 ++I;
501 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000502 if (I == E)
503 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000504 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000505 Scope *CurScope = getCurScope();
506 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000507 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000508 }
509 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000510 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000511 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000512}
513
Alexey Bataev39f915b82015-05-08 10:41:21 +0000514/// \brief Build a variable declaration for OpenMP loop iteration variable.
515static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000516 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000517 DeclContext *DC = SemaRef.CurContext;
518 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
519 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
520 VarDecl *Decl =
521 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000522 if (Attrs) {
523 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
524 I != E; ++I)
525 Decl->addAttr(*I);
526 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000527 Decl->setImplicit();
528 return Decl;
529}
530
531static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
532 SourceLocation Loc,
533 bool RefersToCapture = false) {
534 D->setReferenced();
535 D->markUsed(S.Context);
536 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
537 SourceLocation(), D, RefersToCapture, Loc, Ty,
538 VK_LValue);
539}
540
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000541DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000542 D = D->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000543 DSAVarData DVar;
544
545 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
546 // in a Construct, C/C++, predetermined, p.1]
547 // Variables appearing in threadprivate directives are threadprivate.
Samuel Antaof8b50122015-07-13 22:54:53 +0000548 if ((D->getTLSKind() != VarDecl::TLS_None &&
549 !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
550 SemaRef.getLangOpts().OpenMPUseTLS &&
551 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +0000552 (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
553 !D->isLocalVarDecl())) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000554 addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
555 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000556 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000557 }
558 if (Stack[0].SharingMap.count(D)) {
559 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
560 DVar.CKind = OMPC_threadprivate;
561 return DVar;
562 }
563
564 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
565 // in a Construct, C/C++, predetermined, p.1]
566 // Variables with automatic storage duration that are declared in a scope
567 // inside the construct are private.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000568 OpenMPDirectiveKind Kind =
569 FromParent ? getParentDirective() : getCurrentDirective();
570 auto StartI = std::next(Stack.rbegin());
571 auto EndI = std::prev(Stack.rend());
572 if (FromParent && StartI != EndI) {
573 StartI = std::next(StartI);
574 }
575 if (!isParallelOrTaskRegion(Kind)) {
Alexey Bataev8b9cb982014-07-24 02:33:58 +0000576 if (isOpenMPLocal(D, StartI) &&
577 ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
578 D->getStorageClass() == SC_None)) ||
579 isa<ParmVarDecl>(D))) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000580 DVar.CKind = OMPC_private;
581 return DVar;
Alexander Musman8dba6642014-04-22 13:09:42 +0000582 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000583
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000584 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
585 // in a Construct, C/C++, predetermined, p.4]
586 // Static data members are shared.
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000587 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
588 // in a Construct, C/C++, predetermined, p.7]
589 // Variables with static storage duration that are declared in a scope
590 // inside the construct are shared.
Kelvin Li4eea8c62015-09-15 18:56:58 +0000591 if (D->isStaticDataMember()) {
Alexey Bataev42971a32015-01-20 07:03:46 +0000592 DSAVarData DVarTemp =
593 hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
594 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
595 return DVar;
596
Alexey Bataev24b04aa2015-01-16 07:11:33 +0000597 DVar.CKind = OMPC_shared;
598 return DVar;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601
602 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000603 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
604 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000605 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
606 // in a Construct, C/C++, predetermined, p.6]
607 // Variables with const qualified type having no mutable member are
608 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000609 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000610 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000611 if (IsConstant &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000612 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000613 // Variables with const-qualified type having no mutable member may be
614 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000615 DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
616 MatchesAlways(), FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000617 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
618 return DVar;
619
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620 DVar.CKind = OMPC_shared;
621 return DVar;
622 }
623
Alexey Bataev758e55e2013-09-06 18:03:48 +0000624 // Explicitly specified attributes and local variables with predetermined
625 // attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000626 auto I = std::prev(StartI);
627 if (I->SharingMap.count(D)) {
628 DVar.RefExpr = I->SharingMap[D].RefExpr;
629 DVar.CKind = I->SharingMap[D].Attributes;
630 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000631 }
632
633 return DVar;
634}
635
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000636DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000637 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000638 auto StartI = Stack.rbegin();
639 auto EndI = std::prev(Stack.rend());
640 if (FromParent && StartI != EndI) {
641 StartI = std::next(StartI);
642 }
643 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000644}
645
Alexey Bataevf29276e2014-06-18 04:14:57 +0000646template <class ClausesPredicate, class DirectivesPredicate>
647DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000648 DirectivesPredicate DPred,
649 bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000650 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000651 auto StartI = std::next(Stack.rbegin());
652 auto EndI = std::prev(Stack.rend());
653 if (FromParent && StartI != EndI) {
654 StartI = std::next(StartI);
655 }
656 for (auto I = StartI, EE = EndI; I != EE; ++I) {
657 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000658 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000659 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000660 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000661 return DVar;
662 }
663 return DSAVarData();
664}
665
Alexey Bataevf29276e2014-06-18 04:14:57 +0000666template <class ClausesPredicate, class DirectivesPredicate>
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000667DSAStackTy::DSAVarData
668DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
669 DirectivesPredicate DPred, bool FromParent) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000670 D = D->getCanonicalDecl();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000671 auto StartI = std::next(Stack.rbegin());
672 auto EndI = std::prev(Stack.rend());
673 if (FromParent && StartI != EndI) {
674 StartI = std::next(StartI);
675 }
676 for (auto I = StartI, EE = EndI; I != EE; ++I) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000677 if (!DPred(I->Directive))
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000678 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +0000679 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000680 if (CPred(DVar.CKind))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000681 return DVar;
682 return DSAVarData();
683 }
684 return DSAVarData();
685}
686
Alexey Bataevaac108a2015-06-23 04:51:00 +0000687bool DSAStackTy::hasExplicitDSA(
688 VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
689 unsigned Level) {
690 if (CPred(ClauseKindMode))
691 return true;
692 if (isClauseParsingMode())
693 ++Level;
694 D = D->getCanonicalDecl();
695 auto StartI = Stack.rbegin();
696 auto EndI = std::prev(Stack.rend());
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000697 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000698 return false;
699 std::advance(StartI, Level);
700 return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
701 CPred(StartI->SharingMap[D].Attributes);
702}
703
Samuel Antao4be30e92015-10-02 17:14:03 +0000704bool DSAStackTy::hasExplicitDirective(
705 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
706 unsigned Level) {
707 if (isClauseParsingMode())
708 ++Level;
709 auto StartI = Stack.rbegin();
710 auto EndI = std::prev(Stack.rend());
711 if (std::distance(StartI, EndI) <= (int)Level)
712 return false;
713 std::advance(StartI, Level);
714 return DPred(StartI->Directive);
715}
716
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000717template <class NamedDirectivesPredicate>
718bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
719 auto StartI = std::next(Stack.rbegin());
720 auto EndI = std::prev(Stack.rend());
721 if (FromParent && StartI != EndI) {
722 StartI = std::next(StartI);
723 }
724 for (auto I = StartI, EE = EndI; I != EE; ++I) {
725 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
726 return true;
727 }
728 return false;
729}
730
Alexey Bataev758e55e2013-09-06 18:03:48 +0000731void Sema::InitDataSharingAttributesStack() {
732 VarDataSharingAttributesStack = new DSAStackTy(*this);
733}
734
735#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
736
Alexey Bataevf841bd92014-12-16 07:00:22 +0000737bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
738 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000739 VD = VD->getCanonicalDecl();
Samuel Antao4be30e92015-10-02 17:14:03 +0000740
741 // If we are attempting to capture a global variable in a directive with
742 // 'target' we return true so that this global is also mapped to the device.
743 //
744 // FIXME: If the declaration is enclosed in a 'declare target' directive,
745 // then it should not be captured. Therefore, an extra check has to be
746 // inserted here once support for 'declare target' is added.
747 //
748 if (!VD->hasLocalStorage()) {
749 if (DSAStack->getCurrentDirective() == OMPD_target &&
750 !DSAStack->isClauseParsingMode()) {
751 return true;
752 }
753 if (DSAStack->getCurScope() &&
754 DSAStack->hasDirective(
755 [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
756 SourceLocation Loc) -> bool {
757 return isOpenMPTargetDirective(K);
758 },
759 false)) {
760 return true;
761 }
762 }
763
Alexey Bataev48977c32015-08-04 08:10:48 +0000764 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
765 (!DSAStack->isClauseParsingMode() ||
766 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000767 if (DSAStack->isLoopControlVariable(VD) ||
768 (VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000769 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
770 DSAStack->isForceVarCapturing())
Alexey Bataev9c821032015-04-30 04:23:23 +0000771 return true;
Alexey Bataevaac108a2015-06-23 04:51:00 +0000772 auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000773 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
774 return true;
775 DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
Alexey Bataevaac108a2015-06-23 04:51:00 +0000776 DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +0000777 return DVarPrivate.CKind != OMPC_unknown;
778 }
779 return false;
780}
781
Alexey Bataevaac108a2015-06-23 04:51:00 +0000782bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
783 assert(LangOpts.OpenMP && "OpenMP is not allowed");
784 return DSAStack->hasExplicitDSA(
785 VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
786}
787
Samuel Antao4be30e92015-10-02 17:14:03 +0000788bool Sema::isOpenMPTargetCapturedVar(VarDecl *VD, unsigned Level) {
789 assert(LangOpts.OpenMP && "OpenMP is not allowed");
790 // Return true if the current level is no longer enclosed in a target region.
791
792 return !VD->hasLocalStorage() &&
793 DSAStack->hasExplicitDirective(isOpenMPTargetDirective, Level);
794}
795
Alexey Bataeved09d242014-05-28 05:53:51 +0000796void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000797
798void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
799 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000800 Scope *CurScope, SourceLocation Loc) {
801 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000802 PushExpressionEvaluationContext(PotentiallyEvaluated);
803}
804
Alexey Bataevaac108a2015-06-23 04:51:00 +0000805void Sema::StartOpenMPClause(OpenMPClauseKind K) {
806 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000807}
808
Alexey Bataevaac108a2015-06-23 04:51:00 +0000809void Sema::EndOpenMPClause() {
810 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +0000811}
812
Alexey Bataev758e55e2013-09-06 18:03:48 +0000813void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000814 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
815 // A variable of class type (or array thereof) that appears in a lastprivate
816 // clause requires an accessible, unambiguous default constructor for the
817 // class type, unless the list item is also specified in a firstprivate
818 // clause.
819 if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000820 for (auto *C : D->clauses()) {
821 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
822 SmallVector<Expr *, 8> PrivateCopies;
823 for (auto *DE : Clause->varlists()) {
824 if (DE->isValueDependent() || DE->isTypeDependent()) {
825 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000826 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +0000827 }
828 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
Alexey Bataevbd9fec12015-08-18 06:47:21 +0000829 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000830 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000831 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +0000832 // Generate helper private variable and initialize it with the
833 // default value. The address of the original variable is replaced
834 // by the address of the new private variable in CodeGen. This new
835 // variable is not added to IdResolver, so the code in the OpenMP
836 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000837 auto *VDPrivate = buildVarDecl(
838 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
839 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +0000840 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
841 if (VDPrivate->isInvalidDecl())
842 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000843 PrivateCopies.push_back(buildDeclRefExpr(
844 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +0000845 } else {
846 // The variable is also a firstprivate, so initialization sequence
847 // for private copy is generated already.
848 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000849 }
850 }
Alexey Bataev38e89532015-04-16 04:54:05 +0000851 // Set initializers to private copies if no errors were found.
852 if (PrivateCopies.size() == Clause->varlist_size()) {
853 Clause->setPrivateCopies(PrivateCopies);
854 }
Alexey Bataevf29276e2014-06-18 04:14:57 +0000855 }
856 }
857 }
858
Alexey Bataev758e55e2013-09-06 18:03:48 +0000859 DSAStack->pop();
860 DiscardCleanupsInEvaluationContext();
861 PopExpressionEvaluationContext();
862}
863
Alexander Musman3276a272015-03-21 10:12:56 +0000864static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
865 Expr *NumIterations, Sema &SemaRef,
866 Scope *S);
867
Alexey Bataeva769e072013-03-22 06:34:35 +0000868namespace {
869
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000870class VarDeclFilterCCC : public CorrectionCandidateCallback {
871private:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000872 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +0000873
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000874public:
Alexey Bataev7ff55242014-06-19 09:13:45 +0000875 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +0000876 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000877 NamedDecl *ND = Candidate.getCorrectionDecl();
878 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
879 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +0000880 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
881 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +0000882 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000883 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +0000884 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000885};
Alexey Bataeved09d242014-05-28 05:53:51 +0000886} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000887
888ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
889 CXXScopeSpec &ScopeSpec,
890 const DeclarationNameInfo &Id) {
891 LookupResult Lookup(*this, Id, LookupOrdinaryName);
892 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
893
894 if (Lookup.isAmbiguous())
895 return ExprError();
896
897 VarDecl *VD;
898 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000899 if (TypoCorrection Corrected = CorrectTypo(
900 Id, LookupOrdinaryName, CurScope, nullptr,
901 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000902 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000903 PDiag(Lookup.empty()
904 ? diag::err_undeclared_var_use_suggest
905 : diag::err_omp_expected_var_arg_suggest)
906 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +0000907 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000908 } else {
Richard Smithf9b15102013-08-17 00:46:16 +0000909 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
910 : diag::err_omp_expected_var_arg)
911 << Id.getName();
912 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000913 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000914 } else {
915 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000916 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000917 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
918 return ExprError();
919 }
920 }
921 Lookup.suppressDiagnostics();
922
923 // OpenMP [2.9.2, Syntax, C/C++]
924 // Variables must be file-scope, namespace-scope, or static block-scope.
925 if (!VD->hasGlobalStorage()) {
926 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +0000927 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
928 bool IsDecl =
929 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000930 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +0000931 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
932 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000933 return ExprError();
934 }
935
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000936 VarDecl *CanonicalVD = VD->getCanonicalDecl();
937 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000938 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
939 // A threadprivate directive for file-scope variables must appear outside
940 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000941 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
942 !getCurLexicalContext()->isTranslationUnit()) {
943 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000944 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
945 bool IsDecl =
946 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
947 Diag(VD->getLocation(),
948 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
949 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000950 return ExprError();
951 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000952 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
953 // A threadprivate directive for static class member variables must appear
954 // in the class definition, in the same scope in which the member
955 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000956 if (CanonicalVD->isStaticDataMember() &&
957 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
958 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000959 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
960 bool IsDecl =
961 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
962 Diag(VD->getLocation(),
963 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
964 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000965 return ExprError();
966 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000967 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
968 // A threadprivate directive for namespace-scope variables must appear
969 // outside any definition or declaration other than the namespace
970 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000971 if (CanonicalVD->getDeclContext()->isNamespace() &&
972 (!getCurLexicalContext()->isFileContext() ||
973 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
974 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000975 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
976 bool IsDecl =
977 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
978 Diag(VD->getLocation(),
979 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
980 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000981 return ExprError();
982 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000983 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
984 // A threadprivate directive for static block-scope variables must appear
985 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +0000986 if (CanonicalVD->isStaticLocal() && CurScope &&
987 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000988 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +0000989 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
990 bool IsDecl =
991 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
992 Diag(VD->getLocation(),
993 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
994 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +0000995 return ExprError();
996 }
997
998 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
999 // A threadprivate directive must lexically precede all references to any
1000 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001001 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001002 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001003 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001004 return ExprError();
1005 }
1006
1007 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00001008 ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001009 return DE;
1010}
1011
Alexey Bataeved09d242014-05-28 05:53:51 +00001012Sema::DeclGroupPtrTy
1013Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1014 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001015 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001016 CurContext->addDecl(D);
1017 return DeclGroupPtrTy::make(DeclGroupRef(D));
1018 }
1019 return DeclGroupPtrTy();
1020}
1021
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001022namespace {
1023class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1024 Sema &SemaRef;
1025
1026public:
1027 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1028 if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1029 if (VD->hasLocalStorage()) {
1030 SemaRef.Diag(E->getLocStart(),
1031 diag::err_omp_local_var_in_threadprivate_init)
1032 << E->getSourceRange();
1033 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1034 << VD << VD->getSourceRange();
1035 return true;
1036 }
1037 }
1038 return false;
1039 }
1040 bool VisitStmt(const Stmt *S) {
1041 for (auto Child : S->children()) {
1042 if (Child && Visit(Child))
1043 return true;
1044 }
1045 return false;
1046 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001047 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001048};
1049} // namespace
1050
Alexey Bataeved09d242014-05-28 05:53:51 +00001051OMPThreadPrivateDecl *
1052Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001053 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001054 for (auto &RefExpr : VarList) {
1055 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001056 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1057 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001058
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001059 QualType QType = VD->getType();
1060 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1061 // It will be analyzed later.
1062 Vars.push_back(DE);
1063 continue;
1064 }
1065
Alexey Bataeva769e072013-03-22 06:34:35 +00001066 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1067 // A threadprivate variable must not have an incomplete type.
1068 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001069 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001070 continue;
1071 }
1072
1073 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1074 // A threadprivate variable must not have a reference type.
1075 if (VD->getType()->isReferenceType()) {
1076 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001077 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1078 bool IsDecl =
1079 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1080 Diag(VD->getLocation(),
1081 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1082 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001083 continue;
1084 }
1085
Samuel Antaof8b50122015-07-13 22:54:53 +00001086 // Check if this is a TLS variable. If TLS is not being supported, produce
1087 // the corresponding diagnostic.
1088 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1089 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1090 getLangOpts().OpenMPUseTLS &&
1091 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001092 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1093 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001094 Diag(ILoc, diag::err_omp_var_thread_local)
1095 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001096 bool IsDecl =
1097 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1098 Diag(VD->getLocation(),
1099 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1100 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001101 continue;
1102 }
1103
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001104 // Check if initial value of threadprivate variable reference variable with
1105 // local storage (it is not supported by runtime).
1106 if (auto Init = VD->getAnyInitializer()) {
1107 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001108 if (Checker.Visit(Init))
1109 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001110 }
1111
Alexey Bataeved09d242014-05-28 05:53:51 +00001112 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001113 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001114 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1115 Context, SourceRange(Loc, Loc)));
1116 if (auto *ML = Context.getASTMutationListener())
1117 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001118 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001119 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001120 if (!Vars.empty()) {
1121 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1122 Vars);
1123 D->setAccess(AS_public);
1124 }
1125 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001126}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001127
Alexey Bataev7ff55242014-06-19 09:13:45 +00001128static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1129 const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1130 bool IsLoopIterVar = false) {
1131 if (DVar.RefExpr) {
1132 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1133 << getOpenMPClauseName(DVar.CKind);
1134 return;
1135 }
1136 enum {
1137 PDSA_StaticMemberShared,
1138 PDSA_StaticLocalVarShared,
1139 PDSA_LoopIterVarPrivate,
1140 PDSA_LoopIterVarLinear,
1141 PDSA_LoopIterVarLastprivate,
1142 PDSA_ConstVarShared,
1143 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001144 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001145 PDSA_LocalVarPrivate,
1146 PDSA_Implicit
1147 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001148 bool ReportHint = false;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001149 auto ReportLoc = VD->getLocation();
Alexey Bataev7ff55242014-06-19 09:13:45 +00001150 if (IsLoopIterVar) {
1151 if (DVar.CKind == OMPC_private)
1152 Reason = PDSA_LoopIterVarPrivate;
1153 else if (DVar.CKind == OMPC_lastprivate)
1154 Reason = PDSA_LoopIterVarLastprivate;
1155 else
1156 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001157 } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1158 Reason = PDSA_TaskVarFirstprivate;
1159 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001160 } else if (VD->isStaticLocal())
1161 Reason = PDSA_StaticLocalVarShared;
1162 else if (VD->isStaticDataMember())
1163 Reason = PDSA_StaticMemberShared;
1164 else if (VD->isFileVarDecl())
1165 Reason = PDSA_GlobalVarShared;
1166 else if (VD->getType().isConstant(SemaRef.getASTContext()))
1167 Reason = PDSA_ConstVarShared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001168 else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001169 ReportHint = true;
1170 Reason = PDSA_LocalVarPrivate;
1171 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001172 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001173 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001174 << Reason << ReportHint
1175 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1176 } else if (DVar.ImplicitDSALoc.isValid()) {
1177 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1178 << getOpenMPClauseName(DVar.CKind);
1179 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001180}
1181
Alexey Bataev758e55e2013-09-06 18:03:48 +00001182namespace {
1183class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1184 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001185 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001186 bool ErrorFound;
1187 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001188 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev4acb8592014-07-07 13:01:15 +00001189 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001190
Alexey Bataev758e55e2013-09-06 18:03:48 +00001191public:
1192 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001193 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001194 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1196 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001197
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001198 auto DVar = Stack->getTopDSA(VD, false);
1199 // Check if the variable has explicit DSA set and stop analysis if it so.
1200 if (DVar.RefExpr) return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001201
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001202 auto ELoc = E->getExprLoc();
1203 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001204 // The default(none) clause requires that each variable that is referenced
1205 // in the construct, and does not have a predetermined data-sharing
1206 // attribute, must have its data-sharing attribute explicitly determined
1207 // by being listed in a data-sharing attribute clause.
1208 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001209 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001210 VarsWithInheritedDSA.count(VD) == 0) {
1211 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001212 return;
1213 }
1214
1215 // OpenMP [2.9.3.6, Restrictions, p.2]
1216 // A list item that appears in a reduction clause of the innermost
1217 // enclosing worksharing or parallel construct may not be accessed in an
1218 // explicit task.
Alexey Bataevf29276e2014-06-18 04:14:57 +00001219 DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001220 [](OpenMPDirectiveKind K) -> bool {
1221 return isOpenMPParallelDirective(K) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001222 isOpenMPWorksharingDirective(K) ||
1223 isOpenMPTeamsDirective(K);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001224 },
1225 false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001226 if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1227 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001228 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1229 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001230 return;
1231 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001232
1233 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001234 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001235 if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001236 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001237 }
1238 }
1239 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001240 for (auto *C : S->clauses()) {
1241 // Skip analysis of arguments of implicitly defined firstprivate clause
1242 // for task directives.
1243 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1244 for (auto *CC : C->children()) {
1245 if (CC)
1246 Visit(CC);
1247 }
1248 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001249 }
1250 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001251 for (auto *C : S->children()) {
1252 if (C && !isa<OMPExecutableDirective>(C))
1253 Visit(C);
1254 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001255 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001256
1257 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001258 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001259 llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1260 return VarsWithInheritedDSA;
1261 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001262
Alexey Bataev7ff55242014-06-19 09:13:45 +00001263 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1264 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001265};
Alexey Bataeved09d242014-05-28 05:53:51 +00001266} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001267
Alexey Bataevbae9a792014-06-27 10:37:06 +00001268void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001269 switch (DKind) {
1270 case OMPD_parallel: {
1271 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001272 QualType KmpInt32PtrTy =
1273 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001274 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001275 std::make_pair(".global_tid.", KmpInt32PtrTy),
1276 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1277 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001278 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001279 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1280 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001281 break;
1282 }
1283 case OMPD_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001284 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001285 std::make_pair(StringRef(), QualType()) // __context with shared vars
1286 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001287 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1288 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001289 break;
1290 }
1291 case OMPD_for: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001292 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001293 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001294 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001295 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1296 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001297 break;
1298 }
Alexander Musmanf82886e2014-09-18 05:12:34 +00001299 case OMPD_for_simd: {
1300 Sema::CapturedParamNameType Params[] = {
1301 std::make_pair(StringRef(), QualType()) // __context with shared vars
1302 };
1303 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1304 Params);
1305 break;
1306 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001307 case OMPD_sections: {
1308 Sema::CapturedParamNameType Params[] = {
1309 std::make_pair(StringRef(), QualType()) // __context with shared vars
1310 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001311 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1312 Params);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00001313 break;
1314 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001315 case OMPD_section: {
1316 Sema::CapturedParamNameType Params[] = {
1317 std::make_pair(StringRef(), QualType()) // __context with shared vars
1318 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001319 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1320 Params);
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001321 break;
1322 }
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001323 case OMPD_single: {
1324 Sema::CapturedParamNameType Params[] = {
1325 std::make_pair(StringRef(), QualType()) // __context with shared vars
1326 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001327 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1328 Params);
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00001329 break;
1330 }
Alexander Musman80c22892014-07-17 08:54:58 +00001331 case OMPD_master: {
1332 Sema::CapturedParamNameType Params[] = {
1333 std::make_pair(StringRef(), QualType()) // __context with shared vars
1334 };
1335 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1336 Params);
1337 break;
1338 }
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001339 case OMPD_critical: {
1340 Sema::CapturedParamNameType Params[] = {
1341 std::make_pair(StringRef(), QualType()) // __context with shared vars
1342 };
1343 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1344 Params);
1345 break;
1346 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00001347 case OMPD_parallel_for: {
1348 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001349 QualType KmpInt32PtrTy =
1350 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev4acb8592014-07-07 13:01:15 +00001351 Sema::CapturedParamNameType Params[] = {
1352 std::make_pair(".global_tid.", KmpInt32PtrTy),
1353 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1354 std::make_pair(StringRef(), QualType()) // __context with shared vars
1355 };
1356 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1357 Params);
1358 break;
1359 }
Alexander Musmane4e893b2014-09-23 09:33:00 +00001360 case OMPD_parallel_for_simd: {
1361 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001362 QualType KmpInt32PtrTy =
1363 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexander Musmane4e893b2014-09-23 09:33:00 +00001364 Sema::CapturedParamNameType Params[] = {
1365 std::make_pair(".global_tid.", KmpInt32PtrTy),
1366 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1367 std::make_pair(StringRef(), QualType()) // __context with shared vars
1368 };
1369 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1370 Params);
1371 break;
1372 }
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001373 case OMPD_parallel_sections: {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001374 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001375 QualType KmpInt32PtrTy =
1376 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001377 Sema::CapturedParamNameType Params[] = {
Alexey Bataev68adb7d2015-04-14 03:29:22 +00001378 std::make_pair(".global_tid.", KmpInt32PtrTy),
1379 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001380 std::make_pair(StringRef(), QualType()) // __context with shared vars
1381 };
1382 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1383 Params);
1384 break;
1385 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001386 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001387 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001388 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1389 FunctionProtoType::ExtProtoInfo EPI;
1390 EPI.Variadic = true;
1391 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001392 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001393 std::make_pair(".global_tid.", KmpInt32Ty),
1394 std::make_pair(".part_id.", KmpInt32Ty),
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001395 std::make_pair(".privates.",
1396 Context.VoidPtrTy.withConst().withRestrict()),
1397 std::make_pair(
1398 ".copy_fn.",
1399 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001400 std::make_pair(StringRef(), QualType()) // __context with shared vars
1401 };
1402 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1403 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001404 // Mark this captured region as inlined, because we don't use outlined
1405 // function directly.
1406 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1407 AlwaysInlineAttr::CreateImplicit(
1408 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001409 break;
1410 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001411 case OMPD_ordered: {
1412 Sema::CapturedParamNameType Params[] = {
1413 std::make_pair(StringRef(), QualType()) // __context with shared vars
1414 };
1415 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1416 Params);
1417 break;
1418 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001419 case OMPD_atomic: {
1420 Sema::CapturedParamNameType Params[] = {
1421 std::make_pair(StringRef(), QualType()) // __context with shared vars
1422 };
1423 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1424 Params);
1425 break;
1426 }
Michael Wong65f367f2015-07-21 13:44:28 +00001427 case OMPD_target_data:
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001428 case OMPD_target: {
1429 Sema::CapturedParamNameType Params[] = {
1430 std::make_pair(StringRef(), QualType()) // __context with shared vars
1431 };
1432 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1433 Params);
1434 break;
1435 }
Alexey Bataev13314bf2014-10-09 04:18:56 +00001436 case OMPD_teams: {
1437 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001438 QualType KmpInt32PtrTy =
1439 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataev13314bf2014-10-09 04:18:56 +00001440 Sema::CapturedParamNameType Params[] = {
1441 std::make_pair(".global_tid.", KmpInt32PtrTy),
1442 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1443 std::make_pair(StringRef(), QualType()) // __context with shared vars
1444 };
1445 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1446 Params);
1447 break;
1448 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001449 case OMPD_taskgroup: {
1450 Sema::CapturedParamNameType Params[] = {
1451 std::make_pair(StringRef(), QualType()) // __context with shared vars
1452 };
1453 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1454 Params);
1455 break;
1456 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001457 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001458 case OMPD_taskyield:
1459 case OMPD_barrier:
1460 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001461 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001462 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001463 case OMPD_flush:
Alexey Bataev9959db52014-05-06 10:08:46 +00001464 llvm_unreachable("OpenMP Directive is not allowed");
1465 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001466 llvm_unreachable("Unknown OpenMP directive");
1467 }
1468}
1469
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001470StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1471 ArrayRef<OMPClause *> Clauses) {
1472 if (!S.isUsable()) {
1473 ActOnCapturedRegionError();
1474 return StmtError();
1475 }
Alexey Bataev040d5402015-05-12 08:35:28 +00001476 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001477 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001478 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001479 Clause->getClauseKind() == OMPC_copyprivate ||
1480 (getLangOpts().OpenMPUseTLS &&
1481 getASTContext().getTargetInfo().isTLSSupported() &&
1482 Clause->getClauseKind() == OMPC_copyin)) {
1483 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001484 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001485 for (auto *VarRef : Clause->children()) {
1486 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001487 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001488 }
1489 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001490 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev040d5402015-05-12 08:35:28 +00001491 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1492 Clause->getClauseKind() == OMPC_schedule) {
1493 // Mark all variables in private list clauses as used in inner region.
1494 // Required for proper codegen of combined directives.
1495 // TODO: add processing for other clauses.
1496 if (auto *E = cast_or_null<Expr>(
1497 cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1498 MarkDeclarationsReferencedInExpr(E);
1499 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001500 }
1501 }
1502 return ActOnCapturedRegionEnd(S.get());
1503}
1504
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001505static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1506 OpenMPDirectiveKind CurrentRegion,
1507 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001508 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001509 SourceLocation StartLoc) {
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001510 // Allowed nesting of constructs
1511 // +------------------+-----------------+------------------------------------+
1512 // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1513 // +------------------+-----------------+------------------------------------+
1514 // | parallel | parallel | * |
1515 // | parallel | for | * |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001516 // | parallel | for simd | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001517 // | parallel | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001518 // | parallel | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001519 // | parallel | simd | * |
1520 // | parallel | sections | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001521 // | parallel | section | + |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001522 // | parallel | single | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001523 // | parallel | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001524 // | parallel |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001525 // | parallel |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001526 // | parallel | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001527 // | parallel | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001528 // | parallel | barrier | * |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001529 // | parallel | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001530 // | parallel | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001531 // | parallel | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001532 // | parallel | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001533 // | parallel | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001534 // | parallel | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001535 // | parallel | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001536 // | parallel | cancellation | |
1537 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001538 // | parallel | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001539 // +------------------+-----------------+------------------------------------+
1540 // | for | parallel | * |
1541 // | for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001542 // | for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001543 // | for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001544 // | for | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001545 // | for | simd | * |
1546 // | for | sections | + |
1547 // | for | section | + |
1548 // | for | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001549 // | for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001550 // | for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001551 // | for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001552 // | for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001553 // | for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001554 // | for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001555 // | for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001556 // | for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001557 // | for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001558 // | for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001559 // | for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001560 // | for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001561 // | for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001562 // | for | cancellation | |
1563 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001564 // | for | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001565 // +------------------+-----------------+------------------------------------+
Alexander Musman80c22892014-07-17 08:54:58 +00001566 // | master | parallel | * |
1567 // | master | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001568 // | master | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001569 // | master | master | * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001570 // | master | critical | * |
Alexander Musman80c22892014-07-17 08:54:58 +00001571 // | master | simd | * |
1572 // | master | sections | + |
1573 // | master | section | + |
1574 // | master | single | + |
1575 // | master | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001576 // | master |parallel for simd| * |
Alexander Musman80c22892014-07-17 08:54:58 +00001577 // | master |parallel sections| * |
1578 // | master | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001579 // | master | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001580 // | master | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001581 // | master | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001582 // | master | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001583 // | master | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001584 // | master | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001585 // | master | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001586 // | master | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001587 // | master | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001588 // | master | cancellation | |
1589 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001590 // | master | cancel | |
Alexander Musman80c22892014-07-17 08:54:58 +00001591 // +------------------+-----------------+------------------------------------+
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001592 // | critical | parallel | * |
1593 // | critical | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001594 // | critical | for simd | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001595 // | critical | master | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001596 // | critical | critical | * (should have different names) |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001597 // | critical | simd | * |
1598 // | critical | sections | + |
1599 // | critical | section | + |
1600 // | critical | single | + |
1601 // | critical | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001602 // | critical |parallel for simd| * |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001603 // | critical |parallel sections| * |
1604 // | critical | task | * |
1605 // | critical | taskyield | * |
1606 // | critical | barrier | + |
1607 // | critical | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001608 // | critical | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001609 // | critical | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001610 // | critical | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001611 // | critical | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001612 // | critical | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001613 // | critical | cancellation | |
1614 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001615 // | critical | cancel | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001616 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001617 // | simd | parallel | |
1618 // | simd | for | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001619 // | simd | for simd | |
Alexander Musman80c22892014-07-17 08:54:58 +00001620 // | simd | master | |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001621 // | simd | critical | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001622 // | simd | simd | |
1623 // | simd | sections | |
1624 // | simd | section | |
1625 // | simd | single | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001626 // | simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001627 // | simd |parallel for simd| |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001628 // | simd |parallel sections| |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001629 // | simd | task | |
Alexey Bataev68446b72014-07-18 07:47:19 +00001630 // | simd | taskyield | |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001631 // | simd | barrier | |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001632 // | simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001633 // | simd | taskgroup | |
Alexey Bataev6125da92014-07-21 11:26:11 +00001634 // | simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001635 // | simd | ordered | + (with simd clause) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001636 // | simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001637 // | simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001638 // | simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001639 // | simd | cancellation | |
1640 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001641 // | simd | cancel | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001642 // +------------------+-----------------+------------------------------------+
Alexander Musmanf82886e2014-09-18 05:12:34 +00001643 // | for simd | parallel | |
1644 // | for simd | for | |
1645 // | for simd | for simd | |
1646 // | for simd | master | |
1647 // | for simd | critical | |
1648 // | for simd | simd | |
1649 // | for simd | sections | |
1650 // | for simd | section | |
1651 // | for simd | single | |
1652 // | for simd | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001653 // | for simd |parallel for simd| |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001654 // | for simd |parallel sections| |
1655 // | for simd | task | |
1656 // | for simd | taskyield | |
1657 // | for simd | barrier | |
1658 // | for simd | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001659 // | for simd | taskgroup | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001660 // | for simd | flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001661 // | for simd | ordered | + (with simd clause) |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001662 // | for simd | atomic | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001663 // | for simd | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001664 // | for simd | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001665 // | for simd | cancellation | |
1666 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001667 // | for simd | cancel | |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001668 // +------------------+-----------------+------------------------------------+
Alexander Musmane4e893b2014-09-23 09:33:00 +00001669 // | parallel for simd| parallel | |
1670 // | parallel for simd| for | |
1671 // | parallel for simd| for simd | |
1672 // | parallel for simd| master | |
1673 // | parallel for simd| critical | |
1674 // | parallel for simd| simd | |
1675 // | parallel for simd| sections | |
1676 // | parallel for simd| section | |
1677 // | parallel for simd| single | |
1678 // | parallel for simd| parallel for | |
1679 // | parallel for simd|parallel for simd| |
1680 // | parallel for simd|parallel sections| |
1681 // | parallel for simd| task | |
1682 // | parallel for simd| taskyield | |
1683 // | parallel for simd| barrier | |
1684 // | parallel for simd| taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001685 // | parallel for simd| taskgroup | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001686 // | parallel for simd| flush | |
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001687 // | parallel for simd| ordered | + (with simd clause) |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001688 // | parallel for simd| atomic | |
1689 // | parallel for simd| target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001690 // | parallel for simd| teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001691 // | parallel for simd| cancellation | |
1692 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001693 // | parallel for simd| cancel | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001694 // +------------------+-----------------+------------------------------------+
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001695 // | sections | parallel | * |
1696 // | sections | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001697 // | sections | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001698 // | sections | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001699 // | sections | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001700 // | sections | simd | * |
1701 // | sections | sections | + |
1702 // | sections | section | * |
1703 // | sections | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001704 // | sections | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001705 // | sections |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001706 // | sections |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001707 // | sections | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001708 // | sections | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001709 // | sections | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001710 // | sections | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001711 // | sections | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001712 // | sections | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001713 // | sections | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001714 // | sections | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001715 // | sections | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001716 // | sections | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001717 // | sections | cancellation | |
1718 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001719 // | sections | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001720 // +------------------+-----------------+------------------------------------+
1721 // | section | parallel | * |
1722 // | section | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001723 // | section | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001724 // | section | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001725 // | section | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001726 // | section | simd | * |
1727 // | section | sections | + |
1728 // | section | section | + |
1729 // | section | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001730 // | section | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001731 // | section |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001732 // | section |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001733 // | section | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001734 // | section | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001735 // | section | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001736 // | section | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001737 // | section | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001738 // | section | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001739 // | section | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001740 // | section | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001741 // | section | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001742 // | section | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001743 // | section | cancellation | |
1744 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001745 // | section | cancel | ! |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001746 // +------------------+-----------------+------------------------------------+
1747 // | single | parallel | * |
1748 // | single | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001749 // | single | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001750 // | single | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001751 // | single | critical | * |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001752 // | single | simd | * |
1753 // | single | sections | + |
1754 // | single | section | + |
1755 // | single | single | + |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001756 // | single | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001757 // | single |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001758 // | single |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001759 // | single | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001760 // | single | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001761 // | single | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001762 // | single | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001763 // | single | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001764 // | single | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001765 // | single | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001766 // | single | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001767 // | single | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001768 // | single | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001769 // | single | cancellation | |
1770 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001771 // | single | cancel | |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001772 // +------------------+-----------------+------------------------------------+
1773 // | parallel for | parallel | * |
1774 // | parallel for | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001775 // | parallel for | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001776 // | parallel for | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001777 // | parallel for | critical | * |
Alexey Bataev4acb8592014-07-07 13:01:15 +00001778 // | parallel for | simd | * |
1779 // | parallel for | sections | + |
1780 // | parallel for | section | + |
1781 // | parallel for | single | + |
1782 // | parallel for | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001783 // | parallel for |parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001784 // | parallel for |parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001785 // | parallel for | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001786 // | parallel for | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001787 // | parallel for | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001788 // | parallel for | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001789 // | parallel for | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001790 // | parallel for | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001791 // | parallel for | ordered | * (if construct is ordered) |
Alexey Bataev0162e452014-07-22 10:10:35 +00001792 // | parallel for | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001793 // | parallel for | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001794 // | parallel for | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001795 // | parallel for | cancellation | |
1796 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001797 // | parallel for | cancel | ! |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001798 // +------------------+-----------------+------------------------------------+
1799 // | parallel sections| parallel | * |
1800 // | parallel sections| for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001801 // | parallel sections| for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001802 // | parallel sections| master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001803 // | parallel sections| critical | + |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001804 // | parallel sections| simd | * |
1805 // | parallel sections| sections | + |
1806 // | parallel sections| section | * |
1807 // | parallel sections| single | + |
1808 // | parallel sections| parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001809 // | parallel sections|parallel for simd| * |
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001810 // | parallel sections|parallel sections| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001811 // | parallel sections| task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001812 // | parallel sections| taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001813 // | parallel sections| barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001814 // | parallel sections| taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001815 // | parallel sections| taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001816 // | parallel sections| flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001817 // | parallel sections| ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001818 // | parallel sections| atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001819 // | parallel sections| target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001820 // | parallel sections| teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001821 // | parallel sections| cancellation | |
1822 // | | point | ! |
Alexey Bataev80909872015-07-02 11:25:17 +00001823 // | parallel sections| cancel | ! |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001824 // +------------------+-----------------+------------------------------------+
1825 // | task | parallel | * |
1826 // | task | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001827 // | task | for simd | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001828 // | task | master | + |
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001829 // | task | critical | * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001830 // | task | simd | * |
1831 // | task | sections | + |
Alexander Musman80c22892014-07-17 08:54:58 +00001832 // | task | section | + |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001833 // | task | single | + |
1834 // | task | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001835 // | task |parallel for simd| * |
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001836 // | task |parallel sections| * |
1837 // | task | task | * |
Alexey Bataev68446b72014-07-18 07:47:19 +00001838 // | task | taskyield | * |
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001839 // | task | barrier | + |
Alexey Bataev2df347a2014-07-18 10:17:07 +00001840 // | task | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001841 // | task | taskgroup | * |
Alexey Bataev6125da92014-07-21 11:26:11 +00001842 // | task | flush | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001843 // | task | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001844 // | task | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001845 // | task | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001846 // | task | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001847 // | task | cancellation | |
Alexey Bataev80909872015-07-02 11:25:17 +00001848 // | | point | ! |
1849 // | task | cancel | ! |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001850 // +------------------+-----------------+------------------------------------+
1851 // | ordered | parallel | * |
1852 // | ordered | for | + |
Alexander Musmanf82886e2014-09-18 05:12:34 +00001853 // | ordered | for simd | + |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001854 // | ordered | master | * |
1855 // | ordered | critical | * |
1856 // | ordered | simd | * |
1857 // | ordered | sections | + |
1858 // | ordered | section | + |
1859 // | ordered | single | + |
1860 // | ordered | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001861 // | ordered |parallel for simd| * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001862 // | ordered |parallel sections| * |
1863 // | ordered | task | * |
1864 // | ordered | taskyield | * |
1865 // | ordered | barrier | + |
1866 // | ordered | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001867 // | ordered | taskgroup | * |
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001868 // | ordered | flush | * |
1869 // | ordered | ordered | + |
Alexey Bataev0162e452014-07-22 10:10:35 +00001870 // | ordered | atomic | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001871 // | ordered | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001872 // | ordered | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001873 // | ordered | cancellation | |
1874 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001875 // | ordered | cancel | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001876 // +------------------+-----------------+------------------------------------+
1877 // | atomic | parallel | |
1878 // | atomic | for | |
1879 // | atomic | for simd | |
1880 // | atomic | master | |
1881 // | atomic | critical | |
1882 // | atomic | simd | |
1883 // | atomic | sections | |
1884 // | atomic | section | |
1885 // | atomic | single | |
1886 // | atomic | parallel for | |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001887 // | atomic |parallel for simd| |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001888 // | atomic |parallel sections| |
1889 // | atomic | task | |
1890 // | atomic | taskyield | |
1891 // | atomic | barrier | |
1892 // | atomic | taskwait | |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001893 // | atomic | taskgroup | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001894 // | atomic | flush | |
1895 // | atomic | ordered | |
1896 // | atomic | atomic | |
1897 // | atomic | target | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001898 // | atomic | teams | |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001899 // | atomic | cancellation | |
1900 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001901 // | atomic | cancel | |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001902 // +------------------+-----------------+------------------------------------+
1903 // | target | parallel | * |
1904 // | target | for | * |
1905 // | target | for simd | * |
1906 // | target | master | * |
1907 // | target | critical | * |
1908 // | target | simd | * |
1909 // | target | sections | * |
1910 // | target | section | * |
1911 // | target | single | * |
1912 // | target | parallel for | * |
Alexander Musmane4e893b2014-09-23 09:33:00 +00001913 // | target |parallel for simd| * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001914 // | target |parallel sections| * |
1915 // | target | task | * |
1916 // | target | taskyield | * |
1917 // | target | barrier | * |
1918 // | target | taskwait | * |
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001919 // | target | taskgroup | * |
Alexey Bataev0bd520b2014-09-19 08:19:49 +00001920 // | target | flush | * |
1921 // | target | ordered | * |
1922 // | target | atomic | * |
1923 // | target | target | * |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001924 // | target | teams | * |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001925 // | target | cancellation | |
1926 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001927 // | target | cancel | |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001928 // +------------------+-----------------+------------------------------------+
1929 // | teams | parallel | * |
1930 // | teams | for | + |
1931 // | teams | for simd | + |
1932 // | teams | master | + |
1933 // | teams | critical | + |
1934 // | teams | simd | + |
1935 // | teams | sections | + |
1936 // | teams | section | + |
1937 // | teams | single | + |
1938 // | teams | parallel for | * |
1939 // | teams |parallel for simd| * |
1940 // | teams |parallel sections| * |
1941 // | teams | task | + |
1942 // | teams | taskyield | + |
1943 // | teams | barrier | + |
1944 // | teams | taskwait | + |
Alexey Bataev80909872015-07-02 11:25:17 +00001945 // | teams | taskgroup | + |
Alexey Bataev13314bf2014-10-09 04:18:56 +00001946 // | teams | flush | + |
1947 // | teams | ordered | + |
1948 // | teams | atomic | + |
1949 // | teams | target | + |
1950 // | teams | teams | + |
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001951 // | teams | cancellation | |
1952 // | | point | |
Alexey Bataev80909872015-07-02 11:25:17 +00001953 // | teams | cancel | |
Alexey Bataev18eb25e2014-06-30 10:22:46 +00001954 // +------------------+-----------------+------------------------------------+
Alexey Bataev549210e2014-06-24 04:39:47 +00001955 if (Stack->getCurScope()) {
1956 auto ParentRegion = Stack->getParentDirective();
1957 bool NestingProhibited = false;
1958 bool CloseNesting = true;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001959 enum {
1960 NoRecommend,
1961 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001962 ShouldBeInOrderedRegion,
1963 ShouldBeInTargetRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001964 } Recommend = NoRecommend;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001965 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001966 // OpenMP [2.16, Nesting of Regions]
1967 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001968 // OpenMP [2.8.1,simd Construct, Restrictions]
1969 // An ordered construct with the simd clause is the only OpenMP construct
1970 // that can appear in the simd region.
Alexey Bataev549210e2014-06-24 04:39:47 +00001971 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1972 return true;
1973 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001974 if (ParentRegion == OMPD_atomic) {
1975 // OpenMP [2.16, Nesting of Regions]
1976 // OpenMP constructs may not be nested inside an atomic region.
1977 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1978 return true;
1979 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001980 if (CurrentRegion == OMPD_section) {
1981 // OpenMP [2.7.2, sections Construct, Restrictions]
1982 // Orphaned section directives are prohibited. That is, the section
1983 // directives must appear within the sections construct and must not be
1984 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001985 if (ParentRegion != OMPD_sections &&
1986 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001987 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1988 << (ParentRegion != OMPD_unknown)
1989 << getOpenMPDirectiveName(ParentRegion);
1990 return true;
1991 }
1992 return false;
1993 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001994 // Allow some constructs to be orphaned (they could be used in functions,
1995 // called from OpenMP regions with the required preconditions).
1996 if (ParentRegion == OMPD_unknown)
1997 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001998 if (CurrentRegion == OMPD_cancellation_point ||
1999 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002000 // OpenMP [2.16, Nesting of Regions]
2001 // A cancellation point construct for which construct-type-clause is
2002 // taskgroup must be nested inside a task construct. A cancellation
2003 // point construct for which construct-type-clause is not taskgroup must
2004 // be closely nested inside an OpenMP construct that matches the type
2005 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002006 // A cancel construct for which construct-type-clause is taskgroup must be
2007 // nested inside a task construct. A cancel construct for which
2008 // construct-type-clause is not taskgroup must be closely nested inside an
2009 // OpenMP construct that matches the type specified in
2010 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002011 NestingProhibited =
2012 !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002013 (CancelRegion == OMPD_for &&
2014 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002015 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2016 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002017 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2018 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002019 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002020 // OpenMP [2.16, Nesting of Regions]
2021 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002022 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002023 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2024 ParentRegion == OMPD_task;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002025 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2026 // OpenMP [2.16, Nesting of Regions]
2027 // A critical region may not be nested (closely or otherwise) inside a
2028 // critical region with the same name. Note that this restriction is not
2029 // sufficient to prevent deadlock.
2030 SourceLocation PreviousCriticalLoc;
2031 bool DeadLock =
2032 Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2033 OpenMPDirectiveKind K,
2034 const DeclarationNameInfo &DNI,
2035 SourceLocation Loc)
2036 ->bool {
2037 if (K == OMPD_critical &&
2038 DNI.getName() == CurrentName.getName()) {
2039 PreviousCriticalLoc = Loc;
2040 return true;
2041 } else
2042 return false;
2043 },
2044 false /* skip top directive */);
2045 if (DeadLock) {
2046 SemaRef.Diag(StartLoc,
2047 diag::err_omp_prohibited_region_critical_same_name)
2048 << CurrentName.getName();
2049 if (PreviousCriticalLoc.isValid())
2050 SemaRef.Diag(PreviousCriticalLoc,
2051 diag::note_omp_previous_critical_region);
2052 return true;
2053 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002054 } else if (CurrentRegion == OMPD_barrier) {
2055 // OpenMP [2.16, Nesting of Regions]
2056 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002057 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002058 NestingProhibited =
2059 isOpenMPWorksharingDirective(ParentRegion) ||
2060 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2061 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002062 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Alexander Musmanf82886e2014-09-18 05:12:34 +00002063 !isOpenMPParallelDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002064 // OpenMP [2.16, Nesting of Regions]
2065 // A worksharing region may not be closely nested inside a worksharing,
2066 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002067 NestingProhibited =
Alexander Musmanf82886e2014-09-18 05:12:34 +00002068 isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002069 ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2070 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
2071 Recommend = ShouldBeInParallelRegion;
2072 } else if (CurrentRegion == OMPD_ordered) {
2073 // OpenMP [2.16, Nesting of Regions]
2074 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002075 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002076 // An ordered region must be closely nested inside a loop region (or
2077 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002078 // OpenMP [2.8.1,simd Construct, Restrictions]
2079 // An ordered construct with the simd clause is the only OpenMP construct
2080 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002081 NestingProhibited = ParentRegion == OMPD_critical ||
Alexander Musman80c22892014-07-17 08:54:58 +00002082 ParentRegion == OMPD_task ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002083 !(isOpenMPSimdDirective(ParentRegion) ||
2084 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002085 Recommend = ShouldBeInOrderedRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002086 } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2087 // OpenMP [2.16, Nesting of Regions]
2088 // If specified, a teams construct must be contained within a target
2089 // construct.
2090 NestingProhibited = ParentRegion != OMPD_target;
2091 Recommend = ShouldBeInTargetRegion;
2092 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2093 }
2094 if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2095 // OpenMP [2.16, Nesting of Regions]
2096 // distribute, parallel, parallel sections, parallel workshare, and the
2097 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2098 // constructs that can be closely nested in the teams region.
2099 // TODO: add distribute directive.
2100 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
2101 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002102 }
2103 if (NestingProhibited) {
2104 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002105 << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
2106 << getOpenMPDirectiveName(CurrentRegion);
Alexey Bataev549210e2014-06-24 04:39:47 +00002107 return true;
2108 }
2109 }
2110 return false;
2111}
2112
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002113static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2114 ArrayRef<OMPClause *> Clauses,
2115 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2116 bool ErrorFound = false;
2117 unsigned NamedModifiersNumber = 0;
2118 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2119 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002120 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002121 for (const auto *C : Clauses) {
2122 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2123 // At most one if clause without a directive-name-modifier can appear on
2124 // the directive.
2125 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2126 if (FoundNameModifiers[CurNM]) {
2127 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2128 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2129 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2130 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002131 } else if (CurNM != OMPD_unknown) {
2132 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002133 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002134 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002135 FoundNameModifiers[CurNM] = IC;
2136 if (CurNM == OMPD_unknown)
2137 continue;
2138 // Check if the specified name modifier is allowed for the current
2139 // directive.
2140 // At most one if clause with the particular directive-name-modifier can
2141 // appear on the directive.
2142 bool MatchFound = false;
2143 for (auto NM : AllowedNameModifiers) {
2144 if (CurNM == NM) {
2145 MatchFound = true;
2146 break;
2147 }
2148 }
2149 if (!MatchFound) {
2150 S.Diag(IC->getNameModifierLoc(),
2151 diag::err_omp_wrong_if_directive_name_modifier)
2152 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2153 ErrorFound = true;
2154 }
2155 }
2156 }
2157 // If any if clause on the directive includes a directive-name-modifier then
2158 // all if clauses on the directive must include a directive-name-modifier.
2159 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2160 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2161 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2162 diag::err_omp_no_more_if_clause);
2163 } else {
2164 std::string Values;
2165 std::string Sep(", ");
2166 unsigned AllowedCnt = 0;
2167 unsigned TotalAllowedNum =
2168 AllowedNameModifiers.size() - NamedModifiersNumber;
2169 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2170 ++Cnt) {
2171 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2172 if (!FoundNameModifiers[NM]) {
2173 Values += "'";
2174 Values += getOpenMPDirectiveName(NM);
2175 Values += "'";
2176 if (AllowedCnt + 2 == TotalAllowedNum)
2177 Values += " or ";
2178 else if (AllowedCnt + 1 != TotalAllowedNum)
2179 Values += Sep;
2180 ++AllowedCnt;
2181 }
2182 }
2183 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2184 diag::err_omp_unnamed_if_clause)
2185 << (TotalAllowedNum > 1) << Values;
2186 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002187 for (auto Loc : NameModifierLoc) {
2188 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2189 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002190 ErrorFound = true;
2191 }
2192 return ErrorFound;
2193}
2194
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002195StmtResult Sema::ActOnOpenMPExecutableDirective(
2196 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2197 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2198 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002199 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002200 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2201 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002202 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002203
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002204 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev68446b72014-07-18 07:47:19 +00002205 llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002206 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002207 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002208 if (AStmt) {
2209 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2210
2211 // Check default data sharing attributes for referenced variables.
2212 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2213 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2214 if (DSAChecker.isErrorFound())
2215 return StmtError();
2216 // Generate list of implicitly defined firstprivate variables.
2217 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002218
2219 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2220 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2221 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2222 SourceLocation(), SourceLocation())) {
2223 ClausesWithImplicit.push_back(Implicit);
2224 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2225 DSAChecker.getImplicitFirstprivate().size();
2226 } else
2227 ErrorFound = true;
2228 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002229 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002230
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002231 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002232 switch (Kind) {
2233 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002234 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2235 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002236 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002237 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002238 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002239 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2240 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002241 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002242 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002243 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2244 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002245 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002246 case OMPD_for_simd:
2247 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2248 EndLoc, VarsWithInheritedDSA);
2249 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002250 case OMPD_sections:
2251 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2252 EndLoc);
2253 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002254 case OMPD_section:
2255 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002256 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002257 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2258 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002259 case OMPD_single:
2260 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2261 EndLoc);
2262 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002263 case OMPD_master:
2264 assert(ClausesWithImplicit.empty() &&
2265 "No clauses are allowed for 'omp master' directive");
2266 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2267 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002268 case OMPD_critical:
2269 assert(ClausesWithImplicit.empty() &&
2270 "No clauses are allowed for 'omp critical' directive");
2271 Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
2272 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002273 case OMPD_parallel_for:
2274 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2275 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002276 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002277 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002278 case OMPD_parallel_for_simd:
2279 Res = ActOnOpenMPParallelForSimdDirective(
2280 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002281 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002282 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002283 case OMPD_parallel_sections:
2284 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2285 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002286 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002287 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002288 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002289 Res =
2290 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002291 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002292 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002293 case OMPD_taskyield:
2294 assert(ClausesWithImplicit.empty() &&
2295 "No clauses are allowed for 'omp taskyield' directive");
2296 assert(AStmt == nullptr &&
2297 "No associated statement allowed for 'omp taskyield' directive");
2298 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2299 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002300 case OMPD_barrier:
2301 assert(ClausesWithImplicit.empty() &&
2302 "No clauses are allowed for 'omp barrier' directive");
2303 assert(AStmt == nullptr &&
2304 "No associated statement allowed for 'omp barrier' directive");
2305 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2306 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002307 case OMPD_taskwait:
2308 assert(ClausesWithImplicit.empty() &&
2309 "No clauses are allowed for 'omp taskwait' directive");
2310 assert(AStmt == nullptr &&
2311 "No associated statement allowed for 'omp taskwait' directive");
2312 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2313 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002314 case OMPD_taskgroup:
2315 assert(ClausesWithImplicit.empty() &&
2316 "No clauses are allowed for 'omp taskgroup' directive");
2317 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2318 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002319 case OMPD_flush:
2320 assert(AStmt == nullptr &&
2321 "No associated statement allowed for 'omp flush' directive");
2322 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2323 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002324 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002325 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2326 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002327 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002328 case OMPD_atomic:
2329 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2330 EndLoc);
2331 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002332 case OMPD_teams:
2333 Res =
2334 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2335 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002336 case OMPD_target:
2337 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2338 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002339 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002340 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002341 case OMPD_cancellation_point:
2342 assert(ClausesWithImplicit.empty() &&
2343 "No clauses are allowed for 'omp cancellation point' directive");
2344 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2345 "cancellation point' directive");
2346 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2347 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002348 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002349 assert(AStmt == nullptr &&
2350 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002351 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2352 CancelRegion);
2353 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002354 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002355 case OMPD_target_data:
2356 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2357 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002358 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002359 break;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002360 case OMPD_threadprivate:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002361 llvm_unreachable("OpenMP Directive is not allowed");
2362 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002363 llvm_unreachable("Unknown OpenMP directive");
2364 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002365
Alexey Bataev4acb8592014-07-07 13:01:15 +00002366 for (auto P : VarsWithInheritedDSA) {
2367 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2368 << P.first << P.second->getSourceRange();
2369 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002370 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2371
2372 if (!AllowedNameModifiers.empty())
2373 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2374 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002375
Alexey Bataeved09d242014-05-28 05:53:51 +00002376 if (ErrorFound)
2377 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002378 return Res;
2379}
2380
2381StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2382 Stmt *AStmt,
2383 SourceLocation StartLoc,
2384 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002385 if (!AStmt)
2386 return StmtError();
2387
Alexey Bataev9959db52014-05-06 10:08:46 +00002388 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2389 // 1.2.2 OpenMP Language Terminology
2390 // Structured block - An executable statement with a single entry at the
2391 // top and a single exit at the bottom.
2392 // The point of exit cannot be a branch out of the structured block.
2393 // longjmp() and throw() must not violate the entry/exit criteria.
2394 CS->getCapturedDecl()->setNothrow();
2395
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002396 getCurFunction()->setHasBranchProtectedScope();
2397
Alexey Bataev25e5b442015-09-15 12:52:43 +00002398 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2399 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002400}
2401
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002402namespace {
2403/// \brief Helper class for checking canonical form of the OpenMP loops and
2404/// extracting iteration space of each loop in the loop nest, that will be used
2405/// for IR generation.
2406class OpenMPIterationSpaceChecker {
2407 /// \brief Reference to Sema.
2408 Sema &SemaRef;
2409 /// \brief A location for diagnostics (when there is no some better location).
2410 SourceLocation DefaultLoc;
2411 /// \brief A location for diagnostics (when increment is not compatible).
2412 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002413 /// \brief A source location for referring to loop init later.
2414 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002415 /// \brief A source location for referring to condition later.
2416 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002417 /// \brief A source location for referring to increment later.
2418 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002419 /// \brief Loop variable.
2420 VarDecl *Var;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002421 /// \brief Reference to loop variable.
2422 DeclRefExpr *VarRef;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002423 /// \brief Lower bound (initializer for the var).
2424 Expr *LB;
2425 /// \brief Upper bound.
2426 Expr *UB;
2427 /// \brief Loop step (increment).
2428 Expr *Step;
2429 /// \brief This flag is true when condition is one of:
2430 /// Var < UB
2431 /// Var <= UB
2432 /// UB > Var
2433 /// UB >= Var
2434 bool TestIsLessOp;
2435 /// \brief This flag is true when condition is strict ( < or > ).
2436 bool TestIsStrictOp;
2437 /// \brief This flag is true when step is subtracted on each iteration.
2438 bool SubtractStep;
2439
2440public:
2441 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2442 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
Alexander Musmana5f070a2014-10-01 06:03:56 +00002443 InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2444 IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002445 LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2446 TestIsStrictOp(false), SubtractStep(false) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002447 /// \brief Check init-expr for canonical loop form and save loop counter
2448 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002449 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002450 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2451 /// for less/greater and for strict/non-strict comparison.
2452 bool CheckCond(Expr *S);
2453 /// \brief Check incr-expr for canonical loop form and return true if it
2454 /// does not conform, otherwise save loop step (#Step).
2455 bool CheckInc(Expr *S);
2456 /// \brief Return the loop counter variable.
2457 VarDecl *GetLoopVar() const { return Var; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002458 /// \brief Return the reference expression to loop counter variable.
2459 DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002460 /// \brief Source range of the loop init.
2461 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2462 /// \brief Source range of the loop condition.
2463 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2464 /// \brief Source range of the loop increment.
2465 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2466 /// \brief True if the step should be subtracted.
2467 bool ShouldSubtractStep() const { return SubtractStep; }
2468 /// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002469 Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002470 /// \brief Build the precondition expression for the loops.
2471 Expr *BuildPreCond(Scope *S, Expr *Cond) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002472 /// \brief Build reference expression to the counter be used for codegen.
2473 Expr *BuildCounterVar() const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002474 /// \brief Build reference expression to the private counter be used for
2475 /// codegen.
2476 Expr *BuildPrivateCounterVar() const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002477 /// \brief Build initization of the counter be used for codegen.
2478 Expr *BuildCounterInit() const;
2479 /// \brief Build step of the counter be used for codegen.
2480 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002481 /// \brief Return true if any expression is dependent.
2482 bool Dependent() const;
2483
2484private:
2485 /// \brief Check the right-hand side of an assignment in the increment
2486 /// expression.
2487 bool CheckIncRHS(Expr *RHS);
2488 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002489 bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002490 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002491 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002492 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002493 /// \brief Helper to set loop increment.
2494 bool SetStep(Expr *NewStep, bool Subtract);
2495};
2496
2497bool OpenMPIterationSpaceChecker::Dependent() const {
2498 if (!Var) {
2499 assert(!LB && !UB && !Step);
2500 return false;
2501 }
2502 return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2503 (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2504}
2505
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002506template <typename T>
2507static T *getExprAsWritten(T *E) {
2508 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2509 E = ExprTemp->getSubExpr();
2510
2511 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2512 E = MTE->GetTemporaryExpr();
2513
2514 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2515 E = Binder->getSubExpr();
2516
2517 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2518 E = ICE->getSubExprAsWritten();
2519 return E->IgnoreParens();
2520}
2521
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002522bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2523 DeclRefExpr *NewVarRefExpr,
2524 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002525 // State consistency checking to ensure correct usage.
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002526 assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2527 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002528 if (!NewVar || !NewLB)
2529 return true;
2530 Var = NewVar;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002531 VarRef = NewVarRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002532 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2533 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002534 if ((Ctor->isCopyOrMoveConstructor() ||
2535 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2536 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002537 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002538 LB = NewLB;
2539 return false;
2540}
2541
2542bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002543 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002544 // State consistency checking to ensure correct usage.
2545 assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2546 !TestIsLessOp && !TestIsStrictOp);
2547 if (!NewUB)
2548 return true;
2549 UB = NewUB;
2550 TestIsLessOp = LessOp;
2551 TestIsStrictOp = StrictOp;
2552 ConditionSrcRange = SR;
2553 ConditionLoc = SL;
2554 return false;
2555}
2556
2557bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2558 // State consistency checking to ensure correct usage.
2559 assert(Var != nullptr && LB != nullptr && Step == nullptr);
2560 if (!NewStep)
2561 return true;
2562 if (!NewStep->isValueDependent()) {
2563 // Check that the step is integer expression.
2564 SourceLocation StepLoc = NewStep->getLocStart();
2565 ExprResult Val =
2566 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2567 if (Val.isInvalid())
2568 return true;
2569 NewStep = Val.get();
2570
2571 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2572 // If test-expr is of form var relational-op b and relational-op is < or
2573 // <= then incr-expr must cause var to increase on each iteration of the
2574 // loop. If test-expr is of form var relational-op b and relational-op is
2575 // > or >= then incr-expr must cause var to decrease on each iteration of
2576 // the loop.
2577 // If test-expr is of form b relational-op var and relational-op is < or
2578 // <= then incr-expr must cause var to decrease on each iteration of the
2579 // loop. If test-expr is of form b relational-op var and relational-op is
2580 // > or >= then incr-expr must cause var to increase on each iteration of
2581 // the loop.
2582 llvm::APSInt Result;
2583 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2584 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2585 bool IsConstNeg =
2586 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002587 bool IsConstPos =
2588 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002589 bool IsConstZero = IsConstant && !Result.getBoolValue();
2590 if (UB && (IsConstZero ||
2591 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002592 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002593 SemaRef.Diag(NewStep->getExprLoc(),
2594 diag::err_omp_loop_incr_not_compatible)
2595 << Var << TestIsLessOp << NewStep->getSourceRange();
2596 SemaRef.Diag(ConditionLoc,
2597 diag::note_omp_loop_cond_requres_compatible_incr)
2598 << TestIsLessOp << ConditionSrcRange;
2599 return true;
2600 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002601 if (TestIsLessOp == Subtract) {
2602 NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2603 NewStep).get();
2604 Subtract = !Subtract;
2605 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002606 }
2607
2608 Step = NewStep;
2609 SubtractStep = Subtract;
2610 return false;
2611}
2612
Alexey Bataev9c821032015-04-30 04:23:23 +00002613bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002614 // Check init-expr for canonical loop form and save loop counter
2615 // variable - #Var and its initialization value - #LB.
2616 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2617 // var = lb
2618 // integer-type var = lb
2619 // random-access-iterator-type var = lb
2620 // pointer-type var = lb
2621 //
2622 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002623 if (EmitDiags) {
2624 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2625 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002626 return true;
2627 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002628 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002629 if (Expr *E = dyn_cast<Expr>(S))
2630 S = E->IgnoreParens();
2631 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2632 if (BO->getOpcode() == BO_Assign)
2633 if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002634 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
Alexander Musmana5f070a2014-10-01 06:03:56 +00002635 BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002636 } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2637 if (DS->isSingleDecl()) {
2638 if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002639 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002640 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002641 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002642 SemaRef.Diag(S->getLocStart(),
2643 diag::ext_omp_loop_not_canonical_init)
2644 << S->getSourceRange();
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002645 return SetVarAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002646 }
2647 }
2648 }
2649 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2650 if (CE->getOperator() == OO_Equal)
2651 if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002652 return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2653 CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002654
Alexey Bataev9c821032015-04-30 04:23:23 +00002655 if (EmitDiags) {
2656 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2657 << S->getSourceRange();
2658 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002659 return true;
2660}
2661
Alexey Bataev23b69422014-06-18 07:08:49 +00002662/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002663/// variable (which may be the loop variable) if possible.
2664static const VarDecl *GetInitVarDecl(const Expr *E) {
2665 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00002666 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002667 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002668 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2669 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002670 if ((Ctor->isCopyOrMoveConstructor() ||
2671 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2672 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002673 E = CE->getArg(0)->IgnoreParenImpCasts();
2674 auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2675 if (!DRE)
2676 return nullptr;
2677 return dyn_cast<VarDecl>(DRE->getDecl());
2678}
2679
2680bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2681 // Check test-expr for canonical form, save upper-bound UB, flags for
2682 // less/greater and for strict/non-strict comparison.
2683 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2684 // var relational-op b
2685 // b relational-op var
2686 //
2687 if (!S) {
2688 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2689 return true;
2690 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002691 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002692 SourceLocation CondLoc = S->getLocStart();
2693 if (auto BO = dyn_cast<BinaryOperator>(S)) {
2694 if (BO->isRelationalOp()) {
2695 if (GetInitVarDecl(BO->getLHS()) == Var)
2696 return SetUB(BO->getRHS(),
2697 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2698 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2699 BO->getSourceRange(), BO->getOperatorLoc());
2700 if (GetInitVarDecl(BO->getRHS()) == Var)
2701 return SetUB(BO->getLHS(),
2702 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2703 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2704 BO->getSourceRange(), BO->getOperatorLoc());
2705 }
2706 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2707 if (CE->getNumArgs() == 2) {
2708 auto Op = CE->getOperator();
2709 switch (Op) {
2710 case OO_Greater:
2711 case OO_GreaterEqual:
2712 case OO_Less:
2713 case OO_LessEqual:
2714 if (GetInitVarDecl(CE->getArg(0)) == Var)
2715 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2716 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2717 CE->getOperatorLoc());
2718 if (GetInitVarDecl(CE->getArg(1)) == Var)
2719 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2720 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2721 CE->getOperatorLoc());
2722 break;
2723 default:
2724 break;
2725 }
2726 }
2727 }
2728 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2729 << S->getSourceRange() << Var;
2730 return true;
2731}
2732
2733bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2734 // RHS of canonical loop form increment can be:
2735 // var + incr
2736 // incr + var
2737 // var - incr
2738 //
2739 RHS = RHS->IgnoreParenImpCasts();
2740 if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2741 if (BO->isAdditiveOp()) {
2742 bool IsAdd = BO->getOpcode() == BO_Add;
2743 if (GetInitVarDecl(BO->getLHS()) == Var)
2744 return SetStep(BO->getRHS(), !IsAdd);
2745 if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2746 return SetStep(BO->getLHS(), false);
2747 }
2748 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2749 bool IsAdd = CE->getOperator() == OO_Plus;
2750 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2751 if (GetInitVarDecl(CE->getArg(0)) == Var)
2752 return SetStep(CE->getArg(1), !IsAdd);
2753 if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2754 return SetStep(CE->getArg(0), false);
2755 }
2756 }
2757 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2758 << RHS->getSourceRange() << Var;
2759 return true;
2760}
2761
2762bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2763 // Check incr-expr for canonical loop form and return true if it
2764 // does not conform.
2765 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2766 // ++var
2767 // var++
2768 // --var
2769 // var--
2770 // var += incr
2771 // var -= incr
2772 // var = var + incr
2773 // var = incr + var
2774 // var = var - incr
2775 //
2776 if (!S) {
2777 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2778 return true;
2779 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002780 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002781 S = S->IgnoreParens();
2782 if (auto UO = dyn_cast<UnaryOperator>(S)) {
2783 if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2784 return SetStep(
2785 SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2786 (UO->isDecrementOp() ? -1 : 1)).get(),
2787 false);
2788 } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2789 switch (BO->getOpcode()) {
2790 case BO_AddAssign:
2791 case BO_SubAssign:
2792 if (GetInitVarDecl(BO->getLHS()) == Var)
2793 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2794 break;
2795 case BO_Assign:
2796 if (GetInitVarDecl(BO->getLHS()) == Var)
2797 return CheckIncRHS(BO->getRHS());
2798 break;
2799 default:
2800 break;
2801 }
2802 } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2803 switch (CE->getOperator()) {
2804 case OO_PlusPlus:
2805 case OO_MinusMinus:
2806 if (GetInitVarDecl(CE->getArg(0)) == Var)
2807 return SetStep(
2808 SemaRef.ActOnIntegerConstant(
2809 CE->getLocStart(),
2810 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2811 false);
2812 break;
2813 case OO_PlusEqual:
2814 case OO_MinusEqual:
2815 if (GetInitVarDecl(CE->getArg(0)) == Var)
2816 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2817 break;
2818 case OO_Equal:
2819 if (GetInitVarDecl(CE->getArg(0)) == Var)
2820 return CheckIncRHS(CE->getArg(1));
2821 break;
2822 default:
2823 break;
2824 }
2825 }
2826 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2827 << S->getSourceRange() << Var;
2828 return true;
2829}
Alexander Musmana5f070a2014-10-01 06:03:56 +00002830
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002831namespace {
2832// Transform variables declared in GNU statement expressions to new ones to
2833// avoid crash on codegen.
2834class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
2835 typedef TreeTransform<TransformToNewDefs> BaseTransform;
2836
2837public:
2838 TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
2839
2840 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
2841 if (auto *VD = cast<VarDecl>(D))
2842 if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
2843 !isa<ImplicitParamDecl>(D)) {
2844 auto *NewVD = VarDecl::Create(
2845 SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
2846 VD->getLocation(), VD->getIdentifier(), VD->getType(),
2847 VD->getTypeSourceInfo(), VD->getStorageClass());
2848 NewVD->setTSCSpec(VD->getTSCSpec());
2849 NewVD->setInit(VD->getInit());
2850 NewVD->setInitStyle(VD->getInitStyle());
2851 NewVD->setExceptionVariable(VD->isExceptionVariable());
2852 NewVD->setNRVOVariable(VD->isNRVOVariable());
2853 NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
2854 NewVD->setConstexpr(VD->isConstexpr());
2855 NewVD->setInitCapture(VD->isInitCapture());
2856 NewVD->setPreviousDeclInSameBlockScope(
2857 VD->isPreviousDeclInSameBlockScope());
2858 VD->getDeclContext()->addHiddenDecl(NewVD);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002859 if (VD->hasAttrs())
2860 NewVD->setAttrs(VD->getAttrs());
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002861 transformedLocalDecl(VD, NewVD);
2862 return NewVD;
2863 }
2864 return BaseTransform::TransformDefinition(Loc, D);
2865 }
2866
2867 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
2868 if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
2869 if (E->getDecl() != NewD) {
2870 NewD->setReferenced();
2871 NewD->markUsed(SemaRef.Context);
2872 return DeclRefExpr::Create(
2873 SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
2874 cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
2875 E->getNameInfo(), E->getType(), E->getValueKind());
2876 }
2877 return BaseTransform::TransformDeclRefExpr(E);
2878 }
2879};
2880}
2881
Alexander Musmana5f070a2014-10-01 06:03:56 +00002882/// \brief Build the expression to calculate the number of iterations.
Alexander Musman174b3ca2014-10-06 11:16:29 +00002883Expr *
2884OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2885 const bool LimitedType) const {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002886 TransformToNewDefs Transform(SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00002887 ExprResult Diff;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002888 auto VarType = Var->getType().getNonReferenceType();
2889 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00002890 SemaRef.getLangOpts().CPlusPlus) {
2891 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002892 auto *UBExpr = TestIsLessOp ? UB : LB;
2893 auto *LBExpr = TestIsLessOp ? LB : UB;
2894 Expr *Upper = Transform.TransformExpr(UBExpr).get();
2895 Expr *Lower = Transform.TransformExpr(LBExpr).get();
2896 if (!Upper || !Lower)
2897 return nullptr;
2898 Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
2899 Sema::AA_Converting,
2900 /*AllowExplicit=*/true)
2901 .get();
2902 Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
2903 Sema::AA_Converting,
2904 /*AllowExplicit=*/true)
2905 .get();
2906 if (!Upper || !Lower)
2907 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002908
2909 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2910
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002911 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00002912 // BuildBinOp already emitted error, this one is to point user to upper
2913 // and lower bound, and to tell what is passed to 'operator-'.
2914 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2915 << Upper->getSourceRange() << Lower->getSourceRange();
2916 return nullptr;
2917 }
2918 }
2919
2920 if (!Diff.isUsable())
2921 return nullptr;
2922
2923 // Upper - Lower [- 1]
2924 if (TestIsStrictOp)
2925 Diff = SemaRef.BuildBinOp(
2926 S, DefaultLoc, BO_Sub, Diff.get(),
2927 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2928 if (!Diff.isUsable())
2929 return nullptr;
2930
2931 // Upper - Lower [- 1] + Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002932 auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2933 if (NewStep.isInvalid())
2934 return nullptr;
2935 NewStep = SemaRef.PerformImplicitConversion(
2936 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2937 /*AllowExplicit=*/true);
2938 if (NewStep.isInvalid())
2939 return nullptr;
2940 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002941 if (!Diff.isUsable())
2942 return nullptr;
2943
2944 // Parentheses (for dumping/debugging purposes only).
2945 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2946 if (!Diff.isUsable())
2947 return nullptr;
2948
2949 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002950 NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
2951 if (NewStep.isInvalid())
2952 return nullptr;
2953 NewStep = SemaRef.PerformImplicitConversion(
2954 NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
2955 /*AllowExplicit=*/true);
2956 if (NewStep.isInvalid())
2957 return nullptr;
2958 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002959 if (!Diff.isUsable())
2960 return nullptr;
2961
Alexander Musman174b3ca2014-10-06 11:16:29 +00002962 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002963 QualType Type = Diff.get()->getType();
2964 auto &C = SemaRef.Context;
2965 bool UseVarType = VarType->hasIntegerRepresentation() &&
2966 C.getTypeSize(Type) > C.getTypeSize(VarType);
2967 if (!Type->isIntegerType() || UseVarType) {
2968 unsigned NewSize =
2969 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
2970 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
2971 : Type->hasSignedIntegerRepresentation();
2972 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
2973 Diff = SemaRef.PerformImplicitConversion(
2974 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
2975 if (!Diff.isUsable())
2976 return nullptr;
2977 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00002978 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00002979 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2980 if (NewSize != C.getTypeSize(Type)) {
2981 if (NewSize < C.getTypeSize(Type)) {
2982 assert(NewSize == 64 && "incorrect loop var size");
2983 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2984 << InitSrcRange << ConditionSrcRange;
2985 }
2986 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00002987 NewSize, Type->hasSignedIntegerRepresentation() ||
2988 C.getTypeSize(Type) < NewSize);
Alexander Musman174b3ca2014-10-06 11:16:29 +00002989 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2990 Sema::AA_Converting, true);
2991 if (!Diff.isUsable())
2992 return nullptr;
2993 }
2994 }
2995
Alexander Musmana5f070a2014-10-01 06:03:56 +00002996 return Diff.get();
2997}
2998
Alexey Bataev62dbb972015-04-22 11:59:37 +00002999Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
3000 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3001 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3002 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003003 TransformToNewDefs Transform(SemaRef);
3004
3005 auto NewLB = Transform.TransformExpr(LB);
3006 auto NewUB = Transform.TransformExpr(UB);
3007 if (NewLB.isInvalid() || NewUB.isInvalid())
3008 return Cond;
3009 NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
3010 Sema::AA_Converting,
3011 /*AllowExplicit=*/true);
3012 NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
3013 Sema::AA_Converting,
3014 /*AllowExplicit=*/true);
3015 if (NewLB.isInvalid() || NewUB.isInvalid())
3016 return Cond;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003017 auto CondExpr = SemaRef.BuildBinOp(
3018 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3019 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003020 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003021 if (CondExpr.isUsable()) {
3022 CondExpr = SemaRef.PerformImplicitConversion(
3023 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3024 /*AllowExplicit=*/true);
3025 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003026 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3027 // Otherwise use original loop conditon and evaluate it in runtime.
3028 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3029}
3030
Alexander Musmana5f070a2014-10-01 06:03:56 +00003031/// \brief Build reference expression to the counter be used for codegen.
3032Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
Alexey Bataeva8899172015-08-06 12:30:57 +00003033 return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
3034 DefaultLoc);
3035}
3036
3037Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3038 if (Var && !Var->isInvalidDecl()) {
3039 auto Type = Var->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003040 auto *PrivateVar =
3041 buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
3042 Var->hasAttrs() ? &Var->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003043 if (PrivateVar->isInvalidDecl())
3044 return nullptr;
3045 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3046 }
3047 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003048}
3049
3050/// \brief Build initization of the counter be used for codegen.
3051Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3052
3053/// \brief Build step of the counter be used for codegen.
3054Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3055
3056/// \brief Iteration space of a single for loop.
3057struct LoopIterationSpace {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003058 /// \brief Condition of the loop.
3059 Expr *PreCond;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003060 /// \brief This expression calculates the number of iterations in the loop.
3061 /// It is always possible to calculate it before starting the loop.
3062 Expr *NumIterations;
3063 /// \brief The loop counter variable.
3064 Expr *CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00003065 /// \brief Private loop counter variable.
3066 Expr *PrivateCounterVar;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003067 /// \brief This is initializer for the initial value of #CounterVar.
3068 Expr *CounterInit;
3069 /// \brief This is step for the #CounterVar used to generate its update:
3070 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3071 Expr *CounterStep;
3072 /// \brief Should step be subtracted?
3073 bool Subtract;
3074 /// \brief Source range of the loop init.
3075 SourceRange InitSrcRange;
3076 /// \brief Source range of the loop condition.
3077 SourceRange CondSrcRange;
3078 /// \brief Source range of the loop increment.
3079 SourceRange IncSrcRange;
3080};
3081
Alexey Bataev23b69422014-06-18 07:08:49 +00003082} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003083
Alexey Bataev9c821032015-04-30 04:23:23 +00003084void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3085 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3086 assert(Init && "Expected loop in canonical form.");
3087 unsigned CollapseIteration = DSAStack->getCollapseNumber();
3088 if (CollapseIteration > 0 &&
3089 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3090 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3091 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3092 DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3093 }
3094 DSAStack->setCollapseNumber(CollapseIteration - 1);
3095 }
3096}
3097
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003098/// \brief Called on a for stmt to check and extract its iteration space
3099/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003100static bool CheckOpenMPIterationSpace(
3101 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3102 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003103 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003104 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3105 LoopIterationSpace &ResultIterSpace) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003106 // OpenMP [2.6, Canonical Loop Form]
3107 // for (init-expr; test-expr; incr-expr) structured-block
3108 auto For = dyn_cast_or_null<ForStmt>(S);
3109 if (!For) {
3110 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003111 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3112 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3113 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3114 if (NestedLoopCount > 1) {
3115 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3116 SemaRef.Diag(DSA.getConstructLoc(),
3117 diag::note_omp_collapse_ordered_expr)
3118 << 2 << CollapseLoopCountExpr->getSourceRange()
3119 << OrderedLoopCountExpr->getSourceRange();
3120 else if (CollapseLoopCountExpr)
3121 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3122 diag::note_omp_collapse_ordered_expr)
3123 << 0 << CollapseLoopCountExpr->getSourceRange();
3124 else
3125 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3126 diag::note_omp_collapse_ordered_expr)
3127 << 1 << OrderedLoopCountExpr->getSourceRange();
3128 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003129 return true;
3130 }
3131 assert(For->getBody());
3132
3133 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3134
3135 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003136 auto Init = For->getInit();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003137 if (ISC.CheckInit(Init)) {
3138 return true;
3139 }
3140
3141 bool HasErrors = false;
3142
3143 // Check loop variable's type.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003144 auto Var = ISC.GetLoopVar();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003145
3146 // OpenMP [2.6, Canonical Loop Form]
3147 // Var is one of the following:
3148 // A variable of signed or unsigned integer type.
3149 // For C++, a variable of a random access iterator type.
3150 // For C, a variable of a pointer type.
Alexey Bataeva8899172015-08-06 12:30:57 +00003151 auto VarType = Var->getType().getNonReferenceType();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003152 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3153 !VarType->isPointerType() &&
3154 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3155 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3156 << SemaRef.getLangOpts().CPlusPlus;
3157 HasErrors = true;
3158 }
3159
Alexey Bataev4acb8592014-07-07 13:01:15 +00003160 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3161 // Construct
3162 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3163 // parallel for construct is (are) private.
3164 // The loop iteration variable in the associated for-loop of a simd construct
3165 // with just one associated for-loop is linear with a constant-linear-step
3166 // that is the increment of the associated for-loop.
3167 // Exclude loop var from the list of variables with implicitly defined data
3168 // sharing attributes.
Benjamin Kramerad8e0792014-10-10 15:32:48 +00003169 VarsWithImplicitDSA.erase(Var);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003170
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003171 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3172 // a Construct, C/C++].
Alexey Bataevcefffae2014-06-23 08:21:53 +00003173 // The loop iteration variable in the associated for-loop of a simd construct
3174 // with just one associated for-loop may be listed in a linear clause with a
3175 // constant-linear-step that is the increment of the associated for-loop.
Alexey Bataevf29276e2014-06-18 04:14:57 +00003176 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3177 // parallel for construct may be listed in a private or lastprivate clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003178 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003179 auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3180 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3181 // declared in the loop and it is predetermined as a private.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003182 auto PredeterminedCKind =
3183 isOpenMPSimdDirective(DKind)
3184 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3185 : OMPC_private;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003186 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003187 DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
Alexander Musmanf82886e2014-09-18 05:12:34 +00003188 (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
3189 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
Alexey Bataev0c024df2015-05-12 09:02:07 +00003190 DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
3191 ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
3192 DVar.RefExpr != nullptr)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003193 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
Alexey Bataev4acb8592014-07-07 13:01:15 +00003194 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3195 << getOpenMPClauseName(PredeterminedCKind);
Alexey Bataevf2453a02015-05-06 07:25:08 +00003196 if (DVar.RefExpr == nullptr)
3197 DVar.CKind = PredeterminedCKind;
3198 ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003199 HasErrors = true;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003200 } else if (LoopVarRefExpr != nullptr) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003201 // Make the loop iteration variable private (for worksharing constructs),
3202 // linear (for simd directives with the only one associated loop) or
Alexey Bataev10e775f2015-07-30 11:36:16 +00003203 // lastprivate (for simd directives with several collapsed or ordered
3204 // loops).
Alexey Bataev9aba41c2014-11-14 04:08:45 +00003205 if (DVar.CKind == OMPC_unknown)
3206 DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
3207 /*FromParent=*/false);
Alexey Bataev9c821032015-04-30 04:23:23 +00003208 DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003209 }
3210
Alexey Bataev7ff55242014-06-19 09:13:45 +00003211 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
Alexander Musman1bb328c2014-06-04 13:06:39 +00003212
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003213 // Check test-expr.
3214 HasErrors |= ISC.CheckCond(For->getCond());
3215
3216 // Check incr-expr.
3217 HasErrors |= ISC.CheckInc(For->getInc());
3218
Alexander Musmana5f070a2014-10-01 06:03:56 +00003219 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003220 return HasErrors;
3221
Alexander Musmana5f070a2014-10-01 06:03:56 +00003222 // Build the loop's iteration space representation.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003223 ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
Alexander Musman174b3ca2014-10-06 11:16:29 +00003224 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3225 DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
Alexander Musmana5f070a2014-10-01 06:03:56 +00003226 ResultIterSpace.CounterVar = ISC.BuildCounterVar();
Alexey Bataeva8899172015-08-06 12:30:57 +00003227 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003228 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3229 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3230 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3231 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3232 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3233 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3234
Alexey Bataev62dbb972015-04-22 11:59:37 +00003235 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3236 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003237 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003238 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003239 ResultIterSpace.CounterInit == nullptr ||
3240 ResultIterSpace.CounterStep == nullptr);
3241
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003242 return HasErrors;
3243}
3244
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003245/// \brief Build 'VarRef = Start.
3246static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
3247 ExprResult VarRef, ExprResult Start) {
3248 TransformToNewDefs Transform(SemaRef);
3249 // Build 'VarRef = Start.
3250 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3251 if (NewStart.isInvalid())
3252 return ExprError();
3253 NewStart = SemaRef.PerformImplicitConversion(
3254 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3255 Sema::AA_Converting,
3256 /*AllowExplicit=*/true);
3257 if (NewStart.isInvalid())
3258 return ExprError();
3259 NewStart = SemaRef.PerformImplicitConversion(
3260 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3261 /*AllowExplicit=*/true);
3262 if (!NewStart.isUsable())
3263 return ExprError();
3264
3265 auto Init =
3266 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3267 return Init;
3268}
3269
Alexander Musmana5f070a2014-10-01 06:03:56 +00003270/// \brief Build 'VarRef = Start + Iter * Step'.
3271static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3272 SourceLocation Loc, ExprResult VarRef,
3273 ExprResult Start, ExprResult Iter,
3274 ExprResult Step, bool Subtract) {
3275 // Add parentheses (for debugging purposes only).
3276 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3277 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3278 !Step.isUsable())
3279 return ExprError();
3280
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003281 TransformToNewDefs Transform(SemaRef);
3282 auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3283 if (NewStep.isInvalid())
3284 return ExprError();
3285 NewStep = SemaRef.PerformImplicitConversion(
3286 NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3287 Sema::AA_Converting,
3288 /*AllowExplicit=*/true);
3289 if (NewStep.isInvalid())
3290 return ExprError();
3291 ExprResult Update =
3292 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003293 if (!Update.isUsable())
3294 return ExprError();
3295
3296 // Build 'VarRef = Start + Iter * Step'.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003297 auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3298 if (NewStart.isInvalid())
3299 return ExprError();
3300 NewStart = SemaRef.PerformImplicitConversion(
3301 NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3302 Sema::AA_Converting,
3303 /*AllowExplicit=*/true);
3304 if (NewStart.isInvalid())
3305 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003306 Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003307 NewStart.get(), Update.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003308 if (!Update.isUsable())
3309 return ExprError();
3310
3311 Update = SemaRef.PerformImplicitConversion(
3312 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3313 if (!Update.isUsable())
3314 return ExprError();
3315
3316 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3317 return Update;
3318}
3319
3320/// \brief Convert integer expression \a E to make it have at least \a Bits
3321/// bits.
3322static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3323 Sema &SemaRef) {
3324 if (E == nullptr)
3325 return ExprError();
3326 auto &C = SemaRef.Context;
3327 QualType OldType = E->getType();
3328 unsigned HasBits = C.getTypeSize(OldType);
3329 if (HasBits >= Bits)
3330 return ExprResult(E);
3331 // OK to convert to signed, because new type has more bits than old.
3332 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3333 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3334 true);
3335}
3336
3337/// \brief Check if the given expression \a E is a constant integer that fits
3338/// into \a Bits bits.
3339static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3340 if (E == nullptr)
3341 return false;
3342 llvm::APSInt Result;
3343 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3344 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3345 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003346}
3347
3348/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003349/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3350/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003351static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003352CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3353 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3354 DSAStackTy &DSA,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003355 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003356 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003357 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003358 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003359 // Found 'collapse' clause - calculate collapse number.
3360 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003361 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3362 NestedLoopCount += Result.getLimitedValue() - 1;
3363 }
3364 if (OrderedLoopCountExpr) {
3365 // Found 'ordered' clause - calculate collapse number.
3366 llvm::APSInt Result;
3367 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3368 NestedLoopCount += Result.getLimitedValue() - 1;
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003369 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003370 // This is helper routine for loop directives (e.g., 'for', 'simd',
3371 // 'for simd', etc.).
Alexander Musmana5f070a2014-10-01 06:03:56 +00003372 SmallVector<LoopIterationSpace, 4> IterSpaces;
3373 IterSpaces.resize(NestedLoopCount);
3374 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003375 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003376 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003377 NestedLoopCount, CollapseLoopCountExpr,
3378 OrderedLoopCountExpr, VarsWithImplicitDSA,
3379 IterSpaces[Cnt]))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003380 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003381 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003382 // OpenMP [2.8.1, simd construct, Restrictions]
3383 // All loops associated with the construct must be perfectly nested; that
3384 // is, there must be no intervening code nor any OpenMP directive between
3385 // any two loops.
3386 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003387 }
3388
Alexander Musmana5f070a2014-10-01 06:03:56 +00003389 Built.clear(/* size */ NestedLoopCount);
3390
3391 if (SemaRef.CurContext->isDependentContext())
3392 return NestedLoopCount;
3393
3394 // An example of what is generated for the following code:
3395 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003396 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003397 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003398 // for (k = 0; k < NK; ++k)
3399 // for (j = J0; j < NJ; j+=2) {
3400 // <loop body>
3401 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003402 //
3403 // We generate the code below.
3404 // Note: the loop body may be outlined in CodeGen.
3405 // Note: some counters may be C++ classes, operator- is used to find number of
3406 // iterations and operator+= to calculate counter value.
3407 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3408 // or i64 is currently supported).
3409 //
3410 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3411 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3412 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3413 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3414 // // similar updates for vars in clauses (e.g. 'linear')
3415 // <loop body (using local i and j)>
3416 // }
3417 // i = NI; // assign final values of counters
3418 // j = NJ;
3419 //
3420
3421 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3422 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003423 // Precondition tests if there is at least one iteration (all conditions are
3424 // true).
3425 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003426 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003427 ExprResult LastIteration32 = WidenIterationCount(
3428 32 /* Bits */, SemaRef.PerformImplicitConversion(
3429 N0->IgnoreImpCasts(), N0->getType(),
3430 Sema::AA_Converting, /*AllowExplicit=*/true)
3431 .get(),
3432 SemaRef);
3433 ExprResult LastIteration64 = WidenIterationCount(
3434 64 /* Bits */, SemaRef.PerformImplicitConversion(
3435 N0->IgnoreImpCasts(), N0->getType(),
3436 Sema::AA_Converting, /*AllowExplicit=*/true)
3437 .get(),
3438 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003439
3440 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3441 return NestedLoopCount;
3442
3443 auto &C = SemaRef.Context;
3444 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3445
3446 Scope *CurScope = DSA.getCurScope();
3447 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003448 if (PreCond.isUsable()) {
3449 PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3450 PreCond.get(), IterSpaces[Cnt].PreCond);
3451 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003452 auto N = IterSpaces[Cnt].NumIterations;
3453 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3454 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003455 LastIteration32 = SemaRef.BuildBinOp(
3456 CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3457 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3458 Sema::AA_Converting,
3459 /*AllowExplicit=*/true)
3460 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003461 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003462 LastIteration64 = SemaRef.BuildBinOp(
3463 CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3464 SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3465 Sema::AA_Converting,
3466 /*AllowExplicit=*/true)
3467 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003468 }
3469
3470 // Choose either the 32-bit or 64-bit version.
3471 ExprResult LastIteration = LastIteration64;
3472 if (LastIteration32.isUsable() &&
3473 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3474 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3475 FitsInto(
3476 32 /* Bits */,
3477 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3478 LastIteration64.get(), SemaRef)))
3479 LastIteration = LastIteration32;
3480
3481 if (!LastIteration.isUsable())
3482 return 0;
3483
3484 // Save the number of iterations.
3485 ExprResult NumIterations = LastIteration;
3486 {
3487 LastIteration = SemaRef.BuildBinOp(
3488 CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3489 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3490 if (!LastIteration.isUsable())
3491 return 0;
3492 }
3493
3494 // Calculate the last iteration number beforehand instead of doing this on
3495 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3496 llvm::APSInt Result;
3497 bool IsConstant =
3498 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3499 ExprResult CalcLastIteration;
3500 if (!IsConstant) {
3501 SourceLocation SaveLoc;
3502 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003503 buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003504 ".omp.last.iteration");
Alexey Bataev39f915b82015-05-08 10:41:21 +00003505 ExprResult SaveRef = buildDeclRefExpr(
3506 SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003507 CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3508 SaveRef.get(), LastIteration.get());
3509 LastIteration = SaveRef;
3510
3511 // Prepare SaveRef + 1.
3512 NumIterations = SemaRef.BuildBinOp(
3513 CurScope, SaveLoc, BO_Add, SaveRef.get(),
3514 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3515 if (!NumIterations.isUsable())
3516 return 0;
3517 }
3518
3519 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3520
Alexander Musmanc6388682014-12-15 07:07:06 +00003521 QualType VType = LastIteration.get()->getType();
3522 // Build variables passed into runtime, nesessary for worksharing directives.
3523 ExprResult LB, UB, IL, ST, EUB;
3524 if (isOpenMPWorksharingDirective(DKind)) {
3525 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003526 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3527 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003528 SemaRef.AddInitializerToDecl(
3529 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3530 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3531
3532 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003533 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3534 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003535 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3536 /*DirectInit*/ false,
3537 /*TypeMayContainAuto*/ false);
3538
3539 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3540 // This will be used to implement clause 'lastprivate'.
3541 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003542 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3543 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003544 SemaRef.AddInitializerToDecl(
3545 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3546 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3547
3548 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev39f915b82015-05-08 10:41:21 +00003549 VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3550 ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003551 SemaRef.AddInitializerToDecl(
3552 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3553 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3554
3555 // Build expression: UB = min(UB, LastIteration)
3556 // It is nesessary for CodeGen of directives with static scheduling.
3557 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3558 UB.get(), LastIteration.get());
3559 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3560 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3561 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3562 CondOp.get());
3563 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3564 }
3565
3566 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003567 ExprResult IV;
3568 ExprResult Init;
3569 {
Alexey Bataev39f915b82015-05-08 10:41:21 +00003570 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3571 IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003572 Expr *RHS = isOpenMPWorksharingDirective(DKind)
3573 ? LB.get()
3574 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3575 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3576 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003577 }
3578
Alexander Musmanc6388682014-12-15 07:07:06 +00003579 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003580 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00003581 ExprResult Cond =
3582 isOpenMPWorksharingDirective(DKind)
3583 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3584 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3585 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003586
3587 // Loop increment (IV = IV + 1)
3588 SourceLocation IncLoc;
3589 ExprResult Inc =
3590 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3591 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3592 if (!Inc.isUsable())
3593 return 0;
3594 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00003595 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3596 if (!Inc.isUsable())
3597 return 0;
3598
3599 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3600 // Used for directives with static scheduling.
3601 ExprResult NextLB, NextUB;
3602 if (isOpenMPWorksharingDirective(DKind)) {
3603 // LB + ST
3604 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3605 if (!NextLB.isUsable())
3606 return 0;
3607 // LB = LB + ST
3608 NextLB =
3609 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3610 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3611 if (!NextLB.isUsable())
3612 return 0;
3613 // UB + ST
3614 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3615 if (!NextUB.isUsable())
3616 return 0;
3617 // UB = UB + ST
3618 NextUB =
3619 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3620 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3621 if (!NextUB.isUsable())
3622 return 0;
3623 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003624
3625 // Build updates and final values of the loop counters.
3626 bool HasErrors = false;
3627 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003628 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003629 Built.Updates.resize(NestedLoopCount);
3630 Built.Finals.resize(NestedLoopCount);
3631 {
3632 ExprResult Div;
3633 // Go from inner nested loop to outer.
3634 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3635 LoopIterationSpace &IS = IterSpaces[Cnt];
3636 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3637 // Build: Iter = (IV / Div) % IS.NumIters
3638 // where Div is product of previous iterations' IS.NumIters.
3639 ExprResult Iter;
3640 if (Div.isUsable()) {
3641 Iter =
3642 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3643 } else {
3644 Iter = IV;
3645 assert((Cnt == (int)NestedLoopCount - 1) &&
3646 "unusable div expected on first iteration only");
3647 }
3648
3649 if (Cnt != 0 && Iter.isUsable())
3650 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3651 IS.NumIterations);
3652 if (!Iter.isUsable()) {
3653 HasErrors = true;
3654 break;
3655 }
3656
Alexey Bataev39f915b82015-05-08 10:41:21 +00003657 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3658 auto *CounterVar = buildDeclRefExpr(
3659 SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3660 IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3661 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003662 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
3663 IS.CounterInit);
3664 if (!Init.isUsable()) {
3665 HasErrors = true;
3666 break;
3667 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003668 ExprResult Update =
Alexey Bataev39f915b82015-05-08 10:41:21 +00003669 BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003670 IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3671 if (!Update.isUsable()) {
3672 HasErrors = true;
3673 break;
3674 }
3675
3676 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3677 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00003678 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexander Musmana5f070a2014-10-01 06:03:56 +00003679 IS.NumIterations, IS.CounterStep, IS.Subtract);
3680 if (!Final.isUsable()) {
3681 HasErrors = true;
3682 break;
3683 }
3684
3685 // Build Div for the next iteration: Div <- Div * IS.NumIters
3686 if (Cnt != 0) {
3687 if (Div.isUnset())
3688 Div = IS.NumIterations;
3689 else
3690 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3691 IS.NumIterations);
3692
3693 // Add parentheses (for debugging purposes only).
3694 if (Div.isUsable())
3695 Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3696 if (!Div.isUsable()) {
3697 HasErrors = true;
3698 break;
3699 }
3700 }
3701 if (!Update.isUsable() || !Final.isUsable()) {
3702 HasErrors = true;
3703 break;
3704 }
3705 // Save results
3706 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00003707 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003708 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003709 Built.Updates[Cnt] = Update.get();
3710 Built.Finals[Cnt] = Final.get();
3711 }
3712 }
3713
3714 if (HasErrors)
3715 return 0;
3716
3717 // Save results
3718 Built.IterationVarRef = IV.get();
3719 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00003720 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003721 Built.CalcLastIteration =
3722 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003723 Built.PreCond = PreCond.get();
3724 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003725 Built.Init = Init.get();
3726 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00003727 Built.LB = LB.get();
3728 Built.UB = UB.get();
3729 Built.IL = IL.get();
3730 Built.ST = ST.get();
3731 Built.EUB = EUB.get();
3732 Built.NLB = NextLB.get();
3733 Built.NUB = NextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003734
Alexey Bataevabfc0692014-06-25 06:52:00 +00003735 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003736}
3737
Alexey Bataev10e775f2015-07-30 11:36:16 +00003738static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003739 auto CollapseClauses =
3740 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
3741 if (CollapseClauses.begin() != CollapseClauses.end())
3742 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003743 return nullptr;
3744}
3745
Alexey Bataev10e775f2015-07-30 11:36:16 +00003746static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00003747 auto OrderedClauses =
3748 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
3749 if (OrderedClauses.begin() != OrderedClauses.end())
3750 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003751 return nullptr;
3752}
3753
Alexey Bataev66b15b52015-08-21 11:14:16 +00003754static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
3755 const Expr *Safelen) {
3756 llvm::APSInt SimdlenRes, SafelenRes;
3757 if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
3758 Simdlen->isInstantiationDependent() ||
3759 Simdlen->containsUnexpandedParameterPack())
3760 return false;
3761 if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
3762 Safelen->isInstantiationDependent() ||
3763 Safelen->containsUnexpandedParameterPack())
3764 return false;
3765 Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
3766 Safelen->EvaluateAsInt(SafelenRes, S.Context);
3767 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3768 // If both simdlen and safelen clauses are specified, the value of the simdlen
3769 // parameter must be less than or equal to the value of the safelen parameter.
3770 if (SimdlenRes > SafelenRes) {
3771 S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
3772 << Simdlen->getSourceRange() << Safelen->getSourceRange();
3773 return true;
3774 }
3775 return false;
3776}
3777
Alexey Bataev4acb8592014-07-07 13:01:15 +00003778StmtResult Sema::ActOnOpenMPSimdDirective(
3779 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3780 SourceLocation EndLoc,
3781 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003782 if (!AStmt)
3783 return StmtError();
3784
3785 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003786 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003787 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3788 // define the nested loops number.
3789 unsigned NestedLoopCount = CheckOpenMPLoop(
3790 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3791 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003792 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003793 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003794
Alexander Musmana5f070a2014-10-01 06:03:56 +00003795 assert((CurContext->isDependentContext() || B.builtAll()) &&
3796 "omp simd loop exprs were not built");
3797
Alexander Musman3276a272015-03-21 10:12:56 +00003798 if (!CurContext->isDependentContext()) {
3799 // Finalize the clauses that need pre-built expressions for CodeGen.
3800 for (auto C : Clauses) {
3801 if (auto LC = dyn_cast<OMPLinearClause>(C))
3802 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3803 B.NumIterations, *this, CurScope))
3804 return StmtError();
3805 }
3806 }
3807
Alexey Bataev66b15b52015-08-21 11:14:16 +00003808 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3809 // If both simdlen and safelen clauses are specified, the value of the simdlen
3810 // parameter must be less than or equal to the value of the safelen parameter.
3811 OMPSafelenClause *Safelen = nullptr;
3812 OMPSimdlenClause *Simdlen = nullptr;
3813 for (auto *Clause : Clauses) {
3814 if (Clause->getClauseKind() == OMPC_safelen)
3815 Safelen = cast<OMPSafelenClause>(Clause);
3816 else if (Clause->getClauseKind() == OMPC_simdlen)
3817 Simdlen = cast<OMPSimdlenClause>(Clause);
3818 if (Safelen && Simdlen)
3819 break;
3820 }
3821 if (Simdlen && Safelen &&
3822 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3823 Safelen->getSafelen()))
3824 return StmtError();
3825
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003826 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003827 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3828 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003829}
3830
Alexey Bataev4acb8592014-07-07 13:01:15 +00003831StmtResult Sema::ActOnOpenMPForDirective(
3832 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3833 SourceLocation EndLoc,
3834 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003835 if (!AStmt)
3836 return StmtError();
3837
3838 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003839 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003840 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3841 // define the nested loops number.
3842 unsigned NestedLoopCount = CheckOpenMPLoop(
3843 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
3844 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00003845 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00003846 return StmtError();
3847
Alexander Musmana5f070a2014-10-01 06:03:56 +00003848 assert((CurContext->isDependentContext() || B.builtAll()) &&
3849 "omp for loop exprs were not built");
3850
Alexey Bataev54acd402015-08-04 11:18:19 +00003851 if (!CurContext->isDependentContext()) {
3852 // Finalize the clauses that need pre-built expressions for CodeGen.
3853 for (auto C : Clauses) {
3854 if (auto LC = dyn_cast<OMPLinearClause>(C))
3855 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3856 B.NumIterations, *this, CurScope))
3857 return StmtError();
3858 }
3859 }
3860
Alexey Bataevf29276e2014-06-18 04:14:57 +00003861 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003862 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003863 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00003864}
3865
Alexander Musmanf82886e2014-09-18 05:12:34 +00003866StmtResult Sema::ActOnOpenMPForSimdDirective(
3867 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3868 SourceLocation EndLoc,
3869 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003870 if (!AStmt)
3871 return StmtError();
3872
3873 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00003874 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003875 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
3876 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00003877 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00003878 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
3879 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
3880 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003881 if (NestedLoopCount == 0)
3882 return StmtError();
3883
Alexander Musmanc6388682014-12-15 07:07:06 +00003884 assert((CurContext->isDependentContext() || B.builtAll()) &&
3885 "omp for simd loop exprs were not built");
3886
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00003887 if (!CurContext->isDependentContext()) {
3888 // Finalize the clauses that need pre-built expressions for CodeGen.
3889 for (auto C : Clauses) {
3890 if (auto LC = dyn_cast<OMPLinearClause>(C))
3891 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3892 B.NumIterations, *this, CurScope))
3893 return StmtError();
3894 }
3895 }
3896
Alexey Bataev66b15b52015-08-21 11:14:16 +00003897 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
3898 // If both simdlen and safelen clauses are specified, the value of the simdlen
3899 // parameter must be less than or equal to the value of the safelen parameter.
3900 OMPSafelenClause *Safelen = nullptr;
3901 OMPSimdlenClause *Simdlen = nullptr;
3902 for (auto *Clause : Clauses) {
3903 if (Clause->getClauseKind() == OMPC_safelen)
3904 Safelen = cast<OMPSafelenClause>(Clause);
3905 else if (Clause->getClauseKind() == OMPC_simdlen)
3906 Simdlen = cast<OMPSimdlenClause>(Clause);
3907 if (Safelen && Simdlen)
3908 break;
3909 }
3910 if (Simdlen && Safelen &&
3911 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
3912 Safelen->getSafelen()))
3913 return StmtError();
3914
Alexander Musmanf82886e2014-09-18 05:12:34 +00003915 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00003916 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3917 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00003918}
3919
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003920StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3921 Stmt *AStmt,
3922 SourceLocation StartLoc,
3923 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003924 if (!AStmt)
3925 return StmtError();
3926
3927 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003928 auto BaseStmt = AStmt;
3929 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3930 BaseStmt = CS->getCapturedStmt();
3931 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3932 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00003933 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003934 return StmtError();
3935 // All associated statements must be '#pragma omp section' except for
3936 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00003937 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003938 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3939 if (SectionStmt)
3940 Diag(SectionStmt->getLocStart(),
3941 diag::err_omp_sections_substmt_not_section);
3942 return StmtError();
3943 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00003944 cast<OMPSectionDirective>(SectionStmt)
3945 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003946 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003947 } else {
3948 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3949 return StmtError();
3950 }
3951
3952 getCurFunction()->setHasBranchProtectedScope();
3953
Alexey Bataev25e5b442015-09-15 12:52:43 +00003954 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3955 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003956}
3957
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003958StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3959 SourceLocation StartLoc,
3960 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003961 if (!AStmt)
3962 return StmtError();
3963
3964 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003965
3966 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00003967 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003968
Alexey Bataev25e5b442015-09-15 12:52:43 +00003969 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
3970 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003971}
3972
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003973StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3974 Stmt *AStmt,
3975 SourceLocation StartLoc,
3976 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003977 if (!AStmt)
3978 return StmtError();
3979
3980 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00003981
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003982 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00003983
Alexey Bataev3255bf32015-01-19 05:20:46 +00003984 // OpenMP [2.7.3, single Construct, Restrictions]
3985 // The copyprivate clause must not be used with the nowait clause.
3986 OMPClause *Nowait = nullptr;
3987 OMPClause *Copyprivate = nullptr;
3988 for (auto *Clause : Clauses) {
3989 if (Clause->getClauseKind() == OMPC_nowait)
3990 Nowait = Clause;
3991 else if (Clause->getClauseKind() == OMPC_copyprivate)
3992 Copyprivate = Clause;
3993 if (Copyprivate && Nowait) {
3994 Diag(Copyprivate->getLocStart(),
3995 diag::err_omp_single_copyprivate_with_nowait);
3996 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3997 return StmtError();
3998 }
3999 }
4000
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004001 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4002}
4003
Alexander Musman80c22892014-07-17 08:54:58 +00004004StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4005 SourceLocation StartLoc,
4006 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004007 if (!AStmt)
4008 return StmtError();
4009
4010 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004011
4012 getCurFunction()->setHasBranchProtectedScope();
4013
4014 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4015}
4016
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004017StmtResult
4018Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
4019 Stmt *AStmt, SourceLocation StartLoc,
4020 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004021 if (!AStmt)
4022 return StmtError();
4023
4024 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004025
4026 getCurFunction()->setHasBranchProtectedScope();
4027
4028 return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4029 AStmt);
4030}
4031
Alexey Bataev4acb8592014-07-07 13:01:15 +00004032StmtResult Sema::ActOnOpenMPParallelForDirective(
4033 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4034 SourceLocation EndLoc,
4035 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004036 if (!AStmt)
4037 return StmtError();
4038
Alexey Bataev4acb8592014-07-07 13:01:15 +00004039 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4040 // 1.2.2 OpenMP Language Terminology
4041 // Structured block - An executable statement with a single entry at the
4042 // top and a single exit at the bottom.
4043 // The point of exit cannot be a branch out of the structured block.
4044 // longjmp() and throw() must not violate the entry/exit criteria.
4045 CS->getCapturedDecl()->setNothrow();
4046
Alexander Musmanc6388682014-12-15 07:07:06 +00004047 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004048 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4049 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004050 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004051 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4052 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4053 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004054 if (NestedLoopCount == 0)
4055 return StmtError();
4056
Alexander Musmana5f070a2014-10-01 06:03:56 +00004057 assert((CurContext->isDependentContext() || B.builtAll()) &&
4058 "omp parallel for loop exprs were not built");
4059
Alexey Bataev54acd402015-08-04 11:18:19 +00004060 if (!CurContext->isDependentContext()) {
4061 // Finalize the clauses that need pre-built expressions for CodeGen.
4062 for (auto C : Clauses) {
4063 if (auto LC = dyn_cast<OMPLinearClause>(C))
4064 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4065 B.NumIterations, *this, CurScope))
4066 return StmtError();
4067 }
4068 }
4069
Alexey Bataev4acb8592014-07-07 13:01:15 +00004070 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004071 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004072 NestedLoopCount, Clauses, AStmt, B,
4073 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004074}
4075
Alexander Musmane4e893b2014-09-23 09:33:00 +00004076StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4077 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4078 SourceLocation EndLoc,
4079 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004080 if (!AStmt)
4081 return StmtError();
4082
Alexander Musmane4e893b2014-09-23 09:33:00 +00004083 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4084 // 1.2.2 OpenMP Language Terminology
4085 // Structured block - An executable statement with a single entry at the
4086 // top and a single exit at the bottom.
4087 // The point of exit cannot be a branch out of the structured block.
4088 // longjmp() and throw() must not violate the entry/exit criteria.
4089 CS->getCapturedDecl()->setNothrow();
4090
Alexander Musmanc6388682014-12-15 07:07:06 +00004091 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004092 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4093 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004094 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004095 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4096 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4097 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004098 if (NestedLoopCount == 0)
4099 return StmtError();
4100
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004101 if (!CurContext->isDependentContext()) {
4102 // Finalize the clauses that need pre-built expressions for CodeGen.
4103 for (auto C : Clauses) {
4104 if (auto LC = dyn_cast<OMPLinearClause>(C))
4105 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4106 B.NumIterations, *this, CurScope))
4107 return StmtError();
4108 }
4109 }
4110
Alexey Bataev66b15b52015-08-21 11:14:16 +00004111 // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4112 // If both simdlen and safelen clauses are specified, the value of the simdlen
4113 // parameter must be less than or equal to the value of the safelen parameter.
4114 OMPSafelenClause *Safelen = nullptr;
4115 OMPSimdlenClause *Simdlen = nullptr;
4116 for (auto *Clause : Clauses) {
4117 if (Clause->getClauseKind() == OMPC_safelen)
4118 Safelen = cast<OMPSafelenClause>(Clause);
4119 else if (Clause->getClauseKind() == OMPC_simdlen)
4120 Simdlen = cast<OMPSimdlenClause>(Clause);
4121 if (Safelen && Simdlen)
4122 break;
4123 }
4124 if (Simdlen && Safelen &&
4125 checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4126 Safelen->getSafelen()))
4127 return StmtError();
4128
Alexander Musmane4e893b2014-09-23 09:33:00 +00004129 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004130 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004131 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004132}
4133
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004134StmtResult
4135Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4136 Stmt *AStmt, SourceLocation StartLoc,
4137 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004138 if (!AStmt)
4139 return StmtError();
4140
4141 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004142 auto BaseStmt = AStmt;
4143 while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4144 BaseStmt = CS->getCapturedStmt();
4145 if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4146 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004147 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004148 return StmtError();
4149 // All associated statements must be '#pragma omp section' except for
4150 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004151 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004152 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4153 if (SectionStmt)
4154 Diag(SectionStmt->getLocStart(),
4155 diag::err_omp_parallel_sections_substmt_not_section);
4156 return StmtError();
4157 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004158 cast<OMPSectionDirective>(SectionStmt)
4159 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004160 }
4161 } else {
4162 Diag(AStmt->getLocStart(),
4163 diag::err_omp_parallel_sections_not_compound_stmt);
4164 return StmtError();
4165 }
4166
4167 getCurFunction()->setHasBranchProtectedScope();
4168
Alexey Bataev25e5b442015-09-15 12:52:43 +00004169 return OMPParallelSectionsDirective::Create(
4170 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004171}
4172
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004173StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4174 Stmt *AStmt, SourceLocation StartLoc,
4175 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004176 if (!AStmt)
4177 return StmtError();
4178
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004179 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4180 // 1.2.2 OpenMP Language Terminology
4181 // Structured block - An executable statement with a single entry at the
4182 // top and a single exit at the bottom.
4183 // The point of exit cannot be a branch out of the structured block.
4184 // longjmp() and throw() must not violate the entry/exit criteria.
4185 CS->getCapturedDecl()->setNothrow();
4186
4187 getCurFunction()->setHasBranchProtectedScope();
4188
Alexey Bataev25e5b442015-09-15 12:52:43 +00004189 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4190 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004191}
4192
Alexey Bataev68446b72014-07-18 07:47:19 +00004193StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4194 SourceLocation EndLoc) {
4195 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4196}
4197
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004198StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4199 SourceLocation EndLoc) {
4200 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4201}
4202
Alexey Bataev2df347a2014-07-18 10:17:07 +00004203StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4204 SourceLocation EndLoc) {
4205 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4206}
4207
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004208StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4209 SourceLocation StartLoc,
4210 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004211 if (!AStmt)
4212 return StmtError();
4213
4214 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004215
4216 getCurFunction()->setHasBranchProtectedScope();
4217
4218 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4219}
4220
Alexey Bataev6125da92014-07-21 11:26:11 +00004221StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4222 SourceLocation StartLoc,
4223 SourceLocation EndLoc) {
4224 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4225 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4226}
4227
Alexey Bataev346265e2015-09-25 10:37:12 +00004228StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4229 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004230 SourceLocation StartLoc,
4231 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004232 if (!AStmt)
4233 return StmtError();
4234
4235 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004236
4237 getCurFunction()->setHasBranchProtectedScope();
4238
Alexey Bataev346265e2015-09-25 10:37:12 +00004239 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004240 OMPSIMDClause *SC = nullptr;
Alexey Bataev346265e2015-09-25 10:37:12 +00004241 for (auto *C: Clauses) {
4242 if (C->getClauseKind() == OMPC_threads)
4243 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004244 else if (C->getClauseKind() == OMPC_simd)
4245 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004246 }
4247
4248 // TODO: this must happen only if 'threads' clause specified or if no clauses
4249 // is specified.
4250 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4251 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4252 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) << (TC != nullptr);
4253 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4254 return StmtError();
4255 }
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004256 if (!SC && isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4257 // OpenMP [2.8.1,simd Construct, Restrictions]
4258 // An ordered construct with the simd clause is the only OpenMP construct
4259 // that can appear in the simd region.
4260 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4261 return StmtError();
4262 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004263
4264 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004265}
4266
Alexey Bataev1d160b12015-03-13 12:27:31 +00004267namespace {
4268/// \brief Helper class for checking expression in 'omp atomic [update]'
4269/// construct.
4270class OpenMPAtomicUpdateChecker {
4271 /// \brief Error results for atomic update expressions.
4272 enum ExprAnalysisErrorCode {
4273 /// \brief A statement is not an expression statement.
4274 NotAnExpression,
4275 /// \brief Expression is not builtin binary or unary operation.
4276 NotABinaryOrUnaryExpression,
4277 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4278 NotAnUnaryIncDecExpression,
4279 /// \brief An expression is not of scalar type.
4280 NotAScalarType,
4281 /// \brief A binary operation is not an assignment operation.
4282 NotAnAssignmentOp,
4283 /// \brief RHS part of the binary operation is not a binary expression.
4284 NotABinaryExpression,
4285 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4286 /// expression.
4287 NotABinaryOperator,
4288 /// \brief RHS binary operation does not have reference to the updated LHS
4289 /// part.
4290 NotAnUpdateExpression,
4291 /// \brief No errors is found.
4292 NoError
4293 };
4294 /// \brief Reference to Sema.
4295 Sema &SemaRef;
4296 /// \brief A location for note diagnostics (when error is found).
4297 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004298 /// \brief 'x' lvalue part of the source atomic expression.
4299 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004300 /// \brief 'expr' rvalue part of the source atomic expression.
4301 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004302 /// \brief Helper expression of the form
4303 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4304 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4305 Expr *UpdateExpr;
4306 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4307 /// important for non-associative operations.
4308 bool IsXLHSInRHSPart;
4309 BinaryOperatorKind Op;
4310 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004311 /// \brief true if the source expression is a postfix unary operation, false
4312 /// if it is a prefix unary operation.
4313 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004314
4315public:
4316 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004317 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004318 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004319 /// \brief Check specified statement that it is suitable for 'atomic update'
4320 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004321 /// expression. If DiagId and NoteId == 0, then only check is performed
4322 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004323 /// \param DiagId Diagnostic which should be emitted if error is found.
4324 /// \param NoteId Diagnostic note for the main error message.
4325 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004326 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004327 /// \brief Return the 'x' lvalue part of the source atomic expression.
4328 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004329 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4330 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004331 /// \brief Return the update expression used in calculation of the updated
4332 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4333 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4334 Expr *getUpdateExpr() const { return UpdateExpr; }
4335 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4336 /// false otherwise.
4337 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4338
Alexey Bataevb78ca832015-04-01 03:33:17 +00004339 /// \brief true if the source expression is a postfix unary operation, false
4340 /// if it is a prefix unary operation.
4341 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4342
Alexey Bataev1d160b12015-03-13 12:27:31 +00004343private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004344 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4345 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004346};
4347} // namespace
4348
4349bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4350 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4351 ExprAnalysisErrorCode ErrorFound = NoError;
4352 SourceLocation ErrorLoc, NoteLoc;
4353 SourceRange ErrorRange, NoteRange;
4354 // Allowed constructs are:
4355 // x = x binop expr;
4356 // x = expr binop x;
4357 if (AtomicBinOp->getOpcode() == BO_Assign) {
4358 X = AtomicBinOp->getLHS();
4359 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4360 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4361 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4362 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4363 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004364 Op = AtomicInnerBinOp->getOpcode();
4365 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004366 auto *LHS = AtomicInnerBinOp->getLHS();
4367 auto *RHS = AtomicInnerBinOp->getRHS();
4368 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4369 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4370 /*Canonical=*/true);
4371 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4372 /*Canonical=*/true);
4373 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4374 /*Canonical=*/true);
4375 if (XId == LHSId) {
4376 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004377 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004378 } else if (XId == RHSId) {
4379 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004380 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004381 } else {
4382 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4383 ErrorRange = AtomicInnerBinOp->getSourceRange();
4384 NoteLoc = X->getExprLoc();
4385 NoteRange = X->getSourceRange();
4386 ErrorFound = NotAnUpdateExpression;
4387 }
4388 } else {
4389 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4390 ErrorRange = AtomicInnerBinOp->getSourceRange();
4391 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4392 NoteRange = SourceRange(NoteLoc, NoteLoc);
4393 ErrorFound = NotABinaryOperator;
4394 }
4395 } else {
4396 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4397 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4398 ErrorFound = NotABinaryExpression;
4399 }
4400 } else {
4401 ErrorLoc = AtomicBinOp->getExprLoc();
4402 ErrorRange = AtomicBinOp->getSourceRange();
4403 NoteLoc = AtomicBinOp->getOperatorLoc();
4404 NoteRange = SourceRange(NoteLoc, NoteLoc);
4405 ErrorFound = NotAnAssignmentOp;
4406 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004407 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004408 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4409 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4410 return true;
4411 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004412 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004413 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004414}
4415
4416bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4417 unsigned NoteId) {
4418 ExprAnalysisErrorCode ErrorFound = NoError;
4419 SourceLocation ErrorLoc, NoteLoc;
4420 SourceRange ErrorRange, NoteRange;
4421 // Allowed constructs are:
4422 // x++;
4423 // x--;
4424 // ++x;
4425 // --x;
4426 // x binop= expr;
4427 // x = x binop expr;
4428 // x = expr binop x;
4429 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4430 AtomicBody = AtomicBody->IgnoreParenImpCasts();
4431 if (AtomicBody->getType()->isScalarType() ||
4432 AtomicBody->isInstantiationDependent()) {
4433 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4434 AtomicBody->IgnoreParenImpCasts())) {
4435 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004436 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00004437 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00004438 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004439 E = AtomicCompAssignOp->getRHS();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004440 X = AtomicCompAssignOp->getLHS();
4441 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004442 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4443 AtomicBody->IgnoreParenImpCasts())) {
4444 // Check for Binary Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00004445 if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4446 return true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004447 } else if (auto *AtomicUnaryOp =
Alexey Bataev1d160b12015-03-13 12:27:31 +00004448 dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
4449 // Check for Unary Operation
4450 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004451 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004452 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4453 OpLoc = AtomicUnaryOp->getOperatorLoc();
4454 X = AtomicUnaryOp->getSubExpr();
4455 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4456 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004457 } else {
4458 ErrorFound = NotAnUnaryIncDecExpression;
4459 ErrorLoc = AtomicUnaryOp->getExprLoc();
4460 ErrorRange = AtomicUnaryOp->getSourceRange();
4461 NoteLoc = AtomicUnaryOp->getOperatorLoc();
4462 NoteRange = SourceRange(NoteLoc, NoteLoc);
4463 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004464 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004465 ErrorFound = NotABinaryOrUnaryExpression;
4466 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4467 NoteRange = ErrorRange = AtomicBody->getSourceRange();
4468 }
4469 } else {
4470 ErrorFound = NotAScalarType;
4471 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4472 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4473 }
4474 } else {
4475 ErrorFound = NotAnExpression;
4476 NoteLoc = ErrorLoc = S->getLocStart();
4477 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4478 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004479 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004480 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4481 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4482 return true;
4483 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004484 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004485 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004486 // Build an update expression of form 'OpaqueValueExpr(x) binop
4487 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4488 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4489 auto *OVEX = new (SemaRef.getASTContext())
4490 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4491 auto *OVEExpr = new (SemaRef.getASTContext())
4492 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4493 auto Update =
4494 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4495 IsXLHSInRHSPart ? OVEExpr : OVEX);
4496 if (Update.isInvalid())
4497 return true;
4498 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4499 Sema::AA_Casting);
4500 if (Update.isInvalid())
4501 return true;
4502 UpdateExpr = Update.get();
4503 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00004504 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004505}
4506
Alexey Bataev0162e452014-07-22 10:10:35 +00004507StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4508 Stmt *AStmt,
4509 SourceLocation StartLoc,
4510 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004511 if (!AStmt)
4512 return StmtError();
4513
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004514 auto CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00004515 // 1.2.2 OpenMP Language Terminology
4516 // Structured block - An executable statement with a single entry at the
4517 // top and a single exit at the bottom.
4518 // The point of exit cannot be a branch out of the structured block.
4519 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00004520 OpenMPClauseKind AtomicKind = OMPC_unknown;
4521 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004522 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00004523 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00004524 C->getClauseKind() == OMPC_update ||
4525 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00004526 if (AtomicKind != OMPC_unknown) {
4527 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4528 << SourceRange(C->getLocStart(), C->getLocEnd());
4529 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4530 << getOpenMPClauseName(AtomicKind);
4531 } else {
4532 AtomicKind = C->getClauseKind();
4533 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00004534 }
4535 }
4536 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004537
Alexey Bataev459dec02014-07-24 06:46:57 +00004538 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00004539 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4540 Body = EWC->getSubExpr();
4541
Alexey Bataev62cec442014-11-18 10:14:22 +00004542 Expr *X = nullptr;
4543 Expr *V = nullptr;
4544 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004545 Expr *UE = nullptr;
4546 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004547 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00004548 // OpenMP [2.12.6, atomic Construct]
4549 // In the next expressions:
4550 // * x and v (as applicable) are both l-value expressions with scalar type.
4551 // * During the execution of an atomic region, multiple syntactic
4552 // occurrences of x must designate the same storage location.
4553 // * Neither of v and expr (as applicable) may access the storage location
4554 // designated by x.
4555 // * Neither of x and expr (as applicable) may access the storage location
4556 // designated by v.
4557 // * expr is an expression with scalar type.
4558 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
4559 // * binop, binop=, ++, and -- are not overloaded operators.
4560 // * The expression x binop expr must be numerically equivalent to x binop
4561 // (expr). This requirement is satisfied if the operators in expr have
4562 // precedence greater than binop, or by using parentheses around expr or
4563 // subexpressions of expr.
4564 // * The expression expr binop x must be numerically equivalent to (expr)
4565 // binop x. This requirement is satisfied if the operators in expr have
4566 // precedence equal to or greater than binop, or by using parentheses around
4567 // expr or subexpressions of expr.
4568 // * For forms that allow multiple occurrences of x, the number of times
4569 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00004570 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004571 enum {
4572 NotAnExpression,
4573 NotAnAssignmentOp,
4574 NotAScalarType,
4575 NotAnLValue,
4576 NoError
4577 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00004578 SourceLocation ErrorLoc, NoteLoc;
4579 SourceRange ErrorRange, NoteRange;
4580 // If clause is read:
4581 // v = x;
4582 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4583 auto AtomicBinOp =
4584 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4585 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4586 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4587 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
4588 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4589 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
4590 if (!X->isLValue() || !V->isLValue()) {
4591 auto NotLValueExpr = X->isLValue() ? V : X;
4592 ErrorFound = NotAnLValue;
4593 ErrorLoc = AtomicBinOp->getExprLoc();
4594 ErrorRange = AtomicBinOp->getSourceRange();
4595 NoteLoc = NotLValueExpr->getExprLoc();
4596 NoteRange = NotLValueExpr->getSourceRange();
4597 }
4598 } else if (!X->isInstantiationDependent() ||
4599 !V->isInstantiationDependent()) {
4600 auto NotScalarExpr =
4601 (X->isInstantiationDependent() || X->getType()->isScalarType())
4602 ? V
4603 : X;
4604 ErrorFound = NotAScalarType;
4605 ErrorLoc = AtomicBinOp->getExprLoc();
4606 ErrorRange = AtomicBinOp->getSourceRange();
4607 NoteLoc = NotScalarExpr->getExprLoc();
4608 NoteRange = NotScalarExpr->getSourceRange();
4609 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004610 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00004611 ErrorFound = NotAnAssignmentOp;
4612 ErrorLoc = AtomicBody->getExprLoc();
4613 ErrorRange = AtomicBody->getSourceRange();
4614 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4615 : AtomicBody->getExprLoc();
4616 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4617 : AtomicBody->getSourceRange();
4618 }
4619 } else {
4620 ErrorFound = NotAnExpression;
4621 NoteLoc = ErrorLoc = Body->getLocStart();
4622 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004623 }
Alexey Bataev62cec442014-11-18 10:14:22 +00004624 if (ErrorFound != NoError) {
4625 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
4626 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004627 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4628 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00004629 return StmtError();
4630 } else if (CurContext->isDependentContext())
4631 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00004632 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004633 enum {
4634 NotAnExpression,
4635 NotAnAssignmentOp,
4636 NotAScalarType,
4637 NotAnLValue,
4638 NoError
4639 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00004640 SourceLocation ErrorLoc, NoteLoc;
4641 SourceRange ErrorRange, NoteRange;
4642 // If clause is write:
4643 // x = expr;
4644 if (auto AtomicBody = dyn_cast<Expr>(Body)) {
4645 auto AtomicBinOp =
4646 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4647 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00004648 X = AtomicBinOp->getLHS();
4649 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00004650 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4651 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
4652 if (!X->isLValue()) {
4653 ErrorFound = NotAnLValue;
4654 ErrorLoc = AtomicBinOp->getExprLoc();
4655 ErrorRange = AtomicBinOp->getSourceRange();
4656 NoteLoc = X->getExprLoc();
4657 NoteRange = X->getSourceRange();
4658 }
4659 } else if (!X->isInstantiationDependent() ||
4660 !E->isInstantiationDependent()) {
4661 auto NotScalarExpr =
4662 (X->isInstantiationDependent() || X->getType()->isScalarType())
4663 ? E
4664 : X;
4665 ErrorFound = NotAScalarType;
4666 ErrorLoc = AtomicBinOp->getExprLoc();
4667 ErrorRange = AtomicBinOp->getSourceRange();
4668 NoteLoc = NotScalarExpr->getExprLoc();
4669 NoteRange = NotScalarExpr->getSourceRange();
4670 }
Alexey Bataev5a195472015-09-04 12:55:50 +00004671 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00004672 ErrorFound = NotAnAssignmentOp;
4673 ErrorLoc = AtomicBody->getExprLoc();
4674 ErrorRange = AtomicBody->getSourceRange();
4675 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4676 : AtomicBody->getExprLoc();
4677 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4678 : AtomicBody->getSourceRange();
4679 }
4680 } else {
4681 ErrorFound = NotAnExpression;
4682 NoteLoc = ErrorLoc = Body->getLocStart();
4683 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00004684 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00004685 if (ErrorFound != NoError) {
4686 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
4687 << ErrorRange;
4688 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4689 << NoteRange;
4690 return StmtError();
4691 } else if (CurContext->isDependentContext())
4692 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00004693 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004694 // If clause is update:
4695 // x++;
4696 // x--;
4697 // ++x;
4698 // --x;
4699 // x binop= expr;
4700 // x = x binop expr;
4701 // x = expr binop x;
4702 OpenMPAtomicUpdateChecker Checker(*this);
4703 if (Checker.checkStatement(
4704 Body, (AtomicKind == OMPC_update)
4705 ? diag::err_omp_atomic_update_not_expression_statement
4706 : diag::err_omp_atomic_not_expression_statement,
4707 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00004708 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004709 if (!CurContext->isDependentContext()) {
4710 E = Checker.getExpr();
4711 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00004712 UE = Checker.getUpdateExpr();
4713 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00004714 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004715 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004716 enum {
4717 NotAnAssignmentOp,
4718 NotACompoundStatement,
4719 NotTwoSubstatements,
4720 NotASpecificExpression,
4721 NoError
4722 } ErrorFound = NoError;
4723 SourceLocation ErrorLoc, NoteLoc;
4724 SourceRange ErrorRange, NoteRange;
4725 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
4726 // If clause is a capture:
4727 // v = x++;
4728 // v = x--;
4729 // v = ++x;
4730 // v = --x;
4731 // v = x binop= expr;
4732 // v = x = x binop expr;
4733 // v = x = expr binop x;
4734 auto *AtomicBinOp =
4735 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4736 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4737 V = AtomicBinOp->getLHS();
4738 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4739 OpenMPAtomicUpdateChecker Checker(*this);
4740 if (Checker.checkStatement(
4741 Body, diag::err_omp_atomic_capture_not_expression_statement,
4742 diag::note_omp_atomic_update))
4743 return StmtError();
4744 E = Checker.getExpr();
4745 X = Checker.getX();
4746 UE = Checker.getUpdateExpr();
4747 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4748 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00004749 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004750 ErrorLoc = AtomicBody->getExprLoc();
4751 ErrorRange = AtomicBody->getSourceRange();
4752 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4753 : AtomicBody->getExprLoc();
4754 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4755 : AtomicBody->getSourceRange();
4756 ErrorFound = NotAnAssignmentOp;
4757 }
4758 if (ErrorFound != NoError) {
4759 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
4760 << ErrorRange;
4761 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4762 return StmtError();
4763 } else if (CurContext->isDependentContext()) {
4764 UE = V = E = X = nullptr;
4765 }
4766 } else {
4767 // If clause is a capture:
4768 // { v = x; x = expr; }
4769 // { v = x; x++; }
4770 // { v = x; x--; }
4771 // { v = x; ++x; }
4772 // { v = x; --x; }
4773 // { v = x; x binop= expr; }
4774 // { v = x; x = x binop expr; }
4775 // { v = x; x = expr binop x; }
4776 // { x++; v = x; }
4777 // { x--; v = x; }
4778 // { ++x; v = x; }
4779 // { --x; v = x; }
4780 // { x binop= expr; v = x; }
4781 // { x = x binop expr; v = x; }
4782 // { x = expr binop x; v = x; }
4783 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4784 // Check that this is { expr1; expr2; }
4785 if (CS->size() == 2) {
4786 auto *First = CS->body_front();
4787 auto *Second = CS->body_back();
4788 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4789 First = EWC->getSubExpr()->IgnoreParenImpCasts();
4790 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4791 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4792 // Need to find what subexpression is 'v' and what is 'x'.
4793 OpenMPAtomicUpdateChecker Checker(*this);
4794 bool IsUpdateExprFound = !Checker.checkStatement(Second);
4795 BinaryOperator *BinOp = nullptr;
4796 if (IsUpdateExprFound) {
4797 BinOp = dyn_cast<BinaryOperator>(First);
4798 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4799 }
4800 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4801 // { v = x; x++; }
4802 // { v = x; x--; }
4803 // { v = x; ++x; }
4804 // { v = x; --x; }
4805 // { v = x; x binop= expr; }
4806 // { v = x; x = x binop expr; }
4807 // { v = x; x = expr binop x; }
4808 // Check that the first expression has form v = x.
4809 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4810 llvm::FoldingSetNodeID XId, PossibleXId;
4811 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4812 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4813 IsUpdateExprFound = XId == PossibleXId;
4814 if (IsUpdateExprFound) {
4815 V = BinOp->getLHS();
4816 X = Checker.getX();
4817 E = Checker.getExpr();
4818 UE = Checker.getUpdateExpr();
4819 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004820 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004821 }
4822 }
4823 if (!IsUpdateExprFound) {
4824 IsUpdateExprFound = !Checker.checkStatement(First);
4825 BinOp = nullptr;
4826 if (IsUpdateExprFound) {
4827 BinOp = dyn_cast<BinaryOperator>(Second);
4828 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4829 }
4830 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4831 // { x++; v = x; }
4832 // { x--; v = x; }
4833 // { ++x; v = x; }
4834 // { --x; v = x; }
4835 // { x binop= expr; v = x; }
4836 // { x = x binop expr; v = x; }
4837 // { x = expr binop x; v = x; }
4838 // Check that the second expression has form v = x.
4839 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4840 llvm::FoldingSetNodeID XId, PossibleXId;
4841 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4842 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4843 IsUpdateExprFound = XId == PossibleXId;
4844 if (IsUpdateExprFound) {
4845 V = BinOp->getLHS();
4846 X = Checker.getX();
4847 E = Checker.getExpr();
4848 UE = Checker.getUpdateExpr();
4849 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00004850 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004851 }
4852 }
4853 }
4854 if (!IsUpdateExprFound) {
4855 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00004856 auto *FirstExpr = dyn_cast<Expr>(First);
4857 auto *SecondExpr = dyn_cast<Expr>(Second);
4858 if (!FirstExpr || !SecondExpr ||
4859 !(FirstExpr->isInstantiationDependent() ||
4860 SecondExpr->isInstantiationDependent())) {
4861 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4862 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00004863 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00004864 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4865 : First->getLocStart();
4866 NoteRange = ErrorRange = FirstBinOp
4867 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00004868 : SourceRange(ErrorLoc, ErrorLoc);
4869 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004870 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4871 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4872 ErrorFound = NotAnAssignmentOp;
4873 NoteLoc = ErrorLoc = SecondBinOp
4874 ? SecondBinOp->getOperatorLoc()
4875 : Second->getLocStart();
4876 NoteRange = ErrorRange =
4877 SecondBinOp ? SecondBinOp->getSourceRange()
4878 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00004879 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00004880 auto *PossibleXRHSInFirst =
4881 FirstBinOp->getRHS()->IgnoreParenImpCasts();
4882 auto *PossibleXLHSInSecond =
4883 SecondBinOp->getLHS()->IgnoreParenImpCasts();
4884 llvm::FoldingSetNodeID X1Id, X2Id;
4885 PossibleXRHSInFirst->Profile(X1Id, Context,
4886 /*Canonical=*/true);
4887 PossibleXLHSInSecond->Profile(X2Id, Context,
4888 /*Canonical=*/true);
4889 IsUpdateExprFound = X1Id == X2Id;
4890 if (IsUpdateExprFound) {
4891 V = FirstBinOp->getLHS();
4892 X = SecondBinOp->getLHS();
4893 E = SecondBinOp->getRHS();
4894 UE = nullptr;
4895 IsXLHSInRHSPart = false;
4896 IsPostfixUpdate = true;
4897 } else {
4898 ErrorFound = NotASpecificExpression;
4899 ErrorLoc = FirstBinOp->getExprLoc();
4900 ErrorRange = FirstBinOp->getSourceRange();
4901 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4902 NoteRange = SecondBinOp->getRHS()->getSourceRange();
4903 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004904 }
4905 }
4906 }
4907 }
4908 } else {
4909 NoteLoc = ErrorLoc = Body->getLocStart();
4910 NoteRange = ErrorRange =
4911 SourceRange(Body->getLocStart(), Body->getLocStart());
4912 ErrorFound = NotTwoSubstatements;
4913 }
4914 } else {
4915 NoteLoc = ErrorLoc = Body->getLocStart();
4916 NoteRange = ErrorRange =
4917 SourceRange(Body->getLocStart(), Body->getLocStart());
4918 ErrorFound = NotACompoundStatement;
4919 }
4920 if (ErrorFound != NoError) {
4921 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4922 << ErrorRange;
4923 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4924 return StmtError();
4925 } else if (CurContext->isDependentContext()) {
4926 UE = V = E = X = nullptr;
4927 }
Alexey Bataev459dec02014-07-24 06:46:57 +00004928 }
Alexey Bataevdea47612014-07-23 07:46:59 +00004929 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004930
4931 getCurFunction()->setHasBranchProtectedScope();
4932
Alexey Bataev62cec442014-11-18 10:14:22 +00004933 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00004934 X, V, E, UE, IsXLHSInRHSPart,
4935 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00004936}
4937
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004938StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4939 Stmt *AStmt,
4940 SourceLocation StartLoc,
4941 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004942 if (!AStmt)
4943 return StmtError();
4944
4945 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004946
Alexey Bataev13314bf2014-10-09 04:18:56 +00004947 // OpenMP [2.16, Nesting of Regions]
4948 // If specified, a teams construct must be contained within a target
4949 // construct. That target construct must contain no statements or directives
4950 // outside of the teams construct.
4951 if (DSAStack->hasInnerTeamsRegion()) {
4952 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4953 bool OMPTeamsFound = true;
4954 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4955 auto I = CS->body_begin();
4956 while (I != CS->body_end()) {
4957 auto OED = dyn_cast<OMPExecutableDirective>(*I);
4958 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4959 OMPTeamsFound = false;
4960 break;
4961 }
4962 ++I;
4963 }
4964 assert(I != CS->body_end() && "Not found statement");
4965 S = *I;
4966 }
4967 if (!OMPTeamsFound) {
4968 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4969 Diag(DSAStack->getInnerTeamsRegionLoc(),
4970 diag::note_omp_nested_teams_construct_here);
4971 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4972 << isa<OMPExecutableDirective>(S);
4973 return StmtError();
4974 }
4975 }
4976
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004977 getCurFunction()->setHasBranchProtectedScope();
4978
4979 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4980}
4981
Michael Wong65f367f2015-07-21 13:44:28 +00004982StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
4983 Stmt *AStmt,
4984 SourceLocation StartLoc,
4985 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004986 if (!AStmt)
4987 return StmtError();
4988
4989 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4990
Michael Wong65f367f2015-07-21 13:44:28 +00004991 getCurFunction()->setHasBranchProtectedScope();
4992
4993 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
4994 AStmt);
4995}
4996
Alexey Bataev13314bf2014-10-09 04:18:56 +00004997StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4998 Stmt *AStmt, SourceLocation StartLoc,
4999 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005000 if (!AStmt)
5001 return StmtError();
5002
Alexey Bataev13314bf2014-10-09 04:18:56 +00005003 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5004 // 1.2.2 OpenMP Language Terminology
5005 // Structured block - An executable statement with a single entry at the
5006 // top and a single exit at the bottom.
5007 // The point of exit cannot be a branch out of the structured block.
5008 // longjmp() and throw() must not violate the entry/exit criteria.
5009 CS->getCapturedDecl()->setNothrow();
5010
5011 getCurFunction()->setHasBranchProtectedScope();
5012
5013 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5014}
5015
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005016StmtResult
5017Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5018 SourceLocation EndLoc,
5019 OpenMPDirectiveKind CancelRegion) {
5020 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5021 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5022 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5023 << getOpenMPDirectiveName(CancelRegion);
5024 return StmtError();
5025 }
5026 if (DSAStack->isParentNowaitRegion()) {
5027 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5028 return StmtError();
5029 }
5030 if (DSAStack->isParentOrderedRegion()) {
5031 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5032 return StmtError();
5033 }
5034 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5035 CancelRegion);
5036}
5037
Alexey Bataev87933c72015-09-18 08:07:34 +00005038StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5039 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005040 SourceLocation EndLoc,
5041 OpenMPDirectiveKind CancelRegion) {
5042 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5043 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5044 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5045 << getOpenMPDirectiveName(CancelRegion);
5046 return StmtError();
5047 }
5048 if (DSAStack->isParentNowaitRegion()) {
5049 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5050 return StmtError();
5051 }
5052 if (DSAStack->isParentOrderedRegion()) {
5053 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5054 return StmtError();
5055 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005056 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005057 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5058 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005059}
5060
Alexey Bataeved09d242014-05-28 05:53:51 +00005061OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005062 SourceLocation StartLoc,
5063 SourceLocation LParenLoc,
5064 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005065 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005066 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00005067 case OMPC_final:
5068 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
5069 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00005070 case OMPC_num_threads:
5071 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
5072 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005073 case OMPC_safelen:
5074 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
5075 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00005076 case OMPC_simdlen:
5077 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
5078 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00005079 case OMPC_collapse:
5080 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
5081 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005082 case OMPC_ordered:
5083 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
5084 break;
Michael Wonge710d542015-08-07 16:16:36 +00005085 case OMPC_device:
5086 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
5087 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00005088 case OMPC_num_teams:
5089 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
5090 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005091 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005092 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005093 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005094 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005095 case OMPC_private:
5096 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005097 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005098 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005099 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005100 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005101 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005102 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005103 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00005104 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005105 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005106 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005107 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005108 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005109 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005110 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005111 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005112 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005113 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005114 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00005115 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005116 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005117 case OMPC_map:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005118 case OMPC_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005119 llvm_unreachable("Clause is not allowed.");
5120 }
5121 return Res;
5122}
5123
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005124OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
5125 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005126 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005127 SourceLocation NameModifierLoc,
5128 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005129 SourceLocation EndLoc) {
5130 Expr *ValExpr = Condition;
5131 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5132 !Condition->isInstantiationDependent() &&
5133 !Condition->containsUnexpandedParameterPack()) {
5134 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
Alexey Bataeved09d242014-05-28 05:53:51 +00005135 Condition->getExprLoc(), Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005136 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005137 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005138
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005139 ValExpr = Val.get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005140 }
5141
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005142 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
5143 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005144}
5145
Alexey Bataev3778b602014-07-17 07:32:53 +00005146OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
5147 SourceLocation StartLoc,
5148 SourceLocation LParenLoc,
5149 SourceLocation EndLoc) {
5150 Expr *ValExpr = Condition;
5151 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5152 !Condition->isInstantiationDependent() &&
5153 !Condition->containsUnexpandedParameterPack()) {
5154 ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5155 Condition->getExprLoc(), Condition);
5156 if (Val.isInvalid())
5157 return nullptr;
5158
5159 ValExpr = Val.get();
5160 }
5161
5162 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5163}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005164ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
5165 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00005166 if (!Op)
5167 return ExprError();
5168
5169 class IntConvertDiagnoser : public ICEConvertDiagnoser {
5170 public:
5171 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00005172 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00005173 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
5174 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005175 return S.Diag(Loc, diag::err_omp_not_integral) << T;
5176 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005177 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
5178 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005179 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
5180 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005181 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
5182 QualType T,
5183 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005184 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
5185 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005186 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
5187 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005188 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005189 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005190 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005191 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
5192 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005193 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
5194 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005195 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
5196 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005197 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00005198 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00005199 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005200 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
5201 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00005202 llvm_unreachable("conversion functions are permitted");
5203 }
5204 } ConvertDiagnoser;
5205 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
5206}
5207
5208OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
5209 SourceLocation StartLoc,
5210 SourceLocation LParenLoc,
5211 SourceLocation EndLoc) {
5212 Expr *ValExpr = NumThreads;
5213 if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
Alexey Bataev568a8332014-03-06 06:15:19 +00005214 !NumThreads->containsUnexpandedParameterPack()) {
5215 SourceLocation NumThreadsLoc = NumThreads->getLocStart();
5216 ExprResult Val =
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005217 PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
Alexey Bataev568a8332014-03-06 06:15:19 +00005218 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005219 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00005220
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005221 ValExpr = Val.get();
Alexey Bataev568a8332014-03-06 06:15:19 +00005222
5223 // OpenMP [2.5, Restrictions]
5224 // The num_threads expression must evaluate to a positive integer value.
5225 llvm::APSInt Result;
Alexey Bataeved09d242014-05-28 05:53:51 +00005226 if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
5227 !Result.isStrictlyPositive()) {
Alexey Bataev568a8332014-03-06 06:15:19 +00005228 Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
5229 << "num_threads" << NumThreads->getSourceRange();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005230 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00005231 }
5232 }
5233
Alexey Bataeved09d242014-05-28 05:53:51 +00005234 return new (Context)
5235 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00005236}
5237
Alexey Bataev62c87d22014-03-21 04:51:18 +00005238ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
5239 OpenMPClauseKind CKind) {
5240 if (!E)
5241 return ExprError();
5242 if (E->isValueDependent() || E->isTypeDependent() ||
5243 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005244 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005245 llvm::APSInt Result;
5246 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
5247 if (ICE.isInvalid())
5248 return ExprError();
5249 if (!Result.isStrictlyPositive()) {
5250 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
5251 << getOpenMPClauseName(CKind) << E->getSourceRange();
5252 return ExprError();
5253 }
Alexander Musman09184fe2014-09-30 05:29:28 +00005254 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
5255 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
5256 << E->getSourceRange();
5257 return ExprError();
5258 }
Alexey Bataev9c821032015-04-30 04:23:23 +00005259 if (CKind == OMPC_collapse) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005260 DSAStack->setCollapseNumber(DSAStack->getCollapseNumber() - 1 +
5261 Result.getExtValue());
5262 } else if (CKind == OMPC_ordered) {
5263 DSAStack->setCollapseNumber(DSAStack->getCollapseNumber() - 1 +
5264 Result.getExtValue());
Alexey Bataev9c821032015-04-30 04:23:23 +00005265 }
Alexey Bataev62c87d22014-03-21 04:51:18 +00005266 return ICE;
5267}
5268
5269OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
5270 SourceLocation LParenLoc,
5271 SourceLocation EndLoc) {
5272 // OpenMP [2.8.1, simd construct, Description]
5273 // The parameter of the safelen clause must be a constant
5274 // positive integer expression.
5275 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
5276 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005277 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00005278 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005279 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00005280}
5281
Alexey Bataev66b15b52015-08-21 11:14:16 +00005282OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
5283 SourceLocation LParenLoc,
5284 SourceLocation EndLoc) {
5285 // OpenMP [2.8.1, simd construct, Description]
5286 // The parameter of the simdlen clause must be a constant
5287 // positive integer expression.
5288 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
5289 if (Simdlen.isInvalid())
5290 return nullptr;
5291 return new (Context)
5292 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
5293}
5294
Alexander Musman64d33f12014-06-04 07:53:32 +00005295OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
5296 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00005297 SourceLocation LParenLoc,
5298 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00005299 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005300 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00005301 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00005302 // The parameter of the collapse clause must be a constant
5303 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00005304 ExprResult NumForLoopsResult =
5305 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
5306 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00005307 return nullptr;
5308 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00005309 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00005310}
5311
Alexey Bataev10e775f2015-07-30 11:36:16 +00005312OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5313 SourceLocation EndLoc,
5314 SourceLocation LParenLoc,
5315 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005316 // OpenMP [2.7.1, loop construct, Description]
5317 // OpenMP [2.8.1, simd construct, Description]
5318 // OpenMP [2.9.6, distribute construct, Description]
5319 // The parameter of the ordered clause must be a constant
5320 // positive integer expression if any.
5321 if (NumForLoops && LParenLoc.isValid()) {
5322 ExprResult NumForLoopsResult =
5323 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
5324 if (NumForLoopsResult.isInvalid())
5325 return nullptr;
5326 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00005327 } else
5328 NumForLoops = nullptr;
5329 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00005330 return new (Context)
5331 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
5332}
5333
Alexey Bataeved09d242014-05-28 05:53:51 +00005334OMPClause *Sema::ActOnOpenMPSimpleClause(
5335 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
5336 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005337 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005338 switch (Kind) {
5339 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005340 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00005341 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
5342 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005343 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005344 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00005345 Res = ActOnOpenMPProcBindClause(
5346 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
5347 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005348 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005349 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005350 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005351 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005352 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005353 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005354 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005355 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005356 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005357 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00005358 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00005359 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00005360 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00005361 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005362 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005363 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005364 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005365 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005366 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005367 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005368 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005369 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005370 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005371 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005372 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005373 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005374 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005375 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005376 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005377 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005378 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005379 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005380 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005381 case OMPC_num_teams:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005382 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005383 llvm_unreachable("Clause is not allowed.");
5384 }
5385 return Res;
5386}
5387
5388OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
5389 SourceLocation KindKwLoc,
5390 SourceLocation StartLoc,
5391 SourceLocation LParenLoc,
5392 SourceLocation EndLoc) {
5393 if (Kind == OMPC_DEFAULT_unknown) {
5394 std::string Values;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005395 static_assert(OMPC_DEFAULT_unknown > 0,
5396 "OMPC_DEFAULT_unknown not greater than 0");
Ted Kremenek725a0972014-03-21 17:34:28 +00005397 std::string Sep(", ");
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005398 for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005399 Values += "'";
5400 Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
5401 Values += "'";
5402 switch (i) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005403 case OMPC_DEFAULT_unknown - 2:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005404 Values += " or ";
5405 break;
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00005406 case OMPC_DEFAULT_unknown - 1:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005407 break;
5408 default:
5409 Values += Sep;
5410 break;
5411 }
5412 }
5413 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005414 << Values << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005415 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005416 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00005417 switch (Kind) {
5418 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005419 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005420 break;
5421 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005422 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005423 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005424 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005425 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00005426 break;
5427 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005428 return new (Context)
5429 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005430}
5431
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005432OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
5433 SourceLocation KindKwLoc,
5434 SourceLocation StartLoc,
5435 SourceLocation LParenLoc,
5436 SourceLocation EndLoc) {
5437 if (Kind == OMPC_PROC_BIND_unknown) {
5438 std::string Values;
5439 std::string Sep(", ");
5440 for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
5441 Values += "'";
5442 Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
5443 Values += "'";
5444 switch (i) {
5445 case OMPC_PROC_BIND_unknown - 2:
5446 Values += " or ";
5447 break;
5448 case OMPC_PROC_BIND_unknown - 1:
5449 break;
5450 default:
5451 Values += Sep;
5452 break;
5453 }
5454 }
5455 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataeved09d242014-05-28 05:53:51 +00005456 << Values << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005457 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005458 }
Alexey Bataeved09d242014-05-28 05:53:51 +00005459 return new (Context)
5460 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005461}
5462
Alexey Bataev56dafe82014-06-20 07:16:17 +00005463OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
5464 OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
5465 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005466 SourceLocation ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00005467 SourceLocation EndLoc) {
5468 OMPClause *Res = nullptr;
5469 switch (Kind) {
5470 case OMPC_schedule:
5471 Res = ActOnOpenMPScheduleClause(
5472 static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005473 LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005474 break;
5475 case OMPC_if:
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005476 Res =
5477 ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument), Expr,
5478 StartLoc, LParenLoc, ArgumentLoc, DelimLoc, EndLoc);
5479 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00005480 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005481 case OMPC_num_threads:
5482 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005483 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005484 case OMPC_collapse:
5485 case OMPC_default:
5486 case OMPC_proc_bind:
5487 case OMPC_private:
5488 case OMPC_firstprivate:
5489 case OMPC_lastprivate:
5490 case OMPC_shared:
5491 case OMPC_reduction:
5492 case OMPC_linear:
5493 case OMPC_aligned:
5494 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005495 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005496 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005497 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005498 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005499 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005500 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005501 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005502 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005503 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005504 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005505 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005506 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005507 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005508 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005509 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005510 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005511 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005512 case OMPC_num_teams:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005513 case OMPC_unknown:
5514 llvm_unreachable("Clause is not allowed.");
5515 }
5516 return Res;
5517}
5518
5519OMPClause *Sema::ActOnOpenMPScheduleClause(
5520 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
5521 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
5522 SourceLocation EndLoc) {
5523 if (Kind == OMPC_SCHEDULE_unknown) {
5524 std::string Values;
5525 std::string Sep(", ");
5526 for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
5527 Values += "'";
5528 Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
5529 Values += "'";
5530 switch (i) {
5531 case OMPC_SCHEDULE_unknown - 2:
5532 Values += " or ";
5533 break;
5534 case OMPC_SCHEDULE_unknown - 1:
5535 break;
5536 default:
5537 Values += Sep;
5538 break;
5539 }
5540 }
5541 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
5542 << Values << getOpenMPClauseName(OMPC_schedule);
5543 return nullptr;
5544 }
5545 Expr *ValExpr = ChunkSize;
Alexey Bataev040d5402015-05-12 08:35:28 +00005546 Expr *HelperValExpr = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005547 if (ChunkSize) {
5548 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
5549 !ChunkSize->isInstantiationDependent() &&
5550 !ChunkSize->containsUnexpandedParameterPack()) {
5551 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
5552 ExprResult Val =
5553 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
5554 if (Val.isInvalid())
5555 return nullptr;
5556
5557 ValExpr = Val.get();
5558
5559 // OpenMP [2.7.1, Restrictions]
5560 // chunk_size must be a loop invariant integer expression with a positive
5561 // value.
5562 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00005563 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
5564 if (Result.isSigned() && !Result.isStrictlyPositive()) {
5565 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
5566 << "schedule" << ChunkSize->getSourceRange();
5567 return nullptr;
5568 }
5569 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
5570 auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
5571 ChunkSize->getType(), ".chunk.");
5572 auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
5573 ChunkSize->getExprLoc(),
5574 /*RefersToCapture=*/true);
5575 HelperValExpr = ImpVarRef;
Alexey Bataev56dafe82014-06-20 07:16:17 +00005576 }
5577 }
5578 }
5579
5580 return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
Alexey Bataev040d5402015-05-12 08:35:28 +00005581 EndLoc, Kind, ValExpr, HelperValExpr);
Alexey Bataev56dafe82014-06-20 07:16:17 +00005582}
5583
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005584OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
5585 SourceLocation StartLoc,
5586 SourceLocation EndLoc) {
5587 OMPClause *Res = nullptr;
5588 switch (Kind) {
5589 case OMPC_ordered:
5590 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
5591 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00005592 case OMPC_nowait:
5593 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
5594 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005595 case OMPC_untied:
5596 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
5597 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005598 case OMPC_mergeable:
5599 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
5600 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005601 case OMPC_read:
5602 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
5603 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00005604 case OMPC_write:
5605 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
5606 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005607 case OMPC_update:
5608 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
5609 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00005610 case OMPC_capture:
5611 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
5612 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005613 case OMPC_seq_cst:
5614 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
5615 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00005616 case OMPC_threads:
5617 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
5618 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005619 case OMPC_simd:
5620 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
5621 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005622 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005623 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005624 case OMPC_num_threads:
5625 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005626 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005627 case OMPC_collapse:
5628 case OMPC_schedule:
5629 case OMPC_private:
5630 case OMPC_firstprivate:
5631 case OMPC_lastprivate:
5632 case OMPC_shared:
5633 case OMPC_reduction:
5634 case OMPC_linear:
5635 case OMPC_aligned:
5636 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00005637 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005638 case OMPC_default:
5639 case OMPC_proc_bind:
5640 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00005641 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005642 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00005643 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005644 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005645 case OMPC_num_teams:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005646 case OMPC_unknown:
5647 llvm_unreachable("Clause is not allowed.");
5648 }
5649 return Res;
5650}
5651
Alexey Bataev236070f2014-06-20 11:19:47 +00005652OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
5653 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005654 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00005655 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
5656}
5657
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005658OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
5659 SourceLocation EndLoc) {
5660 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
5661}
5662
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005663OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
5664 SourceLocation EndLoc) {
5665 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
5666}
5667
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005668OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
5669 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005670 return new (Context) OMPReadClause(StartLoc, EndLoc);
5671}
5672
Alexey Bataevdea47612014-07-23 07:46:59 +00005673OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
5674 SourceLocation EndLoc) {
5675 return new (Context) OMPWriteClause(StartLoc, EndLoc);
5676}
5677
Alexey Bataev67a4f222014-07-23 10:25:33 +00005678OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
5679 SourceLocation EndLoc) {
5680 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
5681}
5682
Alexey Bataev459dec02014-07-24 06:46:57 +00005683OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
5684 SourceLocation EndLoc) {
5685 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
5686}
5687
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005688OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
5689 SourceLocation EndLoc) {
5690 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
5691}
5692
Alexey Bataev346265e2015-09-25 10:37:12 +00005693OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
5694 SourceLocation EndLoc) {
5695 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
5696}
5697
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005698OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
5699 SourceLocation EndLoc) {
5700 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
5701}
5702
Alexey Bataevc5e02582014-06-16 07:08:35 +00005703OMPClause *Sema::ActOnOpenMPVarListClause(
5704 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
5705 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
5706 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005707 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Kelvin Li0bff7af2015-11-23 05:32:03 +00005708 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
5709 OpenMPMapClauseKind MapType, SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00005710 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005711 switch (Kind) {
5712 case OMPC_private:
5713 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5714 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005715 case OMPC_firstprivate:
5716 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5717 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00005718 case OMPC_lastprivate:
5719 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5720 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00005721 case OMPC_shared:
5722 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
5723 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00005724 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00005725 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
5726 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00005727 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00005728 case OMPC_linear:
5729 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00005730 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00005731 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00005732 case OMPC_aligned:
5733 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
5734 ColonLoc, EndLoc);
5735 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00005736 case OMPC_copyin:
5737 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
5738 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00005739 case OMPC_copyprivate:
5740 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
5741 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00005742 case OMPC_flush:
5743 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
5744 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005745 case OMPC_depend:
Kelvin Li0bff7af2015-11-23 05:32:03 +00005746 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
5747 StartLoc, LParenLoc, EndLoc);
5748 break;
5749 case OMPC_map:
5750 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, DepLinMapLoc, ColonLoc,
5751 VarList, StartLoc, LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00005752 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00005753 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00005754 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00005755 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00005756 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00005757 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00005758 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005759 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00005760 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00005761 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00005762 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00005763 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00005764 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00005765 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005766 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005767 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00005768 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00005769 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00005770 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00005771 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00005772 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00005773 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005774 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00005775 case OMPC_num_teams:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005776 case OMPC_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005777 llvm_unreachable("Clause is not allowed.");
5778 }
5779 return Res;
5780}
5781
5782OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
5783 SourceLocation StartLoc,
5784 SourceLocation LParenLoc,
5785 SourceLocation EndLoc) {
5786 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00005787 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00005788 for (auto &RefExpr : VarList) {
5789 assert(RefExpr && "NULL expr in OpenMP private clause.");
5790 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005791 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005792 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005793 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005794 continue;
5795 }
5796
Alexey Bataeved09d242014-05-28 05:53:51 +00005797 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005798 // OpenMP [2.1, C/C++]
5799 // A list item is a variable name.
5800 // OpenMP [2.9.3.3, Restrictions, p.1]
5801 // A variable that is part of another variable (as an array or
5802 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005803 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005804 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005805 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005806 continue;
5807 }
5808 Decl *D = DE->getDecl();
5809 VarDecl *VD = cast<VarDecl>(D);
5810
5811 QualType Type = VD->getType();
5812 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5813 // It will be analyzed later.
5814 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005815 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005816 continue;
5817 }
5818
5819 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5820 // A variable that appears in a private clause must not have an incomplete
5821 // type or a reference type.
5822 if (RequireCompleteType(ELoc, Type,
5823 diag::err_omp_private_incomplete_type)) {
5824 continue;
5825 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005826 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005827
Alexey Bataev758e55e2013-09-06 18:03:48 +00005828 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5829 // in a Construct]
5830 // Variables with the predetermined data-sharing attributes may not be
5831 // listed in data-sharing attributes clauses, except for the cases
5832 // listed below. For these exceptions only, listing a predetermined
5833 // variable in a data-sharing attribute clause is allowed and overrides
5834 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005835 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005836 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005837 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5838 << getOpenMPClauseName(OMPC_private);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005839 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00005840 continue;
5841 }
5842
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005843 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00005844 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00005845 DSAStack->getCurrentDirective() == OMPD_task) {
5846 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5847 << getOpenMPClauseName(OMPC_private) << Type
5848 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5849 bool IsDecl =
5850 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5851 Diag(VD->getLocation(),
5852 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5853 << VD;
5854 continue;
5855 }
5856
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005857 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
5858 // A variable of class type (or array thereof) that appears in a private
5859 // clause requires an accessible, unambiguous default constructor for the
5860 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00005861 // Generate helper private variable and initialize it with the default
5862 // value. The address of the original variable is replaced by the address of
5863 // the new private variable in CodeGen. This new variable is not added to
5864 // IdResolver, so the code in the OpenMP region uses original variable for
5865 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005866 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00005867 auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(),
5868 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005869 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005870 if (VDPrivate->isInvalidDecl())
5871 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005872 auto VDPrivateRefExpr = buildDeclRefExpr(
5873 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev03b340a2014-10-21 03:16:40 +00005874
Alexey Bataev758e55e2013-09-06 18:03:48 +00005875 DSAStack->addDSA(VD, DE, OMPC_private);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005876 Vars.push_back(DE);
Alexey Bataev03b340a2014-10-21 03:16:40 +00005877 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005878 }
5879
Alexey Bataeved09d242014-05-28 05:53:51 +00005880 if (Vars.empty())
5881 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005882
Alexey Bataev03b340a2014-10-21 03:16:40 +00005883 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
5884 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005885}
5886
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005887namespace {
5888class DiagsUninitializedSeveretyRAII {
5889private:
5890 DiagnosticsEngine &Diags;
5891 SourceLocation SavedLoc;
5892 bool IsIgnored;
5893
5894public:
5895 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
5896 bool IsIgnored)
5897 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
5898 if (!IsIgnored) {
5899 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
5900 /*Map*/ diag::Severity::Ignored, Loc);
5901 }
5902 }
5903 ~DiagsUninitializedSeveretyRAII() {
5904 if (!IsIgnored)
5905 Diags.popMappings(SavedLoc);
5906 }
5907};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005908}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005909
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005910OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
5911 SourceLocation StartLoc,
5912 SourceLocation LParenLoc,
5913 SourceLocation EndLoc) {
5914 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005915 SmallVector<Expr *, 8> PrivateCopies;
5916 SmallVector<Expr *, 8> Inits;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005917 bool IsImplicitClause =
5918 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
5919 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
5920
Alexey Bataeved09d242014-05-28 05:53:51 +00005921 for (auto &RefExpr : VarList) {
5922 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
5923 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005924 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00005925 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005926 PrivateCopies.push_back(nullptr);
5927 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005928 continue;
5929 }
5930
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005931 SourceLocation ELoc =
5932 IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005933 // OpenMP [2.1, C/C++]
5934 // A list item is a variable name.
5935 // OpenMP [2.9.3.3, Restrictions, p.1]
5936 // A variable that is part of another variable (as an array or
5937 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00005938 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005939 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00005940 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005941 continue;
5942 }
5943 Decl *D = DE->getDecl();
5944 VarDecl *VD = cast<VarDecl>(D);
5945
5946 QualType Type = VD->getType();
5947 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5948 // It will be analyzed later.
5949 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00005950 PrivateCopies.push_back(nullptr);
5951 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005952 continue;
5953 }
5954
5955 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5956 // A variable that appears in a private clause must not have an incomplete
5957 // type or a reference type.
5958 if (RequireCompleteType(ELoc, Type,
5959 diag::err_omp_firstprivate_incomplete_type)) {
5960 continue;
5961 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00005962 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005963
5964 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5965 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00005966 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005967 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005968 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005969
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005970 // If an implicit firstprivate variable found it was checked already.
5971 if (!IsImplicitClause) {
5972 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00005973 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005974 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5975 // A list item that specifies a given variable may not appear in more
5976 // than one clause on the same directive, except that a variable may be
5977 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005978 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00005979 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005980 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00005981 << getOpenMPClauseName(DVar.CKind)
5982 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00005983 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00005984 continue;
5985 }
5986
5987 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5988 // in a Construct]
5989 // Variables with the predetermined data-sharing attributes may not be
5990 // listed in data-sharing attributes clauses, except for the cases
5991 // listed below. For these exceptions only, listing a predetermined
5992 // variable in a data-sharing attribute clause is allowed and overrides
5993 // the variable's predetermined data-sharing attributes.
5994 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5995 // in a Construct, C/C++, p.2]
5996 // Variables with const-qualified type having no mutable member may be
5997 // listed in a firstprivate clause, even if they are static data members.
5998 if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5999 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
6000 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00006001 << getOpenMPClauseName(DVar.CKind)
6002 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006003 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006004 continue;
6005 }
6006
Alexey Bataevf29276e2014-06-18 04:14:57 +00006007 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006008 // OpenMP [2.9.3.4, Restrictions, p.2]
6009 // A list item that is private within a parallel region must not appear
6010 // in a firstprivate clause on a worksharing construct if any of the
6011 // worksharing regions arising from the worksharing construct ever bind
6012 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00006013 if (isOpenMPWorksharingDirective(CurrDir) &&
6014 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006015 DVar = DSAStack->getImplicitDSA(VD, true);
6016 if (DVar.CKind != OMPC_shared &&
6017 (isOpenMPParallelDirective(DVar.DKind) ||
6018 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00006019 Diag(ELoc, diag::err_omp_required_access)
6020 << getOpenMPClauseName(OMPC_firstprivate)
6021 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006022 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006023 continue;
6024 }
6025 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006026 // OpenMP [2.9.3.4, Restrictions, p.3]
6027 // A list item that appears in a reduction clause of a parallel construct
6028 // must not appear in a firstprivate clause on a worksharing or task
6029 // construct if any of the worksharing or task regions arising from the
6030 // worksharing or task construct ever bind to any of the parallel regions
6031 // arising from the parallel construct.
6032 // OpenMP [2.9.3.4, Restrictions, p.4]
6033 // A list item that appears in a reduction clause in worksharing
6034 // construct must not appear in a firstprivate clause in a task construct
6035 // encountered during execution of any of the worksharing regions arising
6036 // from the worksharing construct.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006037 if (CurrDir == OMPD_task) {
6038 DVar =
6039 DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6040 [](OpenMPDirectiveKind K) -> bool {
6041 return isOpenMPParallelDirective(K) ||
6042 isOpenMPWorksharingDirective(K);
6043 },
6044 false);
6045 if (DVar.CKind == OMPC_reduction &&
6046 (isOpenMPParallelDirective(DVar.DKind) ||
6047 isOpenMPWorksharingDirective(DVar.DKind))) {
6048 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
6049 << getOpenMPDirectiveName(DVar.DKind);
6050 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6051 continue;
6052 }
6053 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006054 }
6055
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006056 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00006057 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataevccb59ec2015-05-19 08:44:56 +00006058 DSAStack->getCurrentDirective() == OMPD_task) {
6059 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6060 << getOpenMPClauseName(OMPC_firstprivate) << Type
6061 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6062 bool IsDecl =
6063 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6064 Diag(VD->getLocation(),
6065 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6066 << VD;
6067 continue;
6068 }
6069
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006070 Type = Type.getUnqualifiedType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006071 auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
6072 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006073 // Generate helper private variable and initialize it with the value of the
6074 // original variable. The address of the original variable is replaced by
6075 // the address of the new private variable in the CodeGen. This new variable
6076 // is not added to IdResolver, so the code in the OpenMP region uses
6077 // original variable for proper diagnostics and variable capturing.
6078 Expr *VDInitRefExpr = nullptr;
6079 // For arrays generate initializer for single element and replace it by the
6080 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006081 if (Type->isArrayType()) {
6082 auto VDInit =
6083 buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
6084 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006085 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006086 ElemType = ElemType.getUnqualifiedType();
6087 auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
6088 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00006089 InitializedEntity Entity =
6090 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006091 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
6092
6093 InitializationSequence InitSeq(*this, Entity, Kind, Init);
6094 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
6095 if (Result.isInvalid())
6096 VDPrivate->setInvalidDecl();
6097 else
6098 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006099 // Remove temp variable declaration.
6100 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006101 } else {
Alexey Bataev69c62a92015-04-15 04:52:20 +00006102 auto *VDInit =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006103 buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006104 VDInitRefExpr =
6105 buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00006106 AddInitializerToDecl(VDPrivate,
6107 DefaultLvalueConversion(VDInitRefExpr).get(),
6108 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006109 }
6110 if (VDPrivate->isInvalidDecl()) {
6111 if (IsImplicitClause) {
6112 Diag(DE->getExprLoc(),
6113 diag::note_omp_task_predetermined_firstprivate_here);
6114 }
6115 continue;
6116 }
6117 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006118 auto VDPrivateRefExpr = buildDeclRefExpr(
6119 *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006120 DSAStack->addDSA(VD, DE, OMPC_firstprivate);
6121 Vars.push_back(DE);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006122 PrivateCopies.push_back(VDPrivateRefExpr);
6123 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006124 }
6125
Alexey Bataeved09d242014-05-28 05:53:51 +00006126 if (Vars.empty())
6127 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006128
6129 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev4a5bb772014-10-08 14:01:46 +00006130 Vars, PrivateCopies, Inits);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006131}
6132
Alexander Musman1bb328c2014-06-04 13:06:39 +00006133OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
6134 SourceLocation StartLoc,
6135 SourceLocation LParenLoc,
6136 SourceLocation EndLoc) {
6137 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00006138 SmallVector<Expr *, 8> SrcExprs;
6139 SmallVector<Expr *, 8> DstExprs;
6140 SmallVector<Expr *, 8> AssignmentOps;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006141 for (auto &RefExpr : VarList) {
6142 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
6143 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6144 // It will be analyzed later.
6145 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006146 SrcExprs.push_back(nullptr);
6147 DstExprs.push_back(nullptr);
6148 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006149 continue;
6150 }
6151
6152 SourceLocation ELoc = RefExpr->getExprLoc();
6153 // OpenMP [2.1, C/C++]
6154 // A list item is a variable name.
6155 // OpenMP [2.14.3.5, Restrictions, p.1]
6156 // A variable that is part of another variable (as an array or structure
6157 // element) cannot appear in a lastprivate clause.
6158 DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6159 if (!DE || !isa<VarDecl>(DE->getDecl())) {
6160 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6161 continue;
6162 }
6163 Decl *D = DE->getDecl();
6164 VarDecl *VD = cast<VarDecl>(D);
6165
6166 QualType Type = VD->getType();
6167 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6168 // It will be analyzed later.
6169 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006170 SrcExprs.push_back(nullptr);
6171 DstExprs.push_back(nullptr);
6172 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006173 continue;
6174 }
6175
6176 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
6177 // A variable that appears in a lastprivate clause must not have an
6178 // incomplete type or a reference type.
6179 if (RequireCompleteType(ELoc, Type,
6180 diag::err_omp_lastprivate_incomplete_type)) {
6181 continue;
6182 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006183 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00006184
6185 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6186 // in a Construct]
6187 // Variables with the predetermined data-sharing attributes may not be
6188 // listed in data-sharing attributes clauses, except for the cases
6189 // listed below.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006190 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006191 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
6192 DVar.CKind != OMPC_firstprivate &&
6193 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
6194 Diag(ELoc, diag::err_omp_wrong_dsa)
6195 << getOpenMPClauseName(DVar.CKind)
6196 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006197 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006198 continue;
6199 }
6200
Alexey Bataevf29276e2014-06-18 04:14:57 +00006201 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6202 // OpenMP [2.14.3.5, Restrictions, p.2]
6203 // A list item that is private within a parallel region, or that appears in
6204 // the reduction clause of a parallel construct, must not appear in a
6205 // lastprivate clause on a worksharing construct if any of the corresponding
6206 // worksharing regions ever binds to any of the corresponding parallel
6207 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006208 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00006209 if (isOpenMPWorksharingDirective(CurrDir) &&
6210 !isOpenMPParallelDirective(CurrDir)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006211 DVar = DSAStack->getImplicitDSA(VD, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006212 if (DVar.CKind != OMPC_shared) {
6213 Diag(ELoc, diag::err_omp_required_access)
6214 << getOpenMPClauseName(OMPC_lastprivate)
6215 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006216 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006217 continue;
6218 }
6219 }
Alexander Musman1bb328c2014-06-04 13:06:39 +00006220 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00006221 // A variable of class type (or array thereof) that appears in a
6222 // lastprivate clause requires an accessible, unambiguous default
6223 // constructor for the class type, unless the list item is also specified
6224 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00006225 // A variable of class type (or array thereof) that appears in a
6226 // lastprivate clause requires an accessible, unambiguous copy assignment
6227 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00006228 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev39f915b82015-05-08 10:41:21 +00006229 auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006230 Type.getUnqualifiedType(), ".lastprivate.src",
6231 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006232 auto *PseudoSrcExpr = buildDeclRefExpr(
6233 *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006234 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006235 buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
6236 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00006237 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00006238 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataev38e89532015-04-16 04:54:05 +00006239 // For arrays generate assignment operation for single element and replace
6240 // it by the original array element in CodeGen.
6241 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6242 PseudoDstExpr, PseudoSrcExpr);
6243 if (AssignmentOp.isInvalid())
6244 continue;
6245 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6246 /*DiscardedValue=*/true);
6247 if (AssignmentOp.isInvalid())
6248 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00006249
Alexey Bataev39f915b82015-05-08 10:41:21 +00006250 if (TopDVar.CKind != OMPC_firstprivate)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006251 DSAStack->addDSA(VD, DE, OMPC_lastprivate);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006252 Vars.push_back(DE);
Alexey Bataev38e89532015-04-16 04:54:05 +00006253 SrcExprs.push_back(PseudoSrcExpr);
6254 DstExprs.push_back(PseudoDstExpr);
6255 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00006256 }
6257
6258 if (Vars.empty())
6259 return nullptr;
6260
6261 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00006262 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexander Musman1bb328c2014-06-04 13:06:39 +00006263}
6264
Alexey Bataev758e55e2013-09-06 18:03:48 +00006265OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
6266 SourceLocation StartLoc,
6267 SourceLocation LParenLoc,
6268 SourceLocation EndLoc) {
6269 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00006270 for (auto &RefExpr : VarList) {
6271 assert(RefExpr && "NULL expr in OpenMP shared clause.");
6272 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00006273 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006274 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006275 continue;
6276 }
6277
Alexey Bataeved09d242014-05-28 05:53:51 +00006278 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006279 // OpenMP [2.1, C/C++]
6280 // A list item is a variable name.
Alexey Bataevd4dbdf52014-03-06 12:27:56 +00006281 // OpenMP [2.14.3.2, Restrictions, p.1]
6282 // A variable that is part of another variable (as an array or structure
6283 // element) cannot appear in a shared unless it is a static data member
6284 // of a C++ class.
Alexey Bataeved09d242014-05-28 05:53:51 +00006285 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006286 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006287 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataev758e55e2013-09-06 18:03:48 +00006288 continue;
6289 }
6290 Decl *D = DE->getDecl();
6291 VarDecl *VD = cast<VarDecl>(D);
6292
6293 QualType Type = VD->getType();
6294 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6295 // It will be analyzed later.
6296 Vars.push_back(DE);
6297 continue;
6298 }
6299
6300 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6301 // in a Construct]
6302 // Variables with the predetermined data-sharing attributes may not be
6303 // listed in data-sharing attributes clauses, except for the cases
6304 // listed below. For these exceptions only, listing a predetermined
6305 // variable in a data-sharing attribute clause is allowed and overrides
6306 // the variable's predetermined data-sharing attributes.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006307 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00006308 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
6309 DVar.RefExpr) {
6310 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6311 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006312 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006313 continue;
6314 }
6315
6316 DSAStack->addDSA(VD, DE, OMPC_shared);
6317 Vars.push_back(DE);
6318 }
6319
Alexey Bataeved09d242014-05-28 05:53:51 +00006320 if (Vars.empty())
6321 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00006322
6323 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
6324}
6325
Alexey Bataevc5e02582014-06-16 07:08:35 +00006326namespace {
6327class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
6328 DSAStackTy *Stack;
6329
6330public:
6331 bool VisitDeclRefExpr(DeclRefExpr *E) {
6332 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006333 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006334 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
6335 return false;
6336 if (DVar.CKind != OMPC_unknown)
6337 return true;
Alexey Bataevf29276e2014-06-18 04:14:57 +00006338 DSAStackTy::DSAVarData DVarPrivate =
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006339 Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00006340 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006341 return true;
6342 return false;
6343 }
6344 return false;
6345 }
6346 bool VisitStmt(Stmt *S) {
6347 for (auto Child : S->children()) {
6348 if (Child && Visit(Child))
6349 return true;
6350 }
6351 return false;
6352 }
Alexey Bataev23b69422014-06-18 07:08:49 +00006353 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00006354};
Alexey Bataev23b69422014-06-18 07:08:49 +00006355} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00006356
6357OMPClause *Sema::ActOnOpenMPReductionClause(
6358 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
6359 SourceLocation ColonLoc, SourceLocation EndLoc,
6360 CXXScopeSpec &ReductionIdScopeSpec,
6361 const DeclarationNameInfo &ReductionId) {
6362 // TODO: Allow scope specification search when 'declare reduction' is
6363 // supported.
6364 assert(ReductionIdScopeSpec.isEmpty() &&
6365 "No support for scoped reduction identifiers yet.");
6366
6367 auto DN = ReductionId.getName();
6368 auto OOK = DN.getCXXOverloadedOperator();
6369 BinaryOperatorKind BOK = BO_Comma;
6370
6371 // OpenMP [2.14.3.6, reduction clause]
6372 // C
6373 // reduction-identifier is either an identifier or one of the following
6374 // operators: +, -, *, &, |, ^, && and ||
6375 // C++
6376 // reduction-identifier is either an id-expression or one of the following
6377 // operators: +, -, *, &, |, ^, && and ||
6378 // FIXME: Only 'min' and 'max' identifiers are supported for now.
6379 switch (OOK) {
6380 case OO_Plus:
6381 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006382 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006383 break;
6384 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006385 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006386 break;
6387 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006388 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006389 break;
6390 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006391 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006392 break;
6393 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006394 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006395 break;
6396 case OO_AmpAmp:
6397 BOK = BO_LAnd;
6398 break;
6399 case OO_PipePipe:
6400 BOK = BO_LOr;
6401 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006402 case OO_New:
6403 case OO_Delete:
6404 case OO_Array_New:
6405 case OO_Array_Delete:
6406 case OO_Slash:
6407 case OO_Percent:
6408 case OO_Tilde:
6409 case OO_Exclaim:
6410 case OO_Equal:
6411 case OO_Less:
6412 case OO_Greater:
6413 case OO_LessEqual:
6414 case OO_GreaterEqual:
6415 case OO_PlusEqual:
6416 case OO_MinusEqual:
6417 case OO_StarEqual:
6418 case OO_SlashEqual:
6419 case OO_PercentEqual:
6420 case OO_CaretEqual:
6421 case OO_AmpEqual:
6422 case OO_PipeEqual:
6423 case OO_LessLess:
6424 case OO_GreaterGreater:
6425 case OO_LessLessEqual:
6426 case OO_GreaterGreaterEqual:
6427 case OO_EqualEqual:
6428 case OO_ExclaimEqual:
6429 case OO_PlusPlus:
6430 case OO_MinusMinus:
6431 case OO_Comma:
6432 case OO_ArrowStar:
6433 case OO_Arrow:
6434 case OO_Call:
6435 case OO_Subscript:
6436 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00006437 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006438 case NUM_OVERLOADED_OPERATORS:
6439 llvm_unreachable("Unexpected reduction identifier");
6440 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006441 if (auto II = DN.getAsIdentifierInfo()) {
6442 if (II->isStr("max"))
6443 BOK = BO_GT;
6444 else if (II->isStr("min"))
6445 BOK = BO_LT;
6446 }
6447 break;
6448 }
6449 SourceRange ReductionIdRange;
6450 if (ReductionIdScopeSpec.isValid()) {
6451 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
6452 }
6453 ReductionIdRange.setEnd(ReductionId.getEndLoc());
6454 if (BOK == BO_Comma) {
6455 // Not allowed reduction identifier is found.
6456 Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
6457 << ReductionIdRange;
6458 return nullptr;
6459 }
6460
6461 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006462 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006463 SmallVector<Expr *, 8> LHSs;
6464 SmallVector<Expr *, 8> RHSs;
6465 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006466 for (auto RefExpr : VarList) {
6467 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
6468 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6469 // It will be analyzed later.
6470 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006471 Privates.push_back(nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006472 LHSs.push_back(nullptr);
6473 RHSs.push_back(nullptr);
6474 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006475 continue;
6476 }
6477
6478 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
6479 RefExpr->isInstantiationDependent() ||
6480 RefExpr->containsUnexpandedParameterPack()) {
6481 // It will be analyzed later.
6482 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006483 Privates.push_back(nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006484 LHSs.push_back(nullptr);
6485 RHSs.push_back(nullptr);
6486 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006487 continue;
6488 }
6489
6490 auto ELoc = RefExpr->getExprLoc();
6491 auto ERange = RefExpr->getSourceRange();
6492 // OpenMP [2.1, C/C++]
6493 // A list item is a variable or array section, subject to the restrictions
6494 // specified in Section 2.4 on page 42 and in each of the sections
6495 // describing clauses and directives for which a list appears.
6496 // OpenMP [2.14.3.3, Restrictions, p.1]
6497 // A variable that is part of another variable (as an array or
6498 // structure element) cannot appear in a private clause.
Alexey Bataeva1764212015-09-30 09:22:36 +00006499 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
6500 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
6501 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
6502 if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
6503 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) << ERange;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006504 continue;
6505 }
Alexey Bataeva1764212015-09-30 09:22:36 +00006506 QualType Type;
6507 VarDecl *VD = nullptr;
6508 if (DE) {
6509 auto D = DE->getDecl();
6510 VD = cast<VarDecl>(D);
6511 Type = VD->getType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006512 } else if (ASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006513 Type = ASE->getType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006514 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
6515 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
6516 Base = TempASE->getBase()->IgnoreParenImpCasts();
6517 DE = dyn_cast<DeclRefExpr>(Base);
6518 if (DE)
6519 VD = dyn_cast<VarDecl>(DE->getDecl());
6520 if (!VD) {
6521 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
6522 << 0 << Base->getSourceRange();
6523 continue;
6524 }
6525 } else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006526 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
6527 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
6528 Type = ATy->getElementType();
6529 else
6530 Type = BaseType->getPointeeType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006531 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
6532 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
6533 Base = TempOASE->getBase()->IgnoreParenImpCasts();
6534 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
6535 Base = TempASE->getBase()->IgnoreParenImpCasts();
6536 DE = dyn_cast<DeclRefExpr>(Base);
6537 if (DE)
6538 VD = dyn_cast<VarDecl>(DE->getDecl());
6539 if (!VD) {
6540 Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
6541 << 1 << Base->getSourceRange();
6542 continue;
6543 }
Alexey Bataeva1764212015-09-30 09:22:36 +00006544 }
6545
Alexey Bataevc5e02582014-06-16 07:08:35 +00006546 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6547 // A variable that appears in a private clause must not have an incomplete
6548 // type or a reference type.
6549 if (RequireCompleteType(ELoc, Type,
6550 diag::err_omp_reduction_incomplete_type))
6551 continue;
6552 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6553 // Arrays may not appear in a reduction clause.
6554 if (Type.getNonReferenceType()->isArrayType()) {
6555 Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006556 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006557 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6558 VarDecl::DeclarationOnly;
6559 Diag(VD->getLocation(),
6560 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6561 << VD;
6562 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006563 continue;
6564 }
6565 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6566 // A list item that appears in a reduction clause must not be
6567 // const-qualified.
6568 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006569 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00006570 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006571 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006572 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6573 VarDecl::DeclarationOnly;
6574 Diag(VD->getLocation(),
6575 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6576 << VD;
6577 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006578 continue;
6579 }
6580 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
6581 // If a list-item is a reference type then it must bind to the same object
6582 // for all threads of the team.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006583 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006584 VarDecl *VDDef = VD->getDefinition();
6585 if (Type->isReferenceType() && VDDef) {
6586 DSARefChecker Check(DSAStack);
6587 if (Check.Visit(VDDef->getInit())) {
6588 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
6589 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
6590 continue;
6591 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006592 }
6593 }
6594 // OpenMP [2.14.3.6, reduction clause, Restrictions]
6595 // The type of a list item that appears in a reduction clause must be valid
6596 // for the reduction-identifier. For a max or min reduction in C, the type
6597 // of the list item must be an allowed arithmetic data type: char, int,
6598 // float, double, or _Bool, possibly modified with long, short, signed, or
6599 // unsigned. For a max or min reduction in C++, the type of the list item
6600 // must be an allowed arithmetic data type: char, wchar_t, int, float,
6601 // double, or bool, possibly modified with long, short, signed, or unsigned.
6602 if ((BOK == BO_GT || BOK == BO_LT) &&
6603 !(Type->isScalarType() ||
6604 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
6605 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
6606 << getLangOpts().CPlusPlus;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006607 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006608 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6609 VarDecl::DeclarationOnly;
6610 Diag(VD->getLocation(),
6611 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6612 << VD;
6613 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006614 continue;
6615 }
6616 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
6617 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
6618 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006619 if (!ASE && !OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00006620 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6621 VarDecl::DeclarationOnly;
6622 Diag(VD->getLocation(),
6623 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6624 << VD;
6625 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006626 continue;
6627 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00006628 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6629 // in a Construct]
6630 // Variables with the predetermined data-sharing attributes may not be
6631 // listed in data-sharing attributes clauses, except for the cases
6632 // listed below. For these exceptions only, listing a predetermined
6633 // variable in a data-sharing attribute clause is allowed and overrides
6634 // the variable's predetermined data-sharing attributes.
6635 // OpenMP [2.14.3.6, Restrictions, p.3]
6636 // Any number of reduction clauses can be specified on the directive,
6637 // but a list item can appear only once in the reduction clauses for that
6638 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00006639 DSAStackTy::DSAVarData DVar;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006640 DVar = DSAStack->getTopDSA(VD, false);
6641 if (DVar.CKind == OMPC_reduction) {
6642 Diag(ELoc, diag::err_omp_once_referenced)
6643 << getOpenMPClauseName(OMPC_reduction);
6644 if (DVar.RefExpr) {
6645 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006646 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006647 } else if (DVar.CKind != OMPC_unknown) {
6648 Diag(ELoc, diag::err_omp_wrong_dsa)
6649 << getOpenMPClauseName(DVar.CKind)
6650 << getOpenMPClauseName(OMPC_reduction);
6651 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6652 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006653 }
6654
6655 // OpenMP [2.14.3.6, Restrictions, p.1]
6656 // A list item that appears in a reduction clause of a worksharing
6657 // construct must be shared in the parallel regions to which any of the
6658 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006659 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6660 if (isOpenMPWorksharingDirective(CurrDir) &&
6661 !isOpenMPParallelDirective(CurrDir)) {
6662 DVar = DSAStack->getImplicitDSA(VD, true);
6663 if (DVar.CKind != OMPC_shared) {
6664 Diag(ELoc, diag::err_omp_required_access)
6665 << getOpenMPClauseName(OMPC_reduction)
6666 << getOpenMPClauseName(OMPC_shared);
6667 ReportOriginalDSA(*this, DSAStack, VD, DVar);
6668 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00006669 }
6670 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006671
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006672 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006673 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
6674 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6675 auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
6676 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6677 auto PrivateTy = Type;
6678 if (OASE) {
6679 // For array sections only:
6680 // Create pseudo array type for private copy. The size for this array will
6681 // be generated during codegen.
6682 // For array subscripts or single variables Private Ty is the same as Type
6683 // (type of the variable or single array element).
6684 PrivateTy = Context.getVariableArrayType(
6685 Type, new (Context) OpaqueValueExpr(SourceLocation(),
6686 Context.getSizeType(), VK_RValue),
6687 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
6688 }
6689 // Private copy.
6690 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
6691 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006692 // Add initializer for private variable.
6693 Expr *Init = nullptr;
6694 switch (BOK) {
6695 case BO_Add:
6696 case BO_Xor:
6697 case BO_Or:
6698 case BO_LOr:
6699 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
6700 if (Type->isScalarType() || Type->isAnyComplexType()) {
6701 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006702 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006703 break;
6704 case BO_Mul:
6705 case BO_LAnd:
6706 if (Type->isScalarType() || Type->isAnyComplexType()) {
6707 // '*' and '&&' reduction ops - initializer is '1'.
6708 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
6709 }
6710 break;
6711 case BO_And: {
6712 // '&' reduction op - initializer is '~0'.
6713 QualType OrigType = Type;
6714 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
6715 Type = ComplexTy->getElementType();
6716 }
6717 if (Type->isRealFloatingType()) {
6718 llvm::APFloat InitValue =
6719 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
6720 /*isIEEE=*/true);
6721 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6722 Type, ELoc);
6723 } else if (Type->isScalarType()) {
6724 auto Size = Context.getTypeSize(Type);
6725 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
6726 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
6727 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6728 }
6729 if (Init && OrigType->isAnyComplexType()) {
6730 // Init = 0xFFFF + 0xFFFFi;
6731 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
6732 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
6733 }
6734 Type = OrigType;
6735 break;
6736 }
6737 case BO_LT:
6738 case BO_GT: {
6739 // 'min' reduction op - initializer is 'Largest representable number in
6740 // the reduction list item type'.
6741 // 'max' reduction op - initializer is 'Least representable number in
6742 // the reduction list item type'.
6743 if (Type->isIntegerType() || Type->isPointerType()) {
6744 bool IsSigned = Type->hasSignedIntegerRepresentation();
6745 auto Size = Context.getTypeSize(Type);
6746 QualType IntTy =
6747 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
6748 llvm::APInt InitValue =
6749 (BOK != BO_LT)
6750 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
6751 : llvm::APInt::getMinValue(Size)
6752 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
6753 : llvm::APInt::getMaxValue(Size);
6754 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
6755 if (Type->isPointerType()) {
6756 // Cast to pointer type.
6757 auto CastExpr = BuildCStyleCastExpr(
6758 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
6759 SourceLocation(), Init);
6760 if (CastExpr.isInvalid())
6761 continue;
6762 Init = CastExpr.get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00006763 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006764 } else if (Type->isRealFloatingType()) {
6765 llvm::APFloat InitValue = llvm::APFloat::getLargest(
6766 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
6767 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
6768 Type, ELoc);
6769 }
6770 break;
6771 }
6772 case BO_PtrMemD:
6773 case BO_PtrMemI:
6774 case BO_MulAssign:
6775 case BO_Div:
6776 case BO_Rem:
6777 case BO_Sub:
6778 case BO_Shl:
6779 case BO_Shr:
6780 case BO_LE:
6781 case BO_GE:
6782 case BO_EQ:
6783 case BO_NE:
6784 case BO_AndAssign:
6785 case BO_XorAssign:
6786 case BO_OrAssign:
6787 case BO_Assign:
6788 case BO_AddAssign:
6789 case BO_SubAssign:
6790 case BO_DivAssign:
6791 case BO_RemAssign:
6792 case BO_ShlAssign:
6793 case BO_ShrAssign:
6794 case BO_Comma:
6795 llvm_unreachable("Unexpected reduction operation");
6796 }
6797 if (Init) {
6798 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
6799 /*TypeMayContainAuto=*/false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006800 } else
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006801 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006802 if (!RHSVD->hasInit()) {
6803 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
6804 << ReductionIdRange;
Alexey Bataeva1764212015-09-30 09:22:36 +00006805 if (VD) {
6806 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
6807 VarDecl::DeclarationOnly;
6808 Diag(VD->getLocation(),
6809 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6810 << VD;
6811 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006812 continue;
6813 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006814 // Store initializer for single element in private copy. Will be used during
6815 // codegen.
6816 PrivateVD->setInit(RHSVD->getInit());
6817 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataev39f915b82015-05-08 10:41:21 +00006818 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
6819 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006820 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006821 ExprResult ReductionOp =
6822 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
6823 LHSDRE, RHSDRE);
6824 if (ReductionOp.isUsable()) {
Alexey Bataev69a47792015-05-07 03:54:03 +00006825 if (BOK != BO_LT && BOK != BO_GT) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006826 ReductionOp =
6827 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6828 BO_Assign, LHSDRE, ReductionOp.get());
6829 } else {
6830 auto *ConditionalOp = new (Context) ConditionalOperator(
6831 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
6832 RHSDRE, Type, VK_LValue, OK_Ordinary);
6833 ReductionOp =
6834 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6835 BO_Assign, LHSDRE, ConditionalOp);
6836 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006837 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006838 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006839 if (ReductionOp.isInvalid())
6840 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00006841
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006842 DSAStack->addDSA(VD, DE, OMPC_reduction);
Alexey Bataeva1764212015-09-30 09:22:36 +00006843 Vars.push_back(RefExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006844 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00006845 LHSs.push_back(LHSDRE);
6846 RHSs.push_back(RHSDRE);
6847 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00006848 }
6849
6850 if (Vars.empty())
6851 return nullptr;
6852
6853 return OMPReductionClause::Create(
6854 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00006855 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
6856 LHSs, RHSs, ReductionOps);
Alexey Bataevc5e02582014-06-16 07:08:35 +00006857}
6858
Alexey Bataev182227b2015-08-20 10:54:39 +00006859OMPClause *Sema::ActOnOpenMPLinearClause(
6860 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
6861 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
6862 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006863 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006864 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00006865 SmallVector<Expr *, 8> Inits;
Alexey Bataev182227b2015-08-20 10:54:39 +00006866 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
6867 LinKind == OMPC_LINEAR_unknown) {
6868 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
6869 LinKind = OMPC_LINEAR_val;
6870 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006871 for (auto &RefExpr : VarList) {
6872 assert(RefExpr && "NULL expr in OpenMP linear clause.");
6873 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexander Musman8dba6642014-04-22 13:09:42 +00006874 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00006875 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006876 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006877 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006878 continue;
6879 }
6880
6881 // OpenMP [2.14.3.7, linear clause]
6882 // A list item that appears in a linear clause is subject to the private
6883 // clause semantics described in Section 2.14.3.3 on page 159 except as
6884 // noted. In addition, the value of the new list item on each iteration
6885 // of the associated loop(s) corresponds to the value of the original
6886 // list item before entering the construct plus the logical number of
6887 // the iteration times linear-step.
6888
Alexey Bataeved09d242014-05-28 05:53:51 +00006889 SourceLocation ELoc = RefExpr->getExprLoc();
Alexander Musman8dba6642014-04-22 13:09:42 +00006890 // OpenMP [2.1, C/C++]
6891 // A list item is a variable name.
6892 // OpenMP [2.14.3.3, Restrictions, p.1]
6893 // A variable that is part of another variable (as an array or
6894 // structure element) cannot appear in a private clause.
Alexey Bataeved09d242014-05-28 05:53:51 +00006895 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006896 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00006897 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexander Musman8dba6642014-04-22 13:09:42 +00006898 continue;
6899 }
6900
6901 VarDecl *VD = cast<VarDecl>(DE->getDecl());
6902
6903 // OpenMP [2.14.3.7, linear clause]
6904 // A list-item cannot appear in more than one linear clause.
6905 // A list-item that appears in a linear clause cannot appear in any
6906 // other data-sharing attribute clause.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006907 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00006908 if (DVar.RefExpr) {
6909 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6910 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev7ff55242014-06-19 09:13:45 +00006911 ReportOriginalDSA(*this, DSAStack, VD, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00006912 continue;
6913 }
6914
6915 QualType QType = VD->getType();
6916 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
6917 // It will be analyzed later.
6918 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006919 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00006920 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00006921 continue;
6922 }
6923
6924 // A variable must not have an incomplete type or a reference type.
6925 if (RequireCompleteType(ELoc, QType,
6926 diag::err_omp_linear_incomplete_type)) {
6927 continue;
6928 }
Alexey Bataev1185e192015-08-20 12:15:57 +00006929 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
6930 !QType->isReferenceType()) {
6931 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
6932 << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
6933 continue;
6934 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006935 QType = QType.getNonReferenceType();
Alexander Musman8dba6642014-04-22 13:09:42 +00006936
6937 // A list item must not be const-qualified.
6938 if (QType.isConstant(Context)) {
6939 Diag(ELoc, diag::err_omp_const_variable)
6940 << getOpenMPClauseName(OMPC_linear);
6941 bool IsDecl =
6942 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6943 Diag(VD->getLocation(),
6944 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6945 << VD;
6946 continue;
6947 }
6948
6949 // A list item must be of integral or pointer type.
6950 QType = QType.getUnqualifiedType().getCanonicalType();
6951 const Type *Ty = QType.getTypePtrOrNull();
6952 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
6953 !Ty->isPointerType())) {
6954 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
6955 bool IsDecl =
6956 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6957 Diag(VD->getLocation(),
6958 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6959 << VD;
6960 continue;
6961 }
6962
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006963 // Build private copy of original var.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00006964 auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
6965 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006966 auto *PrivateRef = buildDeclRefExpr(
6967 *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman3276a272015-03-21 10:12:56 +00006968 // Build var to save initial value.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006969 VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00006970 Expr *InitExpr;
6971 if (LinKind == OMPC_LINEAR_uval)
6972 InitExpr = VD->getInit();
6973 else
6974 InitExpr = DE;
6975 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexander Musman3276a272015-03-21 10:12:56 +00006976 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
Alexey Bataevf120c0d2015-05-19 07:46:42 +00006977 auto InitRef = buildDeclRefExpr(
6978 *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
Alexander Musman8dba6642014-04-22 13:09:42 +00006979 DSAStack->addDSA(VD, DE, OMPC_linear);
6980 Vars.push_back(DE);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00006981 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00006982 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00006983 }
6984
6985 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006986 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00006987
6988 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00006989 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00006990 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6991 !Step->isInstantiationDependent() &&
6992 !Step->containsUnexpandedParameterPack()) {
6993 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006994 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00006995 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006996 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006997 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00006998
Alexander Musman3276a272015-03-21 10:12:56 +00006999 // Build var to save the step value.
7000 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007001 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00007002 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007003 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00007004 ExprResult CalcStep =
7005 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007006 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00007007
Alexander Musman8dba6642014-04-22 13:09:42 +00007008 // Warn about zero linear step (it would be probably better specified as
7009 // making corresponding variables 'const').
7010 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00007011 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
7012 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00007013 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
7014 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00007015 if (!IsConstant && CalcStep.isUsable()) {
7016 // Calculate the step beforehand instead of doing this on each iteration.
7017 // (This is not used if the number of iterations may be kfold-ed).
7018 CalcStepExpr = CalcStep.get();
7019 }
Alexander Musman8dba6642014-04-22 13:09:42 +00007020 }
7021
Alexey Bataev182227b2015-08-20 10:54:39 +00007022 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
7023 ColonLoc, EndLoc, Vars, Privates, Inits,
7024 StepExpr, CalcStepExpr);
Alexander Musman3276a272015-03-21 10:12:56 +00007025}
7026
7027static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
7028 Expr *NumIterations, Sema &SemaRef,
7029 Scope *S) {
7030 // Walk the vars and build update/final expressions for the CodeGen.
7031 SmallVector<Expr *, 8> Updates;
7032 SmallVector<Expr *, 8> Finals;
7033 Expr *Step = Clause.getStep();
7034 Expr *CalcStep = Clause.getCalcStep();
7035 // OpenMP [2.14.3.7, linear clause]
7036 // If linear-step is not specified it is assumed to be 1.
7037 if (Step == nullptr)
7038 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7039 else if (CalcStep)
7040 Step = cast<BinaryOperator>(CalcStep)->getLHS();
7041 bool HasErrors = false;
7042 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007043 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00007044 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00007045 for (auto &RefExpr : Clause.varlists()) {
7046 Expr *InitExpr = *CurInit;
7047
7048 // Build privatized reference to the current linear var.
7049 auto DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00007050 Expr *CapturedRef;
7051 if (LinKind == OMPC_LINEAR_uval)
7052 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
7053 else
7054 CapturedRef =
7055 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
7056 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
7057 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007058
7059 // Build update: Var = InitExpr + IV * Step
7060 ExprResult Update =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007061 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexander Musman3276a272015-03-21 10:12:56 +00007062 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007063 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
7064 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007065
7066 // Build final: Var = InitExpr + NumIterations * Step
7067 ExprResult Final =
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007068 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataev39f915b82015-05-08 10:41:21 +00007069 InitExpr, NumIterations, Step, /* Subtract */ false);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007070 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
7071 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00007072 if (!Update.isUsable() || !Final.isUsable()) {
7073 Updates.push_back(nullptr);
7074 Finals.push_back(nullptr);
7075 HasErrors = true;
7076 } else {
7077 Updates.push_back(Update.get());
7078 Finals.push_back(Final.get());
7079 }
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007080 ++CurInit, ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00007081 }
7082 Clause.setUpdates(Updates);
7083 Clause.setFinals(Finals);
7084 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00007085}
7086
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007087OMPClause *Sema::ActOnOpenMPAlignedClause(
7088 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
7089 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7090
7091 SmallVector<Expr *, 8> Vars;
7092 for (auto &RefExpr : VarList) {
7093 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
7094 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7095 // It will be analyzed later.
7096 Vars.push_back(RefExpr);
7097 continue;
7098 }
7099
7100 SourceLocation ELoc = RefExpr->getExprLoc();
7101 // OpenMP [2.1, C/C++]
7102 // A list item is a variable name.
7103 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7104 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7105 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7106 continue;
7107 }
7108
7109 VarDecl *VD = cast<VarDecl>(DE->getDecl());
7110
7111 // OpenMP [2.8.1, simd construct, Restrictions]
7112 // The type of list items appearing in the aligned clause must be
7113 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007114 QualType QType = VD->getType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007115 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007116 const Type *Ty = QType.getTypePtrOrNull();
7117 if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
7118 !Ty->isPointerType())) {
7119 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
7120 << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
7121 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 }
7128
7129 // OpenMP [2.8.1, simd construct, Restrictions]
7130 // A list-item cannot appear in more than one aligned clause.
7131 if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
7132 Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
7133 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
7134 << getOpenMPClauseName(OMPC_aligned);
7135 continue;
7136 }
7137
7138 Vars.push_back(DE);
7139 }
7140
7141 // OpenMP [2.8.1, simd construct, Description]
7142 // The parameter of the aligned clause, alignment, must be a constant
7143 // positive integer expression.
7144 // If no optional parameter is specified, implementation-defined default
7145 // alignments for SIMD instructions on the target platforms are assumed.
7146 if (Alignment != nullptr) {
7147 ExprResult AlignResult =
7148 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
7149 if (AlignResult.isInvalid())
7150 return nullptr;
7151 Alignment = AlignResult.get();
7152 }
7153 if (Vars.empty())
7154 return nullptr;
7155
7156 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
7157 EndLoc, Vars, Alignment);
7158}
7159
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007160OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7161 SourceLocation StartLoc,
7162 SourceLocation LParenLoc,
7163 SourceLocation EndLoc) {
7164 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007165 SmallVector<Expr *, 8> SrcExprs;
7166 SmallVector<Expr *, 8> DstExprs;
7167 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00007168 for (auto &RefExpr : VarList) {
7169 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
7170 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007171 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007172 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007173 SrcExprs.push_back(nullptr);
7174 DstExprs.push_back(nullptr);
7175 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007176 continue;
7177 }
7178
Alexey Bataeved09d242014-05-28 05:53:51 +00007179 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007180 // OpenMP [2.1, C/C++]
7181 // A list item is a variable name.
7182 // OpenMP [2.14.4.1, Restrictions, p.1]
7183 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00007184 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007185 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007186 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007187 continue;
7188 }
7189
7190 Decl *D = DE->getDecl();
7191 VarDecl *VD = cast<VarDecl>(D);
7192
7193 QualType Type = VD->getType();
7194 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7195 // It will be analyzed later.
7196 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007197 SrcExprs.push_back(nullptr);
7198 DstExprs.push_back(nullptr);
7199 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007200 continue;
7201 }
7202
7203 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
7204 // A list item that appears in a copyin clause must be threadprivate.
7205 if (!DSAStack->isThreadPrivate(VD)) {
7206 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00007207 << getOpenMPClauseName(OMPC_copyin)
7208 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007209 continue;
7210 }
7211
7212 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7213 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00007214 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007215 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007216 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007217 auto *SrcVD =
7218 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
7219 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007220 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007221 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
7222 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007223 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
7224 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007225 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007226 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007227 // For arrays generate assignment operation for single element and replace
7228 // it by the original array element in CodeGen.
7229 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7230 PseudoDstExpr, PseudoSrcExpr);
7231 if (AssignmentOp.isInvalid())
7232 continue;
7233 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7234 /*DiscardedValue=*/true);
7235 if (AssignmentOp.isInvalid())
7236 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007237
7238 DSAStack->addDSA(VD, DE, OMPC_copyin);
7239 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007240 SrcExprs.push_back(PseudoSrcExpr);
7241 DstExprs.push_back(PseudoDstExpr);
7242 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007243 }
7244
Alexey Bataeved09d242014-05-28 05:53:51 +00007245 if (Vars.empty())
7246 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007247
Alexey Bataevf56f98c2015-04-16 05:39:01 +00007248 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7249 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007250}
7251
Alexey Bataevbae9a792014-06-27 10:37:06 +00007252OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7253 SourceLocation StartLoc,
7254 SourceLocation LParenLoc,
7255 SourceLocation EndLoc) {
7256 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00007257 SmallVector<Expr *, 8> SrcExprs;
7258 SmallVector<Expr *, 8> DstExprs;
7259 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007260 for (auto &RefExpr : VarList) {
7261 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
7262 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7263 // It will be analyzed later.
7264 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007265 SrcExprs.push_back(nullptr);
7266 DstExprs.push_back(nullptr);
7267 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007268 continue;
7269 }
7270
7271 SourceLocation ELoc = RefExpr->getExprLoc();
7272 // OpenMP [2.1, C/C++]
7273 // A list item is a variable name.
7274 // OpenMP [2.14.4.1, Restrictions, p.1]
7275 // A list item that appears in a copyin clause must be threadprivate.
7276 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7277 if (!DE || !isa<VarDecl>(DE->getDecl())) {
7278 Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7279 continue;
7280 }
7281
7282 Decl *D = DE->getDecl();
7283 VarDecl *VD = cast<VarDecl>(D);
7284
7285 QualType Type = VD->getType();
7286 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7287 // It will be analyzed later.
7288 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007289 SrcExprs.push_back(nullptr);
7290 DstExprs.push_back(nullptr);
7291 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007292 continue;
7293 }
7294
7295 // OpenMP [2.14.4.2, Restrictions, p.2]
7296 // A list item that appears in a copyprivate clause may not appear in a
7297 // private or firstprivate clause on the single construct.
7298 if (!DSAStack->isThreadPrivate(VD)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007299 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007300 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
7301 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00007302 Diag(ELoc, diag::err_omp_wrong_dsa)
7303 << getOpenMPClauseName(DVar.CKind)
7304 << getOpenMPClauseName(OMPC_copyprivate);
7305 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7306 continue;
7307 }
7308
7309 // OpenMP [2.11.4.2, Restrictions, p.1]
7310 // All list items that appear in a copyprivate clause must be either
7311 // threadprivate or private in the enclosing context.
7312 if (DVar.CKind == OMPC_unknown) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007313 DVar = DSAStack->getImplicitDSA(VD, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007314 if (DVar.CKind == OMPC_shared) {
7315 Diag(ELoc, diag::err_omp_required_access)
7316 << getOpenMPClauseName(OMPC_copyprivate)
7317 << "threadprivate or private in the enclosing context";
7318 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7319 continue;
7320 }
7321 }
7322 }
7323
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007324 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007325 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007326 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007327 << getOpenMPClauseName(OMPC_copyprivate) << Type
7328 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00007329 bool IsDecl =
7330 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7331 Diag(VD->getLocation(),
7332 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7333 << VD;
7334 continue;
7335 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007336
Alexey Bataevbae9a792014-06-27 10:37:06 +00007337 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7338 // A variable of class type (or array thereof) that appears in a
7339 // copyin clause requires an accessible, unambiguous copy assignment
7340 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007341 Type = Context.getBaseElementType(Type.getNonReferenceType())
7342 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00007343 auto *SrcVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007344 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
7345 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007346 auto *PseudoSrcExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007347 buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
Alexey Bataev420d45b2015-04-14 05:11:24 +00007348 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007349 buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
7350 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev420d45b2015-04-14 05:11:24 +00007351 auto *PseudoDstExpr =
Alexey Bataev39f915b82015-05-08 10:41:21 +00007352 buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
Alexey Bataeva63048e2015-03-23 06:18:07 +00007353 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7354 PseudoDstExpr, PseudoSrcExpr);
7355 if (AssignmentOp.isInvalid())
7356 continue;
7357 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7358 /*DiscardedValue=*/true);
7359 if (AssignmentOp.isInvalid())
7360 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007361
7362 // No need to mark vars as copyprivate, they are already threadprivate or
7363 // implicitly private.
7364 Vars.push_back(DE);
Alexey Bataeva63048e2015-03-23 06:18:07 +00007365 SrcExprs.push_back(PseudoSrcExpr);
7366 DstExprs.push_back(PseudoDstExpr);
7367 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00007368 }
7369
7370 if (Vars.empty())
7371 return nullptr;
7372
Alexey Bataeva63048e2015-03-23 06:18:07 +00007373 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7374 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00007375}
7376
Alexey Bataev6125da92014-07-21 11:26:11 +00007377OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
7378 SourceLocation StartLoc,
7379 SourceLocation LParenLoc,
7380 SourceLocation EndLoc) {
7381 if (VarList.empty())
7382 return nullptr;
7383
7384 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
7385}
Alexey Bataevdea47612014-07-23 07:46:59 +00007386
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007387OMPClause *
7388Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
7389 SourceLocation DepLoc, SourceLocation ColonLoc,
7390 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
7391 SourceLocation LParenLoc, SourceLocation EndLoc) {
7392 if (DepKind == OMPC_DEPEND_unknown) {
7393 std::string Values;
7394 std::string Sep(", ");
7395 for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
7396 Values += "'";
7397 Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
7398 Values += "'";
7399 switch (i) {
7400 case OMPC_DEPEND_unknown - 2:
7401 Values += " or ";
7402 break;
7403 case OMPC_DEPEND_unknown - 1:
7404 break;
7405 default:
7406 Values += Sep;
7407 break;
7408 }
7409 }
7410 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
7411 << Values << getOpenMPClauseName(OMPC_depend);
7412 return nullptr;
7413 }
7414 SmallVector<Expr *, 8> Vars;
7415 for (auto &RefExpr : VarList) {
7416 assert(RefExpr && "NULL expr in OpenMP shared clause.");
7417 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7418 // It will be analyzed later.
7419 Vars.push_back(RefExpr);
7420 continue;
7421 }
7422
7423 SourceLocation ELoc = RefExpr->getExprLoc();
7424 // OpenMP [2.11.1.1, Restrictions, p.3]
7425 // A variable that is part of another variable (such as a field of a
7426 // structure) but is not an array element or an array section cannot appear
7427 // in a depend clause.
7428 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007429 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
7430 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
7431 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
7432 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
7433 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007434 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
7435 !ASE->getBase()->getType()->isArrayType())) {
7436 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
7437 << RefExpr->getSourceRange();
7438 continue;
7439 }
7440
7441 Vars.push_back(RefExpr->IgnoreParenImpCasts());
7442 }
7443
7444 if (Vars.empty())
7445 return nullptr;
7446
7447 return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
7448 DepLoc, ColonLoc, Vars);
7449}
Michael Wonge710d542015-08-07 16:16:36 +00007450
7451OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
7452 SourceLocation LParenLoc,
7453 SourceLocation EndLoc) {
7454 Expr *ValExpr = Device;
7455 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7456 !ValExpr->isInstantiationDependent()) {
7457 SourceLocation Loc = ValExpr->getExprLoc();
7458 ExprResult Value = PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7459 if (Value.isInvalid())
7460 return nullptr;
7461
7462 // OpenMP [2.9.1, Restrictions]
7463 // The device expression must evaluate to a non-negative integer value.
7464 llvm::APSInt Result;
7465 if (Value.get()->isIntegerConstantExpr(Result, Context) &&
7466 Result.isSigned() && !Result.isStrictlyPositive()) {
7467 Diag(Loc, diag::err_omp_negative_expression_in_clause)
7468 << "device" << ValExpr->getSourceRange();
7469 return nullptr;
7470 }
7471 }
Michael Wonge710d542015-08-07 16:16:36 +00007472 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7473}
Kelvin Li0bff7af2015-11-23 05:32:03 +00007474
7475static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
7476 DSAStackTy *Stack, CXXRecordDecl *RD) {
7477 if (!RD || RD->isInvalidDecl())
7478 return true;
7479
7480 auto QTy = SemaRef.Context.getRecordType(RD);
7481 if (RD->isDynamicClass()) {
7482 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7483 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
7484 return false;
7485 }
7486 auto *DC = RD;
7487 bool IsCorrect = true;
7488 for (auto *I : DC->decls()) {
7489 if (I) {
7490 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
7491 if (MD->isStatic()) {
7492 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7493 SemaRef.Diag(MD->getLocation(),
7494 diag::note_omp_static_member_in_target);
7495 IsCorrect = false;
7496 }
7497 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
7498 if (VD->isStaticDataMember()) {
7499 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
7500 SemaRef.Diag(VD->getLocation(),
7501 diag::note_omp_static_member_in_target);
7502 IsCorrect = false;
7503 }
7504 }
7505 }
7506 }
7507
7508 for (auto &I : RD->bases()) {
7509 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
7510 I.getType()->getAsCXXRecordDecl()))
7511 IsCorrect = false;
7512 }
7513 return IsCorrect;
7514}
7515
7516static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
7517 DSAStackTy *Stack, QualType QTy) {
7518 NamedDecl *ND;
7519 if (QTy->isIncompleteType(&ND)) {
7520 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
7521 return false;
7522 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
7523 if (!RD->isInvalidDecl() &&
7524 !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
7525 return false;
7526 }
7527 return true;
7528}
7529
7530OMPClause *Sema::ActOnOpenMPMapClause(
7531 OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType,
7532 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
7533 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
7534 SmallVector<Expr *, 4> Vars;
7535
7536 for (auto &RE : VarList) {
7537 assert(RE && "Null expr in omp map");
7538 if (isa<DependentScopeDeclRefExpr>(RE)) {
7539 // It will be analyzed later.
7540 Vars.push_back(RE);
7541 continue;
7542 }
7543 SourceLocation ELoc = RE->getExprLoc();
7544
7545 // OpenMP [2.14.5, Restrictions]
7546 // A variable that is part of another variable (such as field of a
7547 // structure) but is not an array element or an array section cannot appear
7548 // in a map clause.
7549 auto *VE = RE->IgnoreParenLValueCasts();
7550
7551 if (VE->isValueDependent() || VE->isTypeDependent() ||
7552 VE->isInstantiationDependent() ||
7553 VE->containsUnexpandedParameterPack()) {
7554 // It will be analyzed later.
7555 Vars.push_back(RE);
7556 continue;
7557 }
7558
7559 auto *SimpleExpr = RE->IgnoreParenCasts();
7560 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
7561 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
7562 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
7563
7564 if (!RE->IgnoreParenImpCasts()->isLValue() ||
7565 (!OASE && !ASE && !DE) ||
7566 (DE && !isa<VarDecl>(DE->getDecl())) ||
7567 (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
7568 !ASE->getBase()->getType()->isArrayType())) {
7569 Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
7570 << RE->getSourceRange();
7571 continue;
7572 }
7573
7574 Decl *D = nullptr;
7575 if (DE) {
7576 D = DE->getDecl();
7577 } else if (ASE) {
7578 auto *B = ASE->getBase()->IgnoreParenCasts();
7579 D = dyn_cast<DeclRefExpr>(B)->getDecl();
7580 } else if (OASE) {
7581 auto *B = OASE->getBase();
7582 D = dyn_cast<DeclRefExpr>(B)->getDecl();
7583 }
7584 assert(D && "Null decl on map clause.");
7585 auto *VD = cast<VarDecl>(D);
7586
7587 // OpenMP [2.14.5, Restrictions, p.8]
7588 // threadprivate variables cannot appear in a map clause.
7589 if (DSAStack->isThreadPrivate(VD)) {
7590 auto DVar = DSAStack->getTopDSA(VD, false);
7591 Diag(ELoc, diag::err_omp_threadprivate_in_map);
7592 ReportOriginalDSA(*this, DSAStack, VD, DVar);
7593 continue;
7594 }
7595
7596 // OpenMP [2.14.5, Restrictions, p.2]
7597 // At most one list item can be an array item derived from a given variable
7598 // in map clauses of the same construct.
7599 // OpenMP [2.14.5, Restrictions, p.3]
7600 // List items of map clauses in the same construct must not share original
7601 // storage.
7602 // OpenMP [2.14.5, Restrictions, C/C++, p.2]
7603 // A variable for which the type is pointer, reference to array, or
7604 // reference to pointer and an array section derived from that variable
7605 // must not appear as list items of map clauses of the same construct.
7606 DSAStackTy::MapInfo MI = DSAStack->IsMappedInCurrentRegion(VD);
7607 if (MI.RefExpr) {
7608 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
7609 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
7610 << MI.RefExpr->getSourceRange();
7611 continue;
7612 }
7613
7614 // OpenMP [2.14.5, Restrictions, C/C++, p.3,4]
7615 // A variable for which the type is pointer, reference to array, or
7616 // reference to pointer must not appear as a list item if the enclosing
7617 // device data environment already contains an array section derived from
7618 // that variable.
7619 // An array section derived from a variable for which the type is pointer,
7620 // reference to array, or reference to pointer must not appear as a list
7621 // item if the enclosing device data environment already contains that
7622 // variable.
7623 QualType Type = VD->getType();
7624 MI = DSAStack->getMapInfoForVar(VD);
7625 if (MI.RefExpr && (isa<DeclRefExpr>(MI.RefExpr->IgnoreParenLValueCasts()) !=
7626 isa<DeclRefExpr>(VE)) &&
7627 (Type->isPointerType() || Type->isReferenceType())) {
7628 Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
7629 Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
7630 << MI.RefExpr->getSourceRange();
7631 continue;
7632 }
7633
7634 // OpenMP [2.14.5, Restrictions, C/C++, p.7]
7635 // A list item must have a mappable type.
7636 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
7637 DSAStack, Type))
7638 continue;
7639
7640 Vars.push_back(RE);
7641 MI.RefExpr = RE;
7642 DSAStack->addMapInfoForVar(VD, MI);
7643 }
7644 if (Vars.empty())
7645 return nullptr;
7646
7647 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7648 MapTypeModifier, MapType, MapLoc);
7649}
Kelvin Li099bb8c2015-11-24 20:50:12 +00007650
7651OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
7652 SourceLocation StartLoc,
7653 SourceLocation LParenLoc,
7654 SourceLocation EndLoc) {
7655 Expr *ValExpr = NumTeams;
7656 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7657 !ValExpr->isInstantiationDependent()) {
7658 SourceLocation Loc = ValExpr->getExprLoc();
7659 ExprResult Value = PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7660 if (Value.isInvalid())
7661 return nullptr;
7662
7663 // OpenMP [teams Constrcut, Restrictions]
7664 // The num_teams expression must evaluate to a positive integer value.
7665 llvm::APSInt Result;
7666 if (Value.get()->isIntegerConstantExpr(Result, Context) &&
7667 Result.isSigned() && !Result.isStrictlyPositive()) {
7668 Diag(Loc, diag::err_omp_negative_expression_in_clause)
7669 << "num_teams" << ValExpr->getSourceRange();
7670 return nullptr;
7671 }
7672 }
7673
7674 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7675}