blob: 040bddc6c708bd88ef24043b85da2e0ff497f7c4 [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 Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
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.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001092 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001597 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001598 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001599 QualType KmpInt32PtrTy =
1600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001601 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001602 std::make_pair(".global_tid.", KmpInt32PtrTy),
1603 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1604 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1607 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001608 break;
1609 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001610 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001611 case OMPD_target_parallel: {
1612 Sema::CapturedParamNameType ParamsTarget[] = {
1613 std::make_pair(StringRef(), QualType()) // __context with shared vars
1614 };
1615 // Start a captured region for 'target' with no implicit parameters.
1616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1617 ParamsTarget);
1618 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1619 QualType KmpInt32PtrTy =
1620 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001621 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001622 std::make_pair(".global_tid.", KmpInt32PtrTy),
1623 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1624 std::make_pair(StringRef(), QualType()) // __context with shared vars
1625 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001626 // Start a captured region for 'teams' or 'parallel'. Both regions have
1627 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001628 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001629 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001630 break;
1631 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001632 case OMPD_simd:
1633 case OMPD_for:
1634 case OMPD_for_simd:
1635 case OMPD_sections:
1636 case OMPD_section:
1637 case OMPD_single:
1638 case OMPD_master:
1639 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001640 case OMPD_taskgroup:
1641 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001642 case OMPD_ordered:
1643 case OMPD_atomic:
1644 case OMPD_target_data:
1645 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001646 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001647 case OMPD_target_parallel_for_simd:
1648 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001649 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001650 std::make_pair(StringRef(), QualType()) // __context with shared vars
1651 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001652 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1653 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001654 break;
1655 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001656 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001657 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001658 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1659 FunctionProtoType::ExtProtoInfo EPI;
1660 EPI.Variadic = true;
1661 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001662 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001663 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001664 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1665 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1666 std::make_pair(".copy_fn.",
1667 Context.getPointerType(CopyFnType).withConst()),
1668 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001669 std::make_pair(StringRef(), QualType()) // __context with shared vars
1670 };
1671 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1672 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001673 // Mark this captured region as inlined, because we don't use outlined
1674 // function directly.
1675 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1676 AlwaysInlineAttr::CreateImplicit(
1677 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001678 break;
1679 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001680 case OMPD_taskloop:
1681 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001682 QualType KmpInt32Ty =
1683 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1684 QualType KmpUInt64Ty =
1685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1686 QualType KmpInt64Ty =
1687 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1688 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1689 FunctionProtoType::ExtProtoInfo EPI;
1690 EPI.Variadic = true;
1691 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001692 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001693 std::make_pair(".global_tid.", KmpInt32Ty),
1694 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1695 std::make_pair(".privates.",
1696 Context.VoidPtrTy.withConst().withRestrict()),
1697 std::make_pair(
1698 ".copy_fn.",
1699 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1700 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1701 std::make_pair(".lb.", KmpUInt64Ty),
1702 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1703 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001704 std::make_pair(StringRef(), QualType()) // __context with shared vars
1705 };
1706 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1707 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001708 // Mark this captured region as inlined, because we don't use outlined
1709 // function directly.
1710 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1711 AlwaysInlineAttr::CreateImplicit(
1712 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001713 break;
1714 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001715 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001716 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001717 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001718 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001719 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001720 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001721 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001722 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001723 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001724 case OMPD_target_teams_distribute_parallel_for_simd:
1725 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001726 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1727 QualType KmpInt32PtrTy =
1728 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1729 Sema::CapturedParamNameType Params[] = {
1730 std::make_pair(".global_tid.", KmpInt32PtrTy),
1731 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1732 std::make_pair(".previous.lb.", Context.getSizeType()),
1733 std::make_pair(".previous.ub.", Context.getSizeType()),
1734 std::make_pair(StringRef(), QualType()) // __context with shared vars
1735 };
1736 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1737 Params);
1738 break;
1739 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001740 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001741 case OMPD_taskyield:
1742 case OMPD_barrier:
1743 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001744 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001745 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001746 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001747 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001748 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001749 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001750 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001751 case OMPD_declare_target:
1752 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001753 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001754 llvm_unreachable("OpenMP Directive is not allowed");
1755 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001756 llvm_unreachable("Unknown OpenMP directive");
1757 }
1758}
1759
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001760int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1761 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1762 getOpenMPCaptureRegions(CaptureRegions, DKind);
1763 return CaptureRegions.size();
1764}
1765
Alexey Bataev3392d762016-02-16 11:18:12 +00001766static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001767 Expr *CaptureExpr, bool WithInit,
1768 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001769 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001770 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001771 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001772 QualType Ty = Init->getType();
1773 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1774 if (S.getLangOpts().CPlusPlus)
1775 Ty = C.getLValueReferenceType(Ty);
1776 else {
1777 Ty = C.getPointerType(Ty);
1778 ExprResult Res =
1779 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1780 if (!Res.isUsable())
1781 return nullptr;
1782 Init = Res.get();
1783 }
Alexey Bataev61205072016-03-02 04:57:40 +00001784 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001785 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001786 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1787 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001788 if (!WithInit)
1789 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001790 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001791 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001792 return CED;
1793}
1794
Alexey Bataev61205072016-03-02 04:57:40 +00001795static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1796 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001797 OMPCapturedExprDecl *CD;
1798 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1799 CD = cast<OMPCapturedExprDecl>(VD);
1800 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001801 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1802 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001803 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001804 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001805}
1806
Alexey Bataev5a3af132016-03-29 08:58:54 +00001807static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1808 if (!Ref) {
1809 auto *CD =
1810 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1811 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1812 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1813 CaptureExpr->getExprLoc());
1814 }
1815 ExprResult Res = Ref;
1816 if (!S.getLangOpts().CPlusPlus &&
1817 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1818 Ref->getType()->isPointerType())
1819 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1820 if (!Res.isUsable())
1821 return ExprError();
1822 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001823}
1824
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001825namespace {
1826// OpenMP directives parsed in this section are represented as a
1827// CapturedStatement with an associated statement. If a syntax error
1828// is detected during the parsing of the associated statement, the
1829// compiler must abort processing and close the CapturedStatement.
1830//
1831// Combined directives such as 'target parallel' have more than one
1832// nested CapturedStatements. This RAII ensures that we unwind out
1833// of all the nested CapturedStatements when an error is found.
1834class CaptureRegionUnwinderRAII {
1835private:
1836 Sema &S;
1837 bool &ErrorFound;
1838 OpenMPDirectiveKind DKind;
1839
1840public:
1841 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1842 OpenMPDirectiveKind DKind)
1843 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1844 ~CaptureRegionUnwinderRAII() {
1845 if (ErrorFound) {
1846 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1847 while (--ThisCaptureLevel >= 0)
1848 S.ActOnCapturedRegionError();
1849 }
1850 }
1851};
1852} // namespace
1853
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001854StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1855 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001856 bool ErrorFound = false;
1857 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1858 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001859 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001860 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001861 return StmtError();
1862 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001863
1864 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001865 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001866 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001867 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001868 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001869 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001870 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001871 Clause->getClauseKind() == OMPC_copyprivate ||
1872 (getLangOpts().OpenMPUseTLS &&
1873 getASTContext().getTargetInfo().isTLSSupported() &&
1874 Clause->getClauseKind() == OMPC_copyin)) {
1875 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001876 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001877 for (auto *VarRef : Clause->children()) {
1878 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001879 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001880 }
1881 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001882 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001883 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001884 if (auto *C = OMPClauseWithPreInit::get(Clause))
1885 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001886 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1887 if (auto *E = C->getPostUpdateExpr())
1888 MarkDeclarationsReferencedInExpr(E);
1889 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001890 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001891 if (Clause->getClauseKind() == OMPC_schedule)
1892 SC = cast<OMPScheduleClause>(Clause);
1893 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001894 OC = cast<OMPOrderedClause>(Clause);
1895 else if (Clause->getClauseKind() == OMPC_linear)
1896 LCs.push_back(cast<OMPLinearClause>(Clause));
1897 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001898 // OpenMP, 2.7.1 Loop Construct, Restrictions
1899 // The nonmonotonic modifier cannot be specified if an ordered clause is
1900 // specified.
1901 if (SC &&
1902 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1903 SC->getSecondScheduleModifier() ==
1904 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1905 OC) {
1906 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1907 ? SC->getFirstScheduleModifierLoc()
1908 : SC->getSecondScheduleModifierLoc(),
1909 diag::err_omp_schedule_nonmonotonic_ordered)
1910 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1911 ErrorFound = true;
1912 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001913 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1914 for (auto *C : LCs) {
1915 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1916 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1917 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001918 ErrorFound = true;
1919 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001920 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1921 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1922 OC->getNumForLoops()) {
1923 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1924 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1925 ErrorFound = true;
1926 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001927 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001928 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001929 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001930 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001931 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1932 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
1933 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
1934 // Mark all variables in private list clauses as used in inner region.
1935 // Required for proper codegen of combined directives.
1936 // TODO: add processing for other clauses.
1937 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1938 for (auto *C : PICs) {
1939 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
1940 // Find the particular capture region for the clause if the
1941 // directive is a combined one with multiple capture regions.
1942 // If the directive is not a combined one, the capture region
1943 // associated with the clause is OMPD_unknown and is generated
1944 // only once.
1945 if (CaptureRegion == ThisCaptureRegion ||
1946 CaptureRegion == OMPD_unknown) {
1947 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1948 for (auto *D : DS->decls())
1949 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1950 }
1951 }
1952 }
1953 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001954 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001955 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001956 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001957}
1958
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001959static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1960 OpenMPDirectiveKind CurrentRegion,
1961 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001962 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001963 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001964 if (Stack->getCurScope()) {
1965 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001966 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001967 bool NestingProhibited = false;
1968 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001969 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001970 enum {
1971 NoRecommend,
1972 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001973 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001974 ShouldBeInTargetRegion,
1975 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001976 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001977 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001978 // OpenMP [2.16, Nesting of Regions]
1979 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001980 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001981 // An ordered construct with the simd clause is the only OpenMP
1982 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001983 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001984 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1985 // message.
1986 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1987 ? diag::err_omp_prohibited_region_simd
1988 : diag::warn_omp_nesting_simd);
1989 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001990 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001991 if (ParentRegion == OMPD_atomic) {
1992 // OpenMP [2.16, Nesting of Regions]
1993 // OpenMP constructs may not be nested inside an atomic region.
1994 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1995 return true;
1996 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001997 if (CurrentRegion == OMPD_section) {
1998 // OpenMP [2.7.2, sections Construct, Restrictions]
1999 // Orphaned section directives are prohibited. That is, the section
2000 // directives must appear within the sections construct and must not be
2001 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002002 if (ParentRegion != OMPD_sections &&
2003 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002004 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2005 << (ParentRegion != OMPD_unknown)
2006 << getOpenMPDirectiveName(ParentRegion);
2007 return true;
2008 }
2009 return false;
2010 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002011 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002012 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002013 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002014 if (ParentRegion == OMPD_unknown &&
2015 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002016 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002017 if (CurrentRegion == OMPD_cancellation_point ||
2018 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002019 // OpenMP [2.16, Nesting of Regions]
2020 // A cancellation point construct for which construct-type-clause is
2021 // taskgroup must be nested inside a task construct. A cancellation
2022 // point construct for which construct-type-clause is not taskgroup must
2023 // be closely nested inside an OpenMP construct that matches the type
2024 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002025 // A cancel construct for which construct-type-clause is taskgroup must be
2026 // nested inside a task construct. A cancel construct for which
2027 // construct-type-clause is not taskgroup must be closely nested inside an
2028 // OpenMP construct that matches the type specified in
2029 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002030 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002031 !((CancelRegion == OMPD_parallel &&
2032 (ParentRegion == OMPD_parallel ||
2033 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002034 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002035 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2036 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002037 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2038 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002039 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2040 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002041 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002042 // OpenMP [2.16, Nesting of Regions]
2043 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002044 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002045 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002046 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002047 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2048 // OpenMP [2.16, Nesting of Regions]
2049 // A critical region may not be nested (closely or otherwise) inside a
2050 // critical region with the same name. Note that this restriction is not
2051 // sufficient to prevent deadlock.
2052 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002053 bool DeadLock = Stack->hasDirective(
2054 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2055 const DeclarationNameInfo &DNI,
2056 SourceLocation Loc) -> bool {
2057 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2058 PreviousCriticalLoc = Loc;
2059 return true;
2060 } else
2061 return false;
2062 },
2063 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002064 if (DeadLock) {
2065 SemaRef.Diag(StartLoc,
2066 diag::err_omp_prohibited_region_critical_same_name)
2067 << CurrentName.getName();
2068 if (PreviousCriticalLoc.isValid())
2069 SemaRef.Diag(PreviousCriticalLoc,
2070 diag::note_omp_previous_critical_region);
2071 return true;
2072 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002073 } else if (CurrentRegion == OMPD_barrier) {
2074 // OpenMP [2.16, Nesting of Regions]
2075 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002076 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002077 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2078 isOpenMPTaskingDirective(ParentRegion) ||
2079 ParentRegion == OMPD_master ||
2080 ParentRegion == OMPD_critical ||
2081 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002082 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002083 !isOpenMPParallelDirective(CurrentRegion) &&
2084 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002085 // OpenMP [2.16, Nesting of Regions]
2086 // A worksharing region may not be closely nested inside a worksharing,
2087 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002088 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2089 isOpenMPTaskingDirective(ParentRegion) ||
2090 ParentRegion == OMPD_master ||
2091 ParentRegion == OMPD_critical ||
2092 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002093 Recommend = ShouldBeInParallelRegion;
2094 } else if (CurrentRegion == OMPD_ordered) {
2095 // OpenMP [2.16, Nesting of Regions]
2096 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002097 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002098 // An ordered region must be closely nested inside a loop region (or
2099 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002100 // OpenMP [2.8.1,simd Construct, Restrictions]
2101 // An ordered construct with the simd clause is the only OpenMP construct
2102 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002103 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002104 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002105 !(isOpenMPSimdDirective(ParentRegion) ||
2106 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002107 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002108 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002109 // OpenMP [2.16, Nesting of Regions]
2110 // If specified, a teams construct must be contained within a target
2111 // construct.
2112 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002113 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002114 Recommend = ShouldBeInTargetRegion;
2115 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2116 }
Kelvin Libf594a52016-12-17 05:48:59 +00002117 if (!NestingProhibited &&
2118 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2119 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2120 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002121 // OpenMP [2.16, Nesting of Regions]
2122 // distribute, parallel, parallel sections, parallel workshare, and the
2123 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2124 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002125 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2126 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002127 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002128 }
David Majnemer9d168222016-08-05 17:44:54 +00002129 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002130 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002131 // OpenMP 4.5 [2.17 Nesting of Regions]
2132 // The region associated with the distribute construct must be strictly
2133 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002134 NestingProhibited =
2135 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002136 Recommend = ShouldBeInTeamsRegion;
2137 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002138 if (!NestingProhibited &&
2139 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2140 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2141 // OpenMP 4.5 [2.17 Nesting of Regions]
2142 // If a target, target update, target data, target enter data, or
2143 // target exit data construct is encountered during execution of a
2144 // target region, the behavior is unspecified.
2145 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002146 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2147 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002148 if (isOpenMPTargetExecutionDirective(K)) {
2149 OffendingRegion = K;
2150 return true;
2151 } else
2152 return false;
2153 },
2154 false /* don't skip top directive */);
2155 CloseNesting = false;
2156 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002157 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002158 if (OrphanSeen) {
2159 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2160 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2161 } else {
2162 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2163 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2164 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2165 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002166 return true;
2167 }
2168 }
2169 return false;
2170}
2171
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002172static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2173 ArrayRef<OMPClause *> Clauses,
2174 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2175 bool ErrorFound = false;
2176 unsigned NamedModifiersNumber = 0;
2177 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2178 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002179 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002180 for (const auto *C : Clauses) {
2181 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2182 // At most one if clause without a directive-name-modifier can appear on
2183 // the directive.
2184 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2185 if (FoundNameModifiers[CurNM]) {
2186 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2187 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2188 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2189 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002190 } else if (CurNM != OMPD_unknown) {
2191 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002192 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002193 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002194 FoundNameModifiers[CurNM] = IC;
2195 if (CurNM == OMPD_unknown)
2196 continue;
2197 // Check if the specified name modifier is allowed for the current
2198 // directive.
2199 // At most one if clause with the particular directive-name-modifier can
2200 // appear on the directive.
2201 bool MatchFound = false;
2202 for (auto NM : AllowedNameModifiers) {
2203 if (CurNM == NM) {
2204 MatchFound = true;
2205 break;
2206 }
2207 }
2208 if (!MatchFound) {
2209 S.Diag(IC->getNameModifierLoc(),
2210 diag::err_omp_wrong_if_directive_name_modifier)
2211 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2212 ErrorFound = true;
2213 }
2214 }
2215 }
2216 // If any if clause on the directive includes a directive-name-modifier then
2217 // all if clauses on the directive must include a directive-name-modifier.
2218 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2219 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2220 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2221 diag::err_omp_no_more_if_clause);
2222 } else {
2223 std::string Values;
2224 std::string Sep(", ");
2225 unsigned AllowedCnt = 0;
2226 unsigned TotalAllowedNum =
2227 AllowedNameModifiers.size() - NamedModifiersNumber;
2228 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2229 ++Cnt) {
2230 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2231 if (!FoundNameModifiers[NM]) {
2232 Values += "'";
2233 Values += getOpenMPDirectiveName(NM);
2234 Values += "'";
2235 if (AllowedCnt + 2 == TotalAllowedNum)
2236 Values += " or ";
2237 else if (AllowedCnt + 1 != TotalAllowedNum)
2238 Values += Sep;
2239 ++AllowedCnt;
2240 }
2241 }
2242 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2243 diag::err_omp_unnamed_if_clause)
2244 << (TotalAllowedNum > 1) << Values;
2245 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002246 for (auto Loc : NameModifierLoc) {
2247 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2248 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002249 ErrorFound = true;
2250 }
2251 return ErrorFound;
2252}
2253
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002254StmtResult Sema::ActOnOpenMPExecutableDirective(
2255 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2256 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2257 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002258 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002259 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2260 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002261 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002262
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002263 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002264 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002265 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002266 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002267 if (AStmt) {
2268 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2269
2270 // Check default data sharing attributes for referenced variables.
2271 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002272 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2273 Stmt *S = AStmt;
2274 while (--ThisCaptureLevel >= 0)
2275 S = cast<CapturedStmt>(S)->getCapturedStmt();
2276 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002277 if (DSAChecker.isErrorFound())
2278 return StmtError();
2279 // Generate list of implicitly defined firstprivate variables.
2280 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002281
2282 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2283 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2284 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2285 SourceLocation(), SourceLocation())) {
2286 ClausesWithImplicit.push_back(Implicit);
2287 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2288 DSAChecker.getImplicitFirstprivate().size();
2289 } else
2290 ErrorFound = true;
2291 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002292 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002293
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002294 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002295 switch (Kind) {
2296 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002297 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2298 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002299 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002300 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002301 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002302 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2303 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002304 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002305 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002306 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2307 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002308 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002309 case OMPD_for_simd:
2310 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2311 EndLoc, VarsWithInheritedDSA);
2312 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002313 case OMPD_sections:
2314 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2315 EndLoc);
2316 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002317 case OMPD_section:
2318 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002319 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002320 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2321 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002322 case OMPD_single:
2323 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2324 EndLoc);
2325 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002326 case OMPD_master:
2327 assert(ClausesWithImplicit.empty() &&
2328 "No clauses are allowed for 'omp master' directive");
2329 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2330 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002331 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002332 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2333 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002334 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002335 case OMPD_parallel_for:
2336 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2337 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002338 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002339 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002340 case OMPD_parallel_for_simd:
2341 Res = ActOnOpenMPParallelForSimdDirective(
2342 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002343 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002344 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002345 case OMPD_parallel_sections:
2346 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2347 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002348 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002349 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002350 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002351 Res =
2352 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002353 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002354 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002355 case OMPD_taskyield:
2356 assert(ClausesWithImplicit.empty() &&
2357 "No clauses are allowed for 'omp taskyield' directive");
2358 assert(AStmt == nullptr &&
2359 "No associated statement allowed for 'omp taskyield' directive");
2360 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2361 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002362 case OMPD_barrier:
2363 assert(ClausesWithImplicit.empty() &&
2364 "No clauses are allowed for 'omp barrier' directive");
2365 assert(AStmt == nullptr &&
2366 "No associated statement allowed for 'omp barrier' directive");
2367 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2368 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002369 case OMPD_taskwait:
2370 assert(ClausesWithImplicit.empty() &&
2371 "No clauses are allowed for 'omp taskwait' directive");
2372 assert(AStmt == nullptr &&
2373 "No associated statement allowed for 'omp taskwait' directive");
2374 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2375 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002376 case OMPD_taskgroup:
2377 assert(ClausesWithImplicit.empty() &&
2378 "No clauses are allowed for 'omp taskgroup' directive");
2379 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2380 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002381 case OMPD_flush:
2382 assert(AStmt == nullptr &&
2383 "No associated statement allowed for 'omp flush' directive");
2384 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2385 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002386 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002387 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2388 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002389 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002390 case OMPD_atomic:
2391 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2392 EndLoc);
2393 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002394 case OMPD_teams:
2395 Res =
2396 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2397 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002398 case OMPD_target:
2399 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2400 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002401 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002402 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002403 case OMPD_target_parallel:
2404 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2405 StartLoc, EndLoc);
2406 AllowedNameModifiers.push_back(OMPD_target);
2407 AllowedNameModifiers.push_back(OMPD_parallel);
2408 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002409 case OMPD_target_parallel_for:
2410 Res = ActOnOpenMPTargetParallelForDirective(
2411 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2412 AllowedNameModifiers.push_back(OMPD_target);
2413 AllowedNameModifiers.push_back(OMPD_parallel);
2414 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002415 case OMPD_cancellation_point:
2416 assert(ClausesWithImplicit.empty() &&
2417 "No clauses are allowed for 'omp cancellation point' directive");
2418 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2419 "cancellation point' directive");
2420 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2421 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002422 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002423 assert(AStmt == nullptr &&
2424 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002425 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2426 CancelRegion);
2427 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002428 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002429 case OMPD_target_data:
2430 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2431 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002432 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002433 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002434 case OMPD_target_enter_data:
2435 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2436 EndLoc);
2437 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2438 break;
Samuel Antao72590762016-01-19 20:04:50 +00002439 case OMPD_target_exit_data:
2440 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2441 EndLoc);
2442 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2443 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002444 case OMPD_taskloop:
2445 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2446 EndLoc, VarsWithInheritedDSA);
2447 AllowedNameModifiers.push_back(OMPD_taskloop);
2448 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002449 case OMPD_taskloop_simd:
2450 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2451 EndLoc, VarsWithInheritedDSA);
2452 AllowedNameModifiers.push_back(OMPD_taskloop);
2453 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002454 case OMPD_distribute:
2455 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2456 EndLoc, VarsWithInheritedDSA);
2457 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002458 case OMPD_target_update:
2459 assert(!AStmt && "Statement is not allowed for target update");
2460 Res =
2461 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2462 AllowedNameModifiers.push_back(OMPD_target_update);
2463 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002464 case OMPD_distribute_parallel_for:
2465 Res = ActOnOpenMPDistributeParallelForDirective(
2466 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2467 AllowedNameModifiers.push_back(OMPD_parallel);
2468 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002469 case OMPD_distribute_parallel_for_simd:
2470 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2472 AllowedNameModifiers.push_back(OMPD_parallel);
2473 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002474 case OMPD_distribute_simd:
2475 Res = ActOnOpenMPDistributeSimdDirective(
2476 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2477 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002478 case OMPD_target_parallel_for_simd:
2479 Res = ActOnOpenMPTargetParallelForSimdDirective(
2480 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2481 AllowedNameModifiers.push_back(OMPD_target);
2482 AllowedNameModifiers.push_back(OMPD_parallel);
2483 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002484 case OMPD_target_simd:
2485 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2486 EndLoc, VarsWithInheritedDSA);
2487 AllowedNameModifiers.push_back(OMPD_target);
2488 break;
Kelvin Li02532872016-08-05 14:37:37 +00002489 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002490 Res = ActOnOpenMPTeamsDistributeDirective(
2491 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002492 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002493 case OMPD_teams_distribute_simd:
2494 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2495 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2496 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002497 case OMPD_teams_distribute_parallel_for_simd:
2498 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2500 AllowedNameModifiers.push_back(OMPD_parallel);
2501 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002502 case OMPD_teams_distribute_parallel_for:
2503 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2504 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2505 AllowedNameModifiers.push_back(OMPD_parallel);
2506 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002507 case OMPD_target_teams:
2508 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2509 EndLoc);
2510 AllowedNameModifiers.push_back(OMPD_target);
2511 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002512 case OMPD_target_teams_distribute:
2513 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2515 AllowedNameModifiers.push_back(OMPD_target);
2516 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002517 case OMPD_target_teams_distribute_parallel_for:
2518 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2519 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2520 AllowedNameModifiers.push_back(OMPD_target);
2521 AllowedNameModifiers.push_back(OMPD_parallel);
2522 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002523 case OMPD_target_teams_distribute_parallel_for_simd:
2524 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2525 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2526 AllowedNameModifiers.push_back(OMPD_target);
2527 AllowedNameModifiers.push_back(OMPD_parallel);
2528 break;
Kelvin Lida681182017-01-10 18:08:18 +00002529 case OMPD_target_teams_distribute_simd:
2530 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2531 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2532 AllowedNameModifiers.push_back(OMPD_target);
2533 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002534 case OMPD_declare_target:
2535 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002536 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002537 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002538 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002539 llvm_unreachable("OpenMP Directive is not allowed");
2540 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002541 llvm_unreachable("Unknown OpenMP directive");
2542 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002543
Alexey Bataev4acb8592014-07-07 13:01:15 +00002544 for (auto P : VarsWithInheritedDSA) {
2545 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2546 << P.first << P.second->getSourceRange();
2547 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002548 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2549
2550 if (!AllowedNameModifiers.empty())
2551 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2552 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002553
Alexey Bataeved09d242014-05-28 05:53:51 +00002554 if (ErrorFound)
2555 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002556 return Res;
2557}
2558
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002559Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2560 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002561 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002562 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2563 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002564 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002565 assert(Linears.size() == LinModifiers.size());
2566 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002567 if (!DG || DG.get().isNull())
2568 return DeclGroupPtrTy();
2569
2570 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002571 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002572 return DG;
2573 }
2574 auto *ADecl = DG.get().getSingleDecl();
2575 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2576 ADecl = FTD->getTemplatedDecl();
2577
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002578 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2579 if (!FD) {
2580 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002581 return DeclGroupPtrTy();
2582 }
2583
Alexey Bataev2af33e32016-04-07 12:45:37 +00002584 // OpenMP [2.8.2, declare simd construct, Description]
2585 // The parameter of the simdlen clause must be a constant positive integer
2586 // expression.
2587 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002588 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002589 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002590 // OpenMP [2.8.2, declare simd construct, Description]
2591 // The special this pointer can be used as if was one of the arguments to the
2592 // function in any of the linear, aligned, or uniform clauses.
2593 // The uniform clause declares one or more arguments to have an invariant
2594 // value for all concurrent invocations of the function in the execution of a
2595 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002596 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2597 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002598 for (auto *E : Uniforms) {
2599 E = E->IgnoreParenImpCasts();
2600 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2601 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2602 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2603 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002604 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2605 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002606 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002607 }
2608 if (isa<CXXThisExpr>(E)) {
2609 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002610 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002611 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002612 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2613 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002614 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002615 // OpenMP [2.8.2, declare simd construct, Description]
2616 // The aligned clause declares that the object to which each list item points
2617 // is aligned to the number of bytes expressed in the optional parameter of
2618 // the aligned clause.
2619 // The special this pointer can be used as if was one of the arguments to the
2620 // function in any of the linear, aligned, or uniform clauses.
2621 // The type of list items appearing in the aligned clause must be array,
2622 // pointer, reference to array, or reference to pointer.
2623 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2624 Expr *AlignedThis = nullptr;
2625 for (auto *E : Aligneds) {
2626 E = E->IgnoreParenImpCasts();
2627 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2628 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2629 auto *CanonPVD = PVD->getCanonicalDecl();
2630 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2631 FD->getParamDecl(PVD->getFunctionScopeIndex())
2632 ->getCanonicalDecl() == CanonPVD) {
2633 // OpenMP [2.8.1, simd construct, Restrictions]
2634 // A list-item cannot appear in more than one aligned clause.
2635 if (AlignedArgs.count(CanonPVD) > 0) {
2636 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2637 << 1 << E->getSourceRange();
2638 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2639 diag::note_omp_explicit_dsa)
2640 << getOpenMPClauseName(OMPC_aligned);
2641 continue;
2642 }
2643 AlignedArgs[CanonPVD] = E;
2644 QualType QTy = PVD->getType()
2645 .getNonReferenceType()
2646 .getUnqualifiedType()
2647 .getCanonicalType();
2648 const Type *Ty = QTy.getTypePtrOrNull();
2649 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2650 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2651 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2652 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2653 }
2654 continue;
2655 }
2656 }
2657 if (isa<CXXThisExpr>(E)) {
2658 if (AlignedThis) {
2659 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2660 << 2 << E->getSourceRange();
2661 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2662 << getOpenMPClauseName(OMPC_aligned);
2663 }
2664 AlignedThis = E;
2665 continue;
2666 }
2667 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2668 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2669 }
2670 // The optional parameter of the aligned clause, alignment, must be a constant
2671 // positive integer expression. If no optional parameter is specified,
2672 // implementation-defined default alignments for SIMD instructions on the
2673 // target platforms are assumed.
2674 SmallVector<Expr *, 4> NewAligns;
2675 for (auto *E : Alignments) {
2676 ExprResult Align;
2677 if (E)
2678 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2679 NewAligns.push_back(Align.get());
2680 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002681 // OpenMP [2.8.2, declare simd construct, Description]
2682 // The linear clause declares one or more list items to be private to a SIMD
2683 // lane and to have a linear relationship with respect to the iteration space
2684 // of a loop.
2685 // The special this pointer can be used as if was one of the arguments to the
2686 // function in any of the linear, aligned, or uniform clauses.
2687 // When a linear-step expression is specified in a linear clause it must be
2688 // either a constant integer expression or an integer-typed parameter that is
2689 // specified in a uniform clause on the directive.
2690 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2691 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2692 auto MI = LinModifiers.begin();
2693 for (auto *E : Linears) {
2694 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2695 ++MI;
2696 E = E->IgnoreParenImpCasts();
2697 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2698 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2699 auto *CanonPVD = PVD->getCanonicalDecl();
2700 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2701 FD->getParamDecl(PVD->getFunctionScopeIndex())
2702 ->getCanonicalDecl() == CanonPVD) {
2703 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2704 // A list-item cannot appear in more than one linear clause.
2705 if (LinearArgs.count(CanonPVD) > 0) {
2706 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2707 << getOpenMPClauseName(OMPC_linear)
2708 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2709 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2710 diag::note_omp_explicit_dsa)
2711 << getOpenMPClauseName(OMPC_linear);
2712 continue;
2713 }
2714 // Each argument can appear in at most one uniform or linear clause.
2715 if (UniformedArgs.count(CanonPVD) > 0) {
2716 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2717 << getOpenMPClauseName(OMPC_linear)
2718 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2719 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2720 diag::note_omp_explicit_dsa)
2721 << getOpenMPClauseName(OMPC_uniform);
2722 continue;
2723 }
2724 LinearArgs[CanonPVD] = E;
2725 if (E->isValueDependent() || E->isTypeDependent() ||
2726 E->isInstantiationDependent() ||
2727 E->containsUnexpandedParameterPack())
2728 continue;
2729 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2730 PVD->getOriginalType());
2731 continue;
2732 }
2733 }
2734 if (isa<CXXThisExpr>(E)) {
2735 if (UniformedLinearThis) {
2736 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2737 << getOpenMPClauseName(OMPC_linear)
2738 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2739 << E->getSourceRange();
2740 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2741 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2742 : OMPC_linear);
2743 continue;
2744 }
2745 UniformedLinearThis = E;
2746 if (E->isValueDependent() || E->isTypeDependent() ||
2747 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2748 continue;
2749 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2750 E->getType());
2751 continue;
2752 }
2753 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2754 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2755 }
2756 Expr *Step = nullptr;
2757 Expr *NewStep = nullptr;
2758 SmallVector<Expr *, 4> NewSteps;
2759 for (auto *E : Steps) {
2760 // Skip the same step expression, it was checked already.
2761 if (Step == E || !E) {
2762 NewSteps.push_back(E ? NewStep : nullptr);
2763 continue;
2764 }
2765 Step = E;
2766 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2767 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2768 auto *CanonPVD = PVD->getCanonicalDecl();
2769 if (UniformedArgs.count(CanonPVD) == 0) {
2770 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2771 << Step->getSourceRange();
2772 } else if (E->isValueDependent() || E->isTypeDependent() ||
2773 E->isInstantiationDependent() ||
2774 E->containsUnexpandedParameterPack() ||
2775 CanonPVD->getType()->hasIntegerRepresentation())
2776 NewSteps.push_back(Step);
2777 else {
2778 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2779 << Step->getSourceRange();
2780 }
2781 continue;
2782 }
2783 NewStep = Step;
2784 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2785 !Step->isInstantiationDependent() &&
2786 !Step->containsUnexpandedParameterPack()) {
2787 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2788 .get();
2789 if (NewStep)
2790 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2791 }
2792 NewSteps.push_back(NewStep);
2793 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002794 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2795 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002796 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002797 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2798 const_cast<Expr **>(Linears.data()), Linears.size(),
2799 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2800 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002801 ADecl->addAttr(NewAttr);
2802 return ConvertDeclToDeclGroup(ADecl);
2803}
2804
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002805StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2806 Stmt *AStmt,
2807 SourceLocation StartLoc,
2808 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002809 if (!AStmt)
2810 return StmtError();
2811
Alexey Bataev9959db52014-05-06 10:08:46 +00002812 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2813 // 1.2.2 OpenMP Language Terminology
2814 // Structured block - An executable statement with a single entry at the
2815 // top and a single exit at the bottom.
2816 // The point of exit cannot be a branch out of the structured block.
2817 // longjmp() and throw() must not violate the entry/exit criteria.
2818 CS->getCapturedDecl()->setNothrow();
2819
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002820 getCurFunction()->setHasBranchProtectedScope();
2821
Alexey Bataev25e5b442015-09-15 12:52:43 +00002822 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2823 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002824}
2825
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002826namespace {
2827/// \brief Helper class for checking canonical form of the OpenMP loops and
2828/// extracting iteration space of each loop in the loop nest, that will be used
2829/// for IR generation.
2830class OpenMPIterationSpaceChecker {
2831 /// \brief Reference to Sema.
2832 Sema &SemaRef;
2833 /// \brief A location for diagnostics (when there is no some better location).
2834 SourceLocation DefaultLoc;
2835 /// \brief A location for diagnostics (when increment is not compatible).
2836 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002837 /// \brief A source location for referring to loop init later.
2838 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002839 /// \brief A source location for referring to condition later.
2840 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002841 /// \brief A source location for referring to increment later.
2842 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002843 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002844 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002845 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002846 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002847 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002848 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002849 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002850 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002851 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002852 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002853 /// \brief This flag is true when condition is one of:
2854 /// Var < UB
2855 /// Var <= UB
2856 /// UB > Var
2857 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002858 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002859 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002860 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002861 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002862 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002863
2864public:
2865 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002866 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002867 /// \brief Check init-expr for canonical loop form and save loop counter
2868 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002869 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002870 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2871 /// for less/greater and for strict/non-strict comparison.
2872 bool CheckCond(Expr *S);
2873 /// \brief Check incr-expr for canonical loop form and return true if it
2874 /// does not conform, otherwise save loop step (#Step).
2875 bool CheckInc(Expr *S);
2876 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002877 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002878 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002879 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002880 /// \brief Source range of the loop init.
2881 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2882 /// \brief Source range of the loop condition.
2883 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2884 /// \brief Source range of the loop increment.
2885 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2886 /// \brief True if the step should be subtracted.
2887 bool ShouldSubtractStep() const { return SubtractStep; }
2888 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002889 Expr *
2890 BuildNumIterations(Scope *S, const bool LimitedType,
2891 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002892 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002893 Expr *BuildPreCond(Scope *S, Expr *Cond,
2894 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002895 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002896 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2897 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002898 /// \brief Build reference expression to the private counter be used for
2899 /// codegen.
2900 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002901 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002902 Expr *BuildCounterInit() const;
2903 /// \brief Build step of the counter be used for codegen.
2904 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002905 /// \brief Return true if any expression is dependent.
2906 bool Dependent() const;
2907
2908private:
2909 /// \brief Check the right-hand side of an assignment in the increment
2910 /// expression.
2911 bool CheckIncRHS(Expr *RHS);
2912 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002913 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002914 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002915 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002916 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002917 /// \brief Helper to set loop increment.
2918 bool SetStep(Expr *NewStep, bool Subtract);
2919};
2920
2921bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002922 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002923 assert(!LB && !UB && !Step);
2924 return false;
2925 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002926 return LCDecl->getType()->isDependentType() ||
2927 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2928 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002929}
2930
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002931static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002932 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2933 E = ExprTemp->getSubExpr();
2934
2935 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2936 E = MTE->GetTemporaryExpr();
2937
2938 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2939 E = Binder->getSubExpr();
2940
2941 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2942 E = ICE->getSubExprAsWritten();
2943 return E->IgnoreParens();
2944}
2945
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002946bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2947 Expr *NewLCRefExpr,
2948 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002949 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002950 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002951 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002952 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002953 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002954 LCDecl = getCanonicalDecl(NewLCDecl);
2955 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002956 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2957 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002958 if ((Ctor->isCopyOrMoveConstructor() ||
2959 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2960 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002961 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002962 LB = NewLB;
2963 return false;
2964}
2965
2966bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002967 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002968 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002969 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2970 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002971 if (!NewUB)
2972 return true;
2973 UB = NewUB;
2974 TestIsLessOp = LessOp;
2975 TestIsStrictOp = StrictOp;
2976 ConditionSrcRange = SR;
2977 ConditionLoc = SL;
2978 return false;
2979}
2980
2981bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2982 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002983 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002984 if (!NewStep)
2985 return true;
2986 if (!NewStep->isValueDependent()) {
2987 // Check that the step is integer expression.
2988 SourceLocation StepLoc = NewStep->getLocStart();
2989 ExprResult Val =
2990 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2991 if (Val.isInvalid())
2992 return true;
2993 NewStep = Val.get();
2994
2995 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2996 // If test-expr is of form var relational-op b and relational-op is < or
2997 // <= then incr-expr must cause var to increase on each iteration of the
2998 // loop. If test-expr is of form var relational-op b and relational-op is
2999 // > or >= then incr-expr must cause var to decrease on each iteration of
3000 // the loop.
3001 // If test-expr is of form b relational-op var and relational-op is < or
3002 // <= then incr-expr must cause var to decrease on each iteration of the
3003 // loop. If test-expr is of form b relational-op var and relational-op is
3004 // > or >= then incr-expr must cause var to increase on each iteration of
3005 // the loop.
3006 llvm::APSInt Result;
3007 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3008 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3009 bool IsConstNeg =
3010 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003011 bool IsConstPos =
3012 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003013 bool IsConstZero = IsConstant && !Result.getBoolValue();
3014 if (UB && (IsConstZero ||
3015 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003016 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003017 SemaRef.Diag(NewStep->getExprLoc(),
3018 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003019 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003020 SemaRef.Diag(ConditionLoc,
3021 diag::note_omp_loop_cond_requres_compatible_incr)
3022 << TestIsLessOp << ConditionSrcRange;
3023 return true;
3024 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003025 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003026 NewStep =
3027 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3028 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003029 Subtract = !Subtract;
3030 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003031 }
3032
3033 Step = NewStep;
3034 SubtractStep = Subtract;
3035 return false;
3036}
3037
Alexey Bataev9c821032015-04-30 04:23:23 +00003038bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003039 // Check init-expr for canonical loop form and save loop counter
3040 // variable - #Var and its initialization value - #LB.
3041 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3042 // var = lb
3043 // integer-type var = lb
3044 // random-access-iterator-type var = lb
3045 // pointer-type var = lb
3046 //
3047 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003048 if (EmitDiags) {
3049 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3050 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003051 return true;
3052 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003053 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3054 if (!ExprTemp->cleanupsHaveSideEffects())
3055 S = ExprTemp->getSubExpr();
3056
Alexander Musmana5f070a2014-10-01 06:03:56 +00003057 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003058 if (Expr *E = dyn_cast<Expr>(S))
3059 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003060 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003061 if (BO->getOpcode() == BO_Assign) {
3062 auto *LHS = BO->getLHS()->IgnoreParens();
3063 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3064 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3065 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3066 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3067 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3068 }
3069 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3070 if (ME->isArrow() &&
3071 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3072 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3073 }
3074 }
David Majnemer9d168222016-08-05 17:44:54 +00003075 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003076 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003077 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003078 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003079 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003080 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003081 SemaRef.Diag(S->getLocStart(),
3082 diag::ext_omp_loop_not_canonical_init)
3083 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003084 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003085 }
3086 }
3087 }
David Majnemer9d168222016-08-05 17:44:54 +00003088 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003089 if (CE->getOperator() == OO_Equal) {
3090 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003091 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003092 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3093 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3094 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3095 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3096 }
3097 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3098 if (ME->isArrow() &&
3099 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3100 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3101 }
3102 }
3103 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003104
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003105 if (Dependent() || SemaRef.CurContext->isDependentContext())
3106 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003107 if (EmitDiags) {
3108 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3109 << S->getSourceRange();
3110 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111 return true;
3112}
3113
Alexey Bataev23b69422014-06-18 07:08:49 +00003114/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003115/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003116static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003117 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003118 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003119 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003120 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3121 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003122 if ((Ctor->isCopyOrMoveConstructor() ||
3123 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3124 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003125 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003126 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3127 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3128 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3129 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3130 return getCanonicalDecl(ME->getMemberDecl());
3131 return getCanonicalDecl(VD);
3132 }
3133 }
3134 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3135 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3136 return getCanonicalDecl(ME->getMemberDecl());
3137 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003138}
3139
3140bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3141 // Check test-expr for canonical form, save upper-bound UB, flags for
3142 // less/greater and for strict/non-strict comparison.
3143 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3144 // var relational-op b
3145 // b relational-op var
3146 //
3147 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003148 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003149 return true;
3150 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003151 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003152 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003153 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003154 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003155 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003156 return SetUB(BO->getRHS(),
3157 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3159 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003160 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003161 return SetUB(BO->getLHS(),
3162 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3163 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3164 BO->getSourceRange(), BO->getOperatorLoc());
3165 }
David Majnemer9d168222016-08-05 17:44:54 +00003166 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003167 if (CE->getNumArgs() == 2) {
3168 auto Op = CE->getOperator();
3169 switch (Op) {
3170 case OO_Greater:
3171 case OO_GreaterEqual:
3172 case OO_Less:
3173 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003174 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003175 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3176 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3177 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003178 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003179 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3180 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3181 CE->getOperatorLoc());
3182 break;
3183 default:
3184 break;
3185 }
3186 }
3187 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003188 if (Dependent() || SemaRef.CurContext->isDependentContext())
3189 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003190 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003191 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003192 return true;
3193}
3194
3195bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3196 // RHS of canonical loop form increment can be:
3197 // var + incr
3198 // incr + var
3199 // var - incr
3200 //
3201 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003202 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003203 if (BO->isAdditiveOp()) {
3204 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003205 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003206 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003207 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003208 return SetStep(BO->getLHS(), false);
3209 }
David Majnemer9d168222016-08-05 17:44:54 +00003210 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003211 bool IsAdd = CE->getOperator() == OO_Plus;
3212 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003213 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003214 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003215 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003216 return SetStep(CE->getArg(0), false);
3217 }
3218 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003219 if (Dependent() || SemaRef.CurContext->isDependentContext())
3220 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003221 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003222 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003223 return true;
3224}
3225
3226bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3227 // Check incr-expr for canonical loop form and return true if it
3228 // does not conform.
3229 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3230 // ++var
3231 // var++
3232 // --var
3233 // var--
3234 // var += incr
3235 // var -= incr
3236 // var = var + incr
3237 // var = incr + var
3238 // var = var - incr
3239 //
3240 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003241 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003242 return true;
3243 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003244 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3245 if (!ExprTemp->cleanupsHaveSideEffects())
3246 S = ExprTemp->getSubExpr();
3247
Alexander Musmana5f070a2014-10-01 06:03:56 +00003248 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003249 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003250 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003251 if (UO->isIncrementDecrementOp() &&
3252 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003253 return SetStep(SemaRef
3254 .ActOnIntegerConstant(UO->getLocStart(),
3255 (UO->isDecrementOp() ? -1 : 1))
3256 .get(),
3257 false);
3258 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003259 switch (BO->getOpcode()) {
3260 case BO_AddAssign:
3261 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003262 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003263 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3264 break;
3265 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003266 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003267 return CheckIncRHS(BO->getRHS());
3268 break;
3269 default:
3270 break;
3271 }
David Majnemer9d168222016-08-05 17:44:54 +00003272 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003273 switch (CE->getOperator()) {
3274 case OO_PlusPlus:
3275 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003276 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003277 return SetStep(SemaRef
3278 .ActOnIntegerConstant(
3279 CE->getLocStart(),
3280 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3281 .get(),
3282 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003283 break;
3284 case OO_PlusEqual:
3285 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003286 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003287 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3288 break;
3289 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003290 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003291 return CheckIncRHS(CE->getArg(1));
3292 break;
3293 default:
3294 break;
3295 }
3296 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003297 if (Dependent() || SemaRef.CurContext->isDependentContext())
3298 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003299 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003300 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003301 return true;
3302}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003303
Alexey Bataev5a3af132016-03-29 08:58:54 +00003304static ExprResult
3305tryBuildCapture(Sema &SemaRef, Expr *Capture,
3306 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003307 if (SemaRef.CurContext->isDependentContext())
3308 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003309 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3310 return SemaRef.PerformImplicitConversion(
3311 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3312 /*AllowExplicit=*/true);
3313 auto I = Captures.find(Capture);
3314 if (I != Captures.end())
3315 return buildCapture(SemaRef, Capture, I->second);
3316 DeclRefExpr *Ref = nullptr;
3317 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3318 Captures[Capture] = Ref;
3319 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003320}
3321
Alexander Musmana5f070a2014-10-01 06:03:56 +00003322/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003323Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3324 Scope *S, const bool LimitedType,
3325 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003326 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003327 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003328 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003329 SemaRef.getLangOpts().CPlusPlus) {
3330 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003331 auto *UBExpr = TestIsLessOp ? UB : LB;
3332 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003333 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3334 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003335 if (!Upper || !Lower)
3336 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003337
3338 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3339
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003340 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003341 // BuildBinOp already emitted error, this one is to point user to upper
3342 // and lower bound, and to tell what is passed to 'operator-'.
3343 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3344 << Upper->getSourceRange() << Lower->getSourceRange();
3345 return nullptr;
3346 }
3347 }
3348
3349 if (!Diff.isUsable())
3350 return nullptr;
3351
3352 // Upper - Lower [- 1]
3353 if (TestIsStrictOp)
3354 Diff = SemaRef.BuildBinOp(
3355 S, DefaultLoc, BO_Sub, Diff.get(),
3356 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3357 if (!Diff.isUsable())
3358 return nullptr;
3359
3360 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003361 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3362 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003363 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003364 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003365 if (!Diff.isUsable())
3366 return nullptr;
3367
3368 // Parentheses (for dumping/debugging purposes only).
3369 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3370 if (!Diff.isUsable())
3371 return nullptr;
3372
3373 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003374 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003375 if (!Diff.isUsable())
3376 return nullptr;
3377
Alexander Musman174b3ca2014-10-06 11:16:29 +00003378 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003379 QualType Type = Diff.get()->getType();
3380 auto &C = SemaRef.Context;
3381 bool UseVarType = VarType->hasIntegerRepresentation() &&
3382 C.getTypeSize(Type) > C.getTypeSize(VarType);
3383 if (!Type->isIntegerType() || UseVarType) {
3384 unsigned NewSize =
3385 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3386 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3387 : Type->hasSignedIntegerRepresentation();
3388 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003389 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3390 Diff = SemaRef.PerformImplicitConversion(
3391 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3392 if (!Diff.isUsable())
3393 return nullptr;
3394 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003395 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003396 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003397 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3398 if (NewSize != C.getTypeSize(Type)) {
3399 if (NewSize < C.getTypeSize(Type)) {
3400 assert(NewSize == 64 && "incorrect loop var size");
3401 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3402 << InitSrcRange << ConditionSrcRange;
3403 }
3404 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003405 NewSize, Type->hasSignedIntegerRepresentation() ||
3406 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003407 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3408 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3409 Sema::AA_Converting, true);
3410 if (!Diff.isUsable())
3411 return nullptr;
3412 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003413 }
3414 }
3415
Alexander Musmana5f070a2014-10-01 06:03:56 +00003416 return Diff.get();
3417}
3418
Alexey Bataev5a3af132016-03-29 08:58:54 +00003419Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3420 Scope *S, Expr *Cond,
3421 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003422 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3423 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3424 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003425
Alexey Bataev5a3af132016-03-29 08:58:54 +00003426 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3427 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3428 if (!NewLB.isUsable() || !NewUB.isUsable())
3429 return nullptr;
3430
Alexey Bataev62dbb972015-04-22 11:59:37 +00003431 auto CondExpr = SemaRef.BuildBinOp(
3432 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3433 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003434 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003435 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003436 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3437 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003438 CondExpr = SemaRef.PerformImplicitConversion(
3439 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3440 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003441 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003442 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3443 // Otherwise use original loop conditon and evaluate it in runtime.
3444 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3445}
3446
Alexander Musmana5f070a2014-10-01 06:03:56 +00003447/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003449 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003450 auto *VD = dyn_cast<VarDecl>(LCDecl);
3451 if (!VD) {
3452 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3453 auto *Ref = buildDeclRefExpr(
3454 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003455 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3456 // If the loop control decl is explicitly marked as private, do not mark it
3457 // as captured again.
3458 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3459 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003460 return Ref;
3461 }
3462 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003463 DefaultLoc);
3464}
3465
3466Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003467 if (LCDecl && !LCDecl->isInvalidDecl()) {
3468 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003469 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003470 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3471 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003472 if (PrivateVar->isInvalidDecl())
3473 return nullptr;
3474 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3475 }
3476 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003477}
3478
Samuel Antao4c8035b2016-12-12 18:00:20 +00003479/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003480Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3481
3482/// \brief Build step of the counter be used for codegen.
3483Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3484
3485/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003486struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003487 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003488 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003489 /// \brief This expression calculates the number of iterations in the loop.
3490 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003491 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003492 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003493 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003494 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003495 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003496 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003497 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003498 /// \brief This is step for the #CounterVar used to generate its update:
3499 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003500 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003501 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003502 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003503 /// \brief Source range of the loop init.
3504 SourceRange InitSrcRange;
3505 /// \brief Source range of the loop condition.
3506 SourceRange CondSrcRange;
3507 /// \brief Source range of the loop increment.
3508 SourceRange IncSrcRange;
3509};
3510
Alexey Bataev23b69422014-06-18 07:08:49 +00003511} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003512
Alexey Bataev9c821032015-04-30 04:23:23 +00003513void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3514 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3515 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003516 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3517 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003518 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3519 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003520 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3521 if (auto *D = ISC.GetLoopDecl()) {
3522 auto *VD = dyn_cast<VarDecl>(D);
3523 if (!VD) {
3524 if (auto *Private = IsOpenMPCapturedDecl(D))
3525 VD = Private;
3526 else {
3527 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3528 /*WithInit=*/false);
3529 VD = cast<VarDecl>(Ref->getDecl());
3530 }
3531 }
3532 DSAStack->addLoopControlVariable(D, VD);
3533 }
3534 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003535 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003536 }
3537}
3538
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003539/// \brief Called on a for stmt to check and extract its iteration space
3540/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003541static bool CheckOpenMPIterationSpace(
3542 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3543 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003544 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003545 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003546 LoopIterationSpace &ResultIterSpace,
3547 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003548 // OpenMP [2.6, Canonical Loop Form]
3549 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003550 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003551 if (!For) {
3552 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003553 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3554 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3555 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3556 if (NestedLoopCount > 1) {
3557 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3558 SemaRef.Diag(DSA.getConstructLoc(),
3559 diag::note_omp_collapse_ordered_expr)
3560 << 2 << CollapseLoopCountExpr->getSourceRange()
3561 << OrderedLoopCountExpr->getSourceRange();
3562 else if (CollapseLoopCountExpr)
3563 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3564 diag::note_omp_collapse_ordered_expr)
3565 << 0 << CollapseLoopCountExpr->getSourceRange();
3566 else
3567 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3568 diag::note_omp_collapse_ordered_expr)
3569 << 1 << OrderedLoopCountExpr->getSourceRange();
3570 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003571 return true;
3572 }
3573 assert(For->getBody());
3574
3575 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3576
3577 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003578 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003579 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003580 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003581
3582 bool HasErrors = false;
3583
3584 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003585 if (auto *LCDecl = ISC.GetLoopDecl()) {
3586 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003587
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003588 // OpenMP [2.6, Canonical Loop Form]
3589 // Var is one of the following:
3590 // A variable of signed or unsigned integer type.
3591 // For C++, a variable of a random access iterator type.
3592 // For C, a variable of a pointer type.
3593 auto VarType = LCDecl->getType().getNonReferenceType();
3594 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3595 !VarType->isPointerType() &&
3596 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3597 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3598 << SemaRef.getLangOpts().CPlusPlus;
3599 HasErrors = true;
3600 }
3601
3602 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3603 // a Construct
3604 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3605 // parallel for construct is (are) private.
3606 // The loop iteration variable in the associated for-loop of a simd
3607 // construct with just one associated for-loop is linear with a
3608 // constant-linear-step that is the increment of the associated for-loop.
3609 // Exclude loop var from the list of variables with implicitly defined data
3610 // sharing attributes.
3611 VarsWithImplicitDSA.erase(LCDecl);
3612
3613 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3614 // in a Construct, C/C++].
3615 // The loop iteration variable in the associated for-loop of a simd
3616 // construct with just one associated for-loop may be listed in a linear
3617 // clause with a constant-linear-step that is the increment of the
3618 // associated for-loop.
3619 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3620 // parallel for construct may be listed in a private or lastprivate clause.
3621 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3622 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3623 // declared in the loop and it is predetermined as a private.
3624 auto PredeterminedCKind =
3625 isOpenMPSimdDirective(DKind)
3626 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3627 : OMPC_private;
3628 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3629 DVar.CKind != PredeterminedCKind) ||
3630 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3631 isOpenMPDistributeDirective(DKind)) &&
3632 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3633 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3634 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3635 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3636 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3637 << getOpenMPClauseName(PredeterminedCKind);
3638 if (DVar.RefExpr == nullptr)
3639 DVar.CKind = PredeterminedCKind;
3640 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3641 HasErrors = true;
3642 } else if (LoopDeclRefExpr != nullptr) {
3643 // Make the loop iteration variable private (for worksharing constructs),
3644 // linear (for simd directives with the only one associated loop) or
3645 // lastprivate (for simd directives with several collapsed or ordered
3646 // loops).
3647 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003648 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3649 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003650 /*FromParent=*/false);
3651 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3652 }
3653
3654 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3655
3656 // Check test-expr.
3657 HasErrors |= ISC.CheckCond(For->getCond());
3658
3659 // Check incr-expr.
3660 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003661 }
3662
Alexander Musmana5f070a2014-10-01 06:03:56 +00003663 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003664 return HasErrors;
3665
Alexander Musmana5f070a2014-10-01 06:03:56 +00003666 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003667 ResultIterSpace.PreCond =
3668 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003669 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003670 DSA.getCurScope(),
3671 (isOpenMPWorksharingDirective(DKind) ||
3672 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3673 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003674 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003675 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003676 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3677 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3678 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3679 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3680 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3681 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3682
Alexey Bataev62dbb972015-04-22 11:59:37 +00003683 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3684 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003685 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003686 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003687 ResultIterSpace.CounterInit == nullptr ||
3688 ResultIterSpace.CounterStep == nullptr);
3689
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003690 return HasErrors;
3691}
3692
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003693/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003694static ExprResult
3695BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3696 ExprResult Start,
3697 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003698 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003699 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3700 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003701 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003702 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003703 VarRef.get()->getType())) {
3704 NewStart = SemaRef.PerformImplicitConversion(
3705 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3706 /*AllowExplicit=*/true);
3707 if (!NewStart.isUsable())
3708 return ExprError();
3709 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003710
3711 auto Init =
3712 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3713 return Init;
3714}
3715
Alexander Musmana5f070a2014-10-01 06:03:56 +00003716/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003717static ExprResult
3718BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3719 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3720 ExprResult Step, bool Subtract,
3721 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003722 // Add parentheses (for debugging purposes only).
3723 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3724 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3725 !Step.isUsable())
3726 return ExprError();
3727
Alexey Bataev5a3af132016-03-29 08:58:54 +00003728 ExprResult NewStep = Step;
3729 if (Captures)
3730 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003731 if (NewStep.isInvalid())
3732 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003733 ExprResult Update =
3734 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003735 if (!Update.isUsable())
3736 return ExprError();
3737
Alexey Bataevc0214e02016-02-16 12:13:49 +00003738 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3739 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003740 ExprResult NewStart = Start;
3741 if (Captures)
3742 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003743 if (NewStart.isInvalid())
3744 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003745
Alexey Bataevc0214e02016-02-16 12:13:49 +00003746 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3747 ExprResult SavedUpdate = Update;
3748 ExprResult UpdateVal;
3749 if (VarRef.get()->getType()->isOverloadableType() ||
3750 NewStart.get()->getType()->isOverloadableType() ||
3751 Update.get()->getType()->isOverloadableType()) {
3752 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3753 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3754 Update =
3755 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3756 if (Update.isUsable()) {
3757 UpdateVal =
3758 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3759 VarRef.get(), SavedUpdate.get());
3760 if (UpdateVal.isUsable()) {
3761 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3762 UpdateVal.get());
3763 }
3764 }
3765 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3766 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003767
Alexey Bataevc0214e02016-02-16 12:13:49 +00003768 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3769 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3770 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3771 NewStart.get(), SavedUpdate.get());
3772 if (!Update.isUsable())
3773 return ExprError();
3774
Alexey Bataev11481f52016-02-17 10:29:05 +00003775 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3776 VarRef.get()->getType())) {
3777 Update = SemaRef.PerformImplicitConversion(
3778 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3779 if (!Update.isUsable())
3780 return ExprError();
3781 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003782
3783 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3784 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003785 return Update;
3786}
3787
3788/// \brief Convert integer expression \a E to make it have at least \a Bits
3789/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003790static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791 if (E == nullptr)
3792 return ExprError();
3793 auto &C = SemaRef.Context;
3794 QualType OldType = E->getType();
3795 unsigned HasBits = C.getTypeSize(OldType);
3796 if (HasBits >= Bits)
3797 return ExprResult(E);
3798 // OK to convert to signed, because new type has more bits than old.
3799 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3800 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3801 true);
3802}
3803
3804/// \brief Check if the given expression \a E is a constant integer that fits
3805/// into \a Bits bits.
3806static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3807 if (E == nullptr)
3808 return false;
3809 llvm::APSInt Result;
3810 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3811 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3812 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003813}
3814
Alexey Bataev5a3af132016-03-29 08:58:54 +00003815/// Build preinits statement for the given declarations.
3816static Stmt *buildPreInits(ASTContext &Context,
3817 SmallVectorImpl<Decl *> &PreInits) {
3818 if (!PreInits.empty()) {
3819 return new (Context) DeclStmt(
3820 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3821 SourceLocation(), SourceLocation());
3822 }
3823 return nullptr;
3824}
3825
3826/// Build preinits statement for the given declarations.
3827static Stmt *buildPreInits(ASTContext &Context,
3828 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3829 if (!Captures.empty()) {
3830 SmallVector<Decl *, 16> PreInits;
3831 for (auto &Pair : Captures)
3832 PreInits.push_back(Pair.second->getDecl());
3833 return buildPreInits(Context, PreInits);
3834 }
3835 return nullptr;
3836}
3837
3838/// Build postupdate expression for the given list of postupdates expressions.
3839static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3840 Expr *PostUpdate = nullptr;
3841 if (!PostUpdates.empty()) {
3842 for (auto *E : PostUpdates) {
3843 Expr *ConvE = S.BuildCStyleCastExpr(
3844 E->getExprLoc(),
3845 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3846 E->getExprLoc(), E)
3847 .get();
3848 PostUpdate = PostUpdate
3849 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3850 PostUpdate, ConvE)
3851 .get()
3852 : ConvE;
3853 }
3854 }
3855 return PostUpdate;
3856}
3857
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003858/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003859/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3860/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003861static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003862CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3863 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3864 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003865 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003866 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003867 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003868 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003869 // Found 'collapse' clause - calculate collapse number.
3870 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003871 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003872 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003873 }
3874 if (OrderedLoopCountExpr) {
3875 // Found 'ordered' clause - calculate collapse number.
3876 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003877 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3878 if (Result.getLimitedValue() < NestedLoopCount) {
3879 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3880 diag::err_omp_wrong_ordered_loop_count)
3881 << OrderedLoopCountExpr->getSourceRange();
3882 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3883 diag::note_collapse_loop_count)
3884 << CollapseLoopCountExpr->getSourceRange();
3885 }
3886 NestedLoopCount = Result.getLimitedValue();
3887 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003888 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003889 // This is helper routine for loop directives (e.g., 'for', 'simd',
3890 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003891 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892 SmallVector<LoopIterationSpace, 4> IterSpaces;
3893 IterSpaces.resize(NestedLoopCount);
3894 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003895 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003896 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003897 NestedLoopCount, CollapseLoopCountExpr,
3898 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003899 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003900 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003901 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003902 // OpenMP [2.8.1, simd construct, Restrictions]
3903 // All loops associated with the construct must be perfectly nested; that
3904 // is, there must be no intervening code nor any OpenMP directive between
3905 // any two loops.
3906 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003907 }
3908
Alexander Musmana5f070a2014-10-01 06:03:56 +00003909 Built.clear(/* size */ NestedLoopCount);
3910
3911 if (SemaRef.CurContext->isDependentContext())
3912 return NestedLoopCount;
3913
3914 // An example of what is generated for the following code:
3915 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003916 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003917 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003918 // for (k = 0; k < NK; ++k)
3919 // for (j = J0; j < NJ; j+=2) {
3920 // <loop body>
3921 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003922 //
3923 // We generate the code below.
3924 // Note: the loop body may be outlined in CodeGen.
3925 // Note: some counters may be C++ classes, operator- is used to find number of
3926 // iterations and operator+= to calculate counter value.
3927 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3928 // or i64 is currently supported).
3929 //
3930 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3931 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3932 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3933 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3934 // // similar updates for vars in clauses (e.g. 'linear')
3935 // <loop body (using local i and j)>
3936 // }
3937 // i = NI; // assign final values of counters
3938 // j = NJ;
3939 //
3940
3941 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3942 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003943 // Precondition tests if there is at least one iteration (all conditions are
3944 // true).
3945 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003946 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003947 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003948 32 /* Bits */, SemaRef
3949 .PerformImplicitConversion(
3950 N0->IgnoreImpCasts(), N0->getType(),
3951 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003952 .get(),
3953 SemaRef);
3954 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003955 64 /* Bits */, SemaRef
3956 .PerformImplicitConversion(
3957 N0->IgnoreImpCasts(), N0->getType(),
3958 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003959 .get(),
3960 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003961
3962 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3963 return NestedLoopCount;
3964
3965 auto &C = SemaRef.Context;
3966 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3967
3968 Scope *CurScope = DSA.getCurScope();
3969 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003970 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003971 PreCond =
3972 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3973 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003974 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003975 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003976 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003977 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3978 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003979 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003980 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003981 SemaRef
3982 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3983 Sema::AA_Converting,
3984 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003985 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003986 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003987 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003988 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003989 SemaRef
3990 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3991 Sema::AA_Converting,
3992 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003993 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003994 }
3995
3996 // Choose either the 32-bit or 64-bit version.
3997 ExprResult LastIteration = LastIteration64;
3998 if (LastIteration32.isUsable() &&
3999 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4000 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4001 FitsInto(
4002 32 /* Bits */,
4003 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4004 LastIteration64.get(), SemaRef)))
4005 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004006 QualType VType = LastIteration.get()->getType();
4007 QualType RealVType = VType;
4008 QualType StrideVType = VType;
4009 if (isOpenMPTaskLoopDirective(DKind)) {
4010 VType =
4011 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4012 StrideVType =
4013 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4014 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004015
4016 if (!LastIteration.isUsable())
4017 return 0;
4018
4019 // Save the number of iterations.
4020 ExprResult NumIterations = LastIteration;
4021 {
4022 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004023 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4024 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004025 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4026 if (!LastIteration.isUsable())
4027 return 0;
4028 }
4029
4030 // Calculate the last iteration number beforehand instead of doing this on
4031 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4032 llvm::APSInt Result;
4033 bool IsConstant =
4034 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4035 ExprResult CalcLastIteration;
4036 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004037 ExprResult SaveRef =
4038 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004039 LastIteration = SaveRef;
4040
4041 // Prepare SaveRef + 1.
4042 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004043 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004044 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4045 if (!NumIterations.isUsable())
4046 return 0;
4047 }
4048
4049 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4050
David Majnemer9d168222016-08-05 17:44:54 +00004051 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00004052 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004053 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4054 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004055 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004056 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4057 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004058 SemaRef.AddInitializerToDecl(LBDecl,
4059 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4060 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004061
4062 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004063 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4064 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004065 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004066 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004067
4068 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4069 // This will be used to implement clause 'lastprivate'.
4070 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004071 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4072 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004073 SemaRef.AddInitializerToDecl(ILDecl,
4074 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4075 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004076
4077 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004078 VarDecl *STDecl =
4079 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4080 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004081 SemaRef.AddInitializerToDecl(STDecl,
4082 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4083 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004084
4085 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004086 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004087 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4088 UB.get(), LastIteration.get());
4089 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4090 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4091 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4092 CondOp.get());
4093 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004094
4095 // If we have a combined directive that combines 'distribute', 'for' or
4096 // 'simd' we need to be able to access the bounds of the schedule of the
4097 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4098 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4099 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4100 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4101
4102 // We expect to have at least 2 more parameters than the 'parallel'
4103 // directive does - the lower and upper bounds of the previous schedule.
4104 assert(CD->getNumParams() >= 4 &&
4105 "Unexpected number of parameters in loop combined directive");
4106
4107 // Set the proper type for the bounds given what we learned from the
4108 // enclosed loops.
4109 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4110 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4111
4112 // Previous lower and upper bounds are obtained from the region
4113 // parameters.
4114 PrevLB =
4115 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4116 PrevUB =
4117 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4118 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004119 }
4120
4121 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004122 ExprResult IV;
4123 ExprResult Init;
4124 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004125 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4126 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004127 Expr *RHS =
4128 (isOpenMPWorksharingDirective(DKind) ||
4129 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4130 ? LB.get()
4131 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004132 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4133 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004134 }
4135
Alexander Musmanc6388682014-12-15 07:07:06 +00004136 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004137 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004138 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004139 (isOpenMPWorksharingDirective(DKind) ||
4140 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004141 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4142 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4143 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004144
4145 // Loop increment (IV = IV + 1)
4146 SourceLocation IncLoc;
4147 ExprResult Inc =
4148 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4149 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4150 if (!Inc.isUsable())
4151 return 0;
4152 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004153 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4154 if (!Inc.isUsable())
4155 return 0;
4156
4157 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4158 // Used for directives with static scheduling.
4159 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004160 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4161 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004162 // LB + ST
4163 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4164 if (!NextLB.isUsable())
4165 return 0;
4166 // LB = LB + ST
4167 NextLB =
4168 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4169 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4170 if (!NextLB.isUsable())
4171 return 0;
4172 // UB + ST
4173 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4174 if (!NextUB.isUsable())
4175 return 0;
4176 // UB = UB + ST
4177 NextUB =
4178 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4179 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4180 if (!NextUB.isUsable())
4181 return 0;
4182 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183
4184 // Build updates and final values of the loop counters.
4185 bool HasErrors = false;
4186 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004187 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004188 Built.Updates.resize(NestedLoopCount);
4189 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004190 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004191 {
4192 ExprResult Div;
4193 // Go from inner nested loop to outer.
4194 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4195 LoopIterationSpace &IS = IterSpaces[Cnt];
4196 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4197 // Build: Iter = (IV / Div) % IS.NumIters
4198 // where Div is product of previous iterations' IS.NumIters.
4199 ExprResult Iter;
4200 if (Div.isUsable()) {
4201 Iter =
4202 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4203 } else {
4204 Iter = IV;
4205 assert((Cnt == (int)NestedLoopCount - 1) &&
4206 "unusable div expected on first iteration only");
4207 }
4208
4209 if (Cnt != 0 && Iter.isUsable())
4210 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4211 IS.NumIterations);
4212 if (!Iter.isUsable()) {
4213 HasErrors = true;
4214 break;
4215 }
4216
Alexey Bataev39f915b82015-05-08 10:41:21 +00004217 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004218 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4219 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4220 IS.CounterVar->getExprLoc(),
4221 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004222 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004223 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004224 if (!Init.isUsable()) {
4225 HasErrors = true;
4226 break;
4227 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004228 ExprResult Update = BuildCounterUpdate(
4229 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4230 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004231 if (!Update.isUsable()) {
4232 HasErrors = true;
4233 break;
4234 }
4235
4236 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4237 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004238 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004239 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004240 if (!Final.isUsable()) {
4241 HasErrors = true;
4242 break;
4243 }
4244
4245 // Build Div for the next iteration: Div <- Div * IS.NumIters
4246 if (Cnt != 0) {
4247 if (Div.isUnset())
4248 Div = IS.NumIterations;
4249 else
4250 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4251 IS.NumIterations);
4252
4253 // Add parentheses (for debugging purposes only).
4254 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004255 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004256 if (!Div.isUsable()) {
4257 HasErrors = true;
4258 break;
4259 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004260 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004261 }
4262 if (!Update.isUsable() || !Final.isUsable()) {
4263 HasErrors = true;
4264 break;
4265 }
4266 // Save results
4267 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004268 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004269 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004270 Built.Updates[Cnt] = Update.get();
4271 Built.Finals[Cnt] = Final.get();
4272 }
4273 }
4274
4275 if (HasErrors)
4276 return 0;
4277
4278 // Save results
4279 Built.IterationVarRef = IV.get();
4280 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004281 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004282 Built.CalcLastIteration =
4283 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004284 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004285 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004286 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004287 Built.Init = Init.get();
4288 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004289 Built.LB = LB.get();
4290 Built.UB = UB.get();
4291 Built.IL = IL.get();
4292 Built.ST = ST.get();
4293 Built.EUB = EUB.get();
4294 Built.NLB = NextLB.get();
4295 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004296 Built.PrevLB = PrevLB.get();
4297 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004298
Alexey Bataev8b427062016-05-25 12:36:08 +00004299 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4300 // Fill data for doacross depend clauses.
4301 for (auto Pair : DSA.getDoacrossDependClauses()) {
4302 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4303 Pair.first->setCounterValue(CounterVal);
4304 else {
4305 if (NestedLoopCount != Pair.second.size() ||
4306 NestedLoopCount != LoopMultipliers.size() + 1) {
4307 // Erroneous case - clause has some problems.
4308 Pair.first->setCounterValue(CounterVal);
4309 continue;
4310 }
4311 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4312 auto I = Pair.second.rbegin();
4313 auto IS = IterSpaces.rbegin();
4314 auto ILM = LoopMultipliers.rbegin();
4315 Expr *UpCounterVal = CounterVal;
4316 Expr *Multiplier = nullptr;
4317 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4318 if (I->first) {
4319 assert(IS->CounterStep);
4320 Expr *NormalizedOffset =
4321 SemaRef
4322 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4323 I->first, IS->CounterStep)
4324 .get();
4325 if (Multiplier) {
4326 NormalizedOffset =
4327 SemaRef
4328 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4329 NormalizedOffset, Multiplier)
4330 .get();
4331 }
4332 assert(I->second == OO_Plus || I->second == OO_Minus);
4333 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004334 UpCounterVal = SemaRef
4335 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4336 UpCounterVal, NormalizedOffset)
4337 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004338 }
4339 Multiplier = *ILM;
4340 ++I;
4341 ++IS;
4342 ++ILM;
4343 }
4344 Pair.first->setCounterValue(UpCounterVal);
4345 }
4346 }
4347
Alexey Bataevabfc0692014-06-25 06:52:00 +00004348 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004349}
4350
Alexey Bataev10e775f2015-07-30 11:36:16 +00004351static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004352 auto CollapseClauses =
4353 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4354 if (CollapseClauses.begin() != CollapseClauses.end())
4355 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004356 return nullptr;
4357}
4358
Alexey Bataev10e775f2015-07-30 11:36:16 +00004359static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004360 auto OrderedClauses =
4361 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4362 if (OrderedClauses.begin() != OrderedClauses.end())
4363 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004364 return nullptr;
4365}
4366
Kelvin Lic5609492016-07-15 04:39:07 +00004367static bool checkSimdlenSafelenSpecified(Sema &S,
4368 const ArrayRef<OMPClause *> Clauses) {
4369 OMPSafelenClause *Safelen = nullptr;
4370 OMPSimdlenClause *Simdlen = nullptr;
4371
4372 for (auto *Clause : Clauses) {
4373 if (Clause->getClauseKind() == OMPC_safelen)
4374 Safelen = cast<OMPSafelenClause>(Clause);
4375 else if (Clause->getClauseKind() == OMPC_simdlen)
4376 Simdlen = cast<OMPSimdlenClause>(Clause);
4377 if (Safelen && Simdlen)
4378 break;
4379 }
4380
4381 if (Simdlen && Safelen) {
4382 llvm::APSInt SimdlenRes, SafelenRes;
4383 auto SimdlenLength = Simdlen->getSimdlen();
4384 auto SafelenLength = Safelen->getSafelen();
4385 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4386 SimdlenLength->isInstantiationDependent() ||
4387 SimdlenLength->containsUnexpandedParameterPack())
4388 return false;
4389 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4390 SafelenLength->isInstantiationDependent() ||
4391 SafelenLength->containsUnexpandedParameterPack())
4392 return false;
4393 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4394 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4395 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4396 // If both simdlen and safelen clauses are specified, the value of the
4397 // simdlen parameter must be less than or equal to the value of the safelen
4398 // parameter.
4399 if (SimdlenRes > SafelenRes) {
4400 S.Diag(SimdlenLength->getExprLoc(),
4401 diag::err_omp_wrong_simdlen_safelen_values)
4402 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4403 return true;
4404 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004405 }
4406 return false;
4407}
4408
Alexey Bataev4acb8592014-07-07 13:01:15 +00004409StmtResult Sema::ActOnOpenMPSimdDirective(
4410 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4411 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004412 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004413 if (!AStmt)
4414 return StmtError();
4415
4416 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004417 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004418 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4419 // define the nested loops number.
4420 unsigned NestedLoopCount = CheckOpenMPLoop(
4421 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4422 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004423 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004424 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004425
Alexander Musmana5f070a2014-10-01 06:03:56 +00004426 assert((CurContext->isDependentContext() || B.builtAll()) &&
4427 "omp simd loop exprs were not built");
4428
Alexander Musman3276a272015-03-21 10:12:56 +00004429 if (!CurContext->isDependentContext()) {
4430 // Finalize the clauses that need pre-built expressions for CodeGen.
4431 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004432 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004433 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004434 B.NumIterations, *this, CurScope,
4435 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004436 return StmtError();
4437 }
4438 }
4439
Kelvin Lic5609492016-07-15 04:39:07 +00004440 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004441 return StmtError();
4442
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004443 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004444 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4445 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004446}
4447
Alexey Bataev4acb8592014-07-07 13:01:15 +00004448StmtResult Sema::ActOnOpenMPForDirective(
4449 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4450 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004451 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004452 if (!AStmt)
4453 return StmtError();
4454
4455 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004456 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004457 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4458 // define the nested loops number.
4459 unsigned NestedLoopCount = CheckOpenMPLoop(
4460 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4461 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004462 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004463 return StmtError();
4464
Alexander Musmana5f070a2014-10-01 06:03:56 +00004465 assert((CurContext->isDependentContext() || B.builtAll()) &&
4466 "omp for loop exprs were not built");
4467
Alexey Bataev54acd402015-08-04 11:18:19 +00004468 if (!CurContext->isDependentContext()) {
4469 // Finalize the clauses that need pre-built expressions for CodeGen.
4470 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004471 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004472 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004473 B.NumIterations, *this, CurScope,
4474 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004475 return StmtError();
4476 }
4477 }
4478
Alexey Bataevf29276e2014-06-18 04:14:57 +00004479 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004480 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004481 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004482}
4483
Alexander Musmanf82886e2014-09-18 05:12:34 +00004484StmtResult Sema::ActOnOpenMPForSimdDirective(
4485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4486 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004487 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004488 if (!AStmt)
4489 return StmtError();
4490
4491 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004492 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004493 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4494 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004495 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004496 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4497 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4498 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004499 if (NestedLoopCount == 0)
4500 return StmtError();
4501
Alexander Musmanc6388682014-12-15 07:07:06 +00004502 assert((CurContext->isDependentContext() || B.builtAll()) &&
4503 "omp for simd loop exprs were not built");
4504
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004505 if (!CurContext->isDependentContext()) {
4506 // Finalize the clauses that need pre-built expressions for CodeGen.
4507 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004508 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004509 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004510 B.NumIterations, *this, CurScope,
4511 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004512 return StmtError();
4513 }
4514 }
4515
Kelvin Lic5609492016-07-15 04:39:07 +00004516 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004517 return StmtError();
4518
Alexander Musmanf82886e2014-09-18 05:12:34 +00004519 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004520 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4521 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004522}
4523
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004524StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4525 Stmt *AStmt,
4526 SourceLocation StartLoc,
4527 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004528 if (!AStmt)
4529 return StmtError();
4530
4531 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004532 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004533 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004534 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004535 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004536 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004537 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004538 return StmtError();
4539 // All associated statements must be '#pragma omp section' except for
4540 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004541 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004542 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4543 if (SectionStmt)
4544 Diag(SectionStmt->getLocStart(),
4545 diag::err_omp_sections_substmt_not_section);
4546 return StmtError();
4547 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004548 cast<OMPSectionDirective>(SectionStmt)
4549 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004550 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004551 } else {
4552 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4553 return StmtError();
4554 }
4555
4556 getCurFunction()->setHasBranchProtectedScope();
4557
Alexey Bataev25e5b442015-09-15 12:52:43 +00004558 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4559 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004560}
4561
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004562StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4563 SourceLocation StartLoc,
4564 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004565 if (!AStmt)
4566 return StmtError();
4567
4568 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004569
4570 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004571 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004572
Alexey Bataev25e5b442015-09-15 12:52:43 +00004573 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4574 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004575}
4576
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004577StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4578 Stmt *AStmt,
4579 SourceLocation StartLoc,
4580 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004581 if (!AStmt)
4582 return StmtError();
4583
4584 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004585
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004586 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004587
Alexey Bataev3255bf32015-01-19 05:20:46 +00004588 // OpenMP [2.7.3, single Construct, Restrictions]
4589 // The copyprivate clause must not be used with the nowait clause.
4590 OMPClause *Nowait = nullptr;
4591 OMPClause *Copyprivate = nullptr;
4592 for (auto *Clause : Clauses) {
4593 if (Clause->getClauseKind() == OMPC_nowait)
4594 Nowait = Clause;
4595 else if (Clause->getClauseKind() == OMPC_copyprivate)
4596 Copyprivate = Clause;
4597 if (Copyprivate && Nowait) {
4598 Diag(Copyprivate->getLocStart(),
4599 diag::err_omp_single_copyprivate_with_nowait);
4600 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4601 return StmtError();
4602 }
4603 }
4604
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004605 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4606}
4607
Alexander Musman80c22892014-07-17 08:54:58 +00004608StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4609 SourceLocation StartLoc,
4610 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004611 if (!AStmt)
4612 return StmtError();
4613
4614 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004615
4616 getCurFunction()->setHasBranchProtectedScope();
4617
4618 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4619}
4620
Alexey Bataev28c75412015-12-15 08:19:24 +00004621StmtResult Sema::ActOnOpenMPCriticalDirective(
4622 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4623 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004624 if (!AStmt)
4625 return StmtError();
4626
4627 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004628
Alexey Bataev28c75412015-12-15 08:19:24 +00004629 bool ErrorFound = false;
4630 llvm::APSInt Hint;
4631 SourceLocation HintLoc;
4632 bool DependentHint = false;
4633 for (auto *C : Clauses) {
4634 if (C->getClauseKind() == OMPC_hint) {
4635 if (!DirName.getName()) {
4636 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4637 ErrorFound = true;
4638 }
4639 Expr *E = cast<OMPHintClause>(C)->getHint();
4640 if (E->isTypeDependent() || E->isValueDependent() ||
4641 E->isInstantiationDependent())
4642 DependentHint = true;
4643 else {
4644 Hint = E->EvaluateKnownConstInt(Context);
4645 HintLoc = C->getLocStart();
4646 }
4647 }
4648 }
4649 if (ErrorFound)
4650 return StmtError();
4651 auto Pair = DSAStack->getCriticalWithHint(DirName);
4652 if (Pair.first && DirName.getName() && !DependentHint) {
4653 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4654 Diag(StartLoc, diag::err_omp_critical_with_hint);
4655 if (HintLoc.isValid()) {
4656 Diag(HintLoc, diag::note_omp_critical_hint_here)
4657 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4658 } else
4659 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4660 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4661 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4662 << 1
4663 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4664 /*Radix=*/10, /*Signed=*/false);
4665 } else
4666 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4667 }
4668 }
4669
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004670 getCurFunction()->setHasBranchProtectedScope();
4671
Alexey Bataev28c75412015-12-15 08:19:24 +00004672 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4673 Clauses, AStmt);
4674 if (!Pair.first && DirName.getName() && !DependentHint)
4675 DSAStack->addCriticalWithHint(Dir, Hint);
4676 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004677}
4678
Alexey Bataev4acb8592014-07-07 13:01:15 +00004679StmtResult Sema::ActOnOpenMPParallelForDirective(
4680 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4681 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004682 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004683 if (!AStmt)
4684 return StmtError();
4685
Alexey Bataev4acb8592014-07-07 13:01:15 +00004686 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4687 // 1.2.2 OpenMP Language Terminology
4688 // Structured block - An executable statement with a single entry at the
4689 // top and a single exit at the bottom.
4690 // The point of exit cannot be a branch out of the structured block.
4691 // longjmp() and throw() must not violate the entry/exit criteria.
4692 CS->getCapturedDecl()->setNothrow();
4693
Alexander Musmanc6388682014-12-15 07:07:06 +00004694 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004695 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4696 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004697 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004698 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4699 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4700 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004701 if (NestedLoopCount == 0)
4702 return StmtError();
4703
Alexander Musmana5f070a2014-10-01 06:03:56 +00004704 assert((CurContext->isDependentContext() || B.builtAll()) &&
4705 "omp parallel for loop exprs were not built");
4706
Alexey Bataev54acd402015-08-04 11:18:19 +00004707 if (!CurContext->isDependentContext()) {
4708 // Finalize the clauses that need pre-built expressions for CodeGen.
4709 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004710 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004711 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004712 B.NumIterations, *this, CurScope,
4713 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004714 return StmtError();
4715 }
4716 }
4717
Alexey Bataev4acb8592014-07-07 13:01:15 +00004718 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004719 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004720 NestedLoopCount, Clauses, AStmt, B,
4721 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004722}
4723
Alexander Musmane4e893b2014-09-23 09:33:00 +00004724StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4725 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4726 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004727 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004728 if (!AStmt)
4729 return StmtError();
4730
Alexander Musmane4e893b2014-09-23 09:33:00 +00004731 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4732 // 1.2.2 OpenMP Language Terminology
4733 // Structured block - An executable statement with a single entry at the
4734 // top and a single exit at the bottom.
4735 // The point of exit cannot be a branch out of the structured block.
4736 // longjmp() and throw() must not violate the entry/exit criteria.
4737 CS->getCapturedDecl()->setNothrow();
4738
Alexander Musmanc6388682014-12-15 07:07:06 +00004739 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004740 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4741 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004742 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004743 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4744 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4745 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004746 if (NestedLoopCount == 0)
4747 return StmtError();
4748
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004749 if (!CurContext->isDependentContext()) {
4750 // Finalize the clauses that need pre-built expressions for CodeGen.
4751 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004752 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004753 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004754 B.NumIterations, *this, CurScope,
4755 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004756 return StmtError();
4757 }
4758 }
4759
Kelvin Lic5609492016-07-15 04:39:07 +00004760 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004761 return StmtError();
4762
Alexander Musmane4e893b2014-09-23 09:33:00 +00004763 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004764 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004765 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004766}
4767
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004768StmtResult
4769Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4770 Stmt *AStmt, SourceLocation StartLoc,
4771 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004772 if (!AStmt)
4773 return StmtError();
4774
4775 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004776 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004777 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004778 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004779 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004780 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004781 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004782 return StmtError();
4783 // All associated statements must be '#pragma omp section' except for
4784 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004785 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004786 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4787 if (SectionStmt)
4788 Diag(SectionStmt->getLocStart(),
4789 diag::err_omp_parallel_sections_substmt_not_section);
4790 return StmtError();
4791 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004792 cast<OMPSectionDirective>(SectionStmt)
4793 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004794 }
4795 } else {
4796 Diag(AStmt->getLocStart(),
4797 diag::err_omp_parallel_sections_not_compound_stmt);
4798 return StmtError();
4799 }
4800
4801 getCurFunction()->setHasBranchProtectedScope();
4802
Alexey Bataev25e5b442015-09-15 12:52:43 +00004803 return OMPParallelSectionsDirective::Create(
4804 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004805}
4806
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004807StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4808 Stmt *AStmt, SourceLocation StartLoc,
4809 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004810 if (!AStmt)
4811 return StmtError();
4812
David Majnemer9d168222016-08-05 17:44:54 +00004813 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004814 // 1.2.2 OpenMP Language Terminology
4815 // Structured block - An executable statement with a single entry at the
4816 // top and a single exit at the bottom.
4817 // The point of exit cannot be a branch out of the structured block.
4818 // longjmp() and throw() must not violate the entry/exit criteria.
4819 CS->getCapturedDecl()->setNothrow();
4820
4821 getCurFunction()->setHasBranchProtectedScope();
4822
Alexey Bataev25e5b442015-09-15 12:52:43 +00004823 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4824 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004825}
4826
Alexey Bataev68446b72014-07-18 07:47:19 +00004827StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4828 SourceLocation EndLoc) {
4829 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4830}
4831
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004832StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4833 SourceLocation EndLoc) {
4834 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4835}
4836
Alexey Bataev2df347a2014-07-18 10:17:07 +00004837StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4838 SourceLocation EndLoc) {
4839 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4840}
4841
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004842StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4843 SourceLocation StartLoc,
4844 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004845 if (!AStmt)
4846 return StmtError();
4847
4848 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004849
4850 getCurFunction()->setHasBranchProtectedScope();
4851
4852 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4853}
4854
Alexey Bataev6125da92014-07-21 11:26:11 +00004855StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4856 SourceLocation StartLoc,
4857 SourceLocation EndLoc) {
4858 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4859 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4860}
4861
Alexey Bataev346265e2015-09-25 10:37:12 +00004862StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4863 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004864 SourceLocation StartLoc,
4865 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004866 OMPClause *DependFound = nullptr;
4867 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004868 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004869 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004870 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004871 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004872 for (auto *C : Clauses) {
4873 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4874 DependFound = C;
4875 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4876 if (DependSourceClause) {
4877 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4878 << getOpenMPDirectiveName(OMPD_ordered)
4879 << getOpenMPClauseName(OMPC_depend) << 2;
4880 ErrorFound = true;
4881 } else
4882 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004883 if (DependSinkClause) {
4884 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4885 << 0;
4886 ErrorFound = true;
4887 }
4888 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4889 if (DependSourceClause) {
4890 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4891 << 1;
4892 ErrorFound = true;
4893 }
4894 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004895 }
4896 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004897 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004898 else if (C->getClauseKind() == OMPC_simd)
4899 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004900 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004901 if (!ErrorFound && !SC &&
4902 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004903 // OpenMP [2.8.1,simd Construct, Restrictions]
4904 // An ordered construct with the simd clause is the only OpenMP construct
4905 // that can appear in the simd region.
4906 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004907 ErrorFound = true;
4908 } else if (DependFound && (TC || SC)) {
4909 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4910 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4911 ErrorFound = true;
4912 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4913 Diag(DependFound->getLocStart(),
4914 diag::err_omp_ordered_directive_without_param);
4915 ErrorFound = true;
4916 } else if (TC || Clauses.empty()) {
4917 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4918 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4919 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4920 << (TC != nullptr);
4921 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4922 ErrorFound = true;
4923 }
4924 }
4925 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004926 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004927
4928 if (AStmt) {
4929 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4930
4931 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004932 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004933
4934 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004935}
4936
Alexey Bataev1d160b12015-03-13 12:27:31 +00004937namespace {
4938/// \brief Helper class for checking expression in 'omp atomic [update]'
4939/// construct.
4940class OpenMPAtomicUpdateChecker {
4941 /// \brief Error results for atomic update expressions.
4942 enum ExprAnalysisErrorCode {
4943 /// \brief A statement is not an expression statement.
4944 NotAnExpression,
4945 /// \brief Expression is not builtin binary or unary operation.
4946 NotABinaryOrUnaryExpression,
4947 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4948 NotAnUnaryIncDecExpression,
4949 /// \brief An expression is not of scalar type.
4950 NotAScalarType,
4951 /// \brief A binary operation is not an assignment operation.
4952 NotAnAssignmentOp,
4953 /// \brief RHS part of the binary operation is not a binary expression.
4954 NotABinaryExpression,
4955 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4956 /// expression.
4957 NotABinaryOperator,
4958 /// \brief RHS binary operation does not have reference to the updated LHS
4959 /// part.
4960 NotAnUpdateExpression,
4961 /// \brief No errors is found.
4962 NoError
4963 };
4964 /// \brief Reference to Sema.
4965 Sema &SemaRef;
4966 /// \brief A location for note diagnostics (when error is found).
4967 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004968 /// \brief 'x' lvalue part of the source atomic expression.
4969 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004970 /// \brief 'expr' rvalue part of the source atomic expression.
4971 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004972 /// \brief Helper expression of the form
4973 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4974 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4975 Expr *UpdateExpr;
4976 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4977 /// important for non-associative operations.
4978 bool IsXLHSInRHSPart;
4979 BinaryOperatorKind Op;
4980 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004981 /// \brief true if the source expression is a postfix unary operation, false
4982 /// if it is a prefix unary operation.
4983 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004984
4985public:
4986 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004987 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004988 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004989 /// \brief Check specified statement that it is suitable for 'atomic update'
4990 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004991 /// expression. If DiagId and NoteId == 0, then only check is performed
4992 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004993 /// \param DiagId Diagnostic which should be emitted if error is found.
4994 /// \param NoteId Diagnostic note for the main error message.
4995 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004996 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004997 /// \brief Return the 'x' lvalue part of the source atomic expression.
4998 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004999 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5000 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005001 /// \brief Return the update expression used in calculation of the updated
5002 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5003 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5004 Expr *getUpdateExpr() const { return UpdateExpr; }
5005 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5006 /// false otherwise.
5007 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5008
Alexey Bataevb78ca832015-04-01 03:33:17 +00005009 /// \brief true if the source expression is a postfix unary operation, false
5010 /// if it is a prefix unary operation.
5011 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5012
Alexey Bataev1d160b12015-03-13 12:27:31 +00005013private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005014 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5015 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005016};
5017} // namespace
5018
5019bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5020 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5021 ExprAnalysisErrorCode ErrorFound = NoError;
5022 SourceLocation ErrorLoc, NoteLoc;
5023 SourceRange ErrorRange, NoteRange;
5024 // Allowed constructs are:
5025 // x = x binop expr;
5026 // x = expr binop x;
5027 if (AtomicBinOp->getOpcode() == BO_Assign) {
5028 X = AtomicBinOp->getLHS();
5029 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5030 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5031 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5032 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5033 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005034 Op = AtomicInnerBinOp->getOpcode();
5035 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005036 auto *LHS = AtomicInnerBinOp->getLHS();
5037 auto *RHS = AtomicInnerBinOp->getRHS();
5038 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5039 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5040 /*Canonical=*/true);
5041 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5042 /*Canonical=*/true);
5043 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5044 /*Canonical=*/true);
5045 if (XId == LHSId) {
5046 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005047 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005048 } else if (XId == RHSId) {
5049 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005050 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005051 } else {
5052 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5053 ErrorRange = AtomicInnerBinOp->getSourceRange();
5054 NoteLoc = X->getExprLoc();
5055 NoteRange = X->getSourceRange();
5056 ErrorFound = NotAnUpdateExpression;
5057 }
5058 } else {
5059 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5060 ErrorRange = AtomicInnerBinOp->getSourceRange();
5061 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5062 NoteRange = SourceRange(NoteLoc, NoteLoc);
5063 ErrorFound = NotABinaryOperator;
5064 }
5065 } else {
5066 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5067 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5068 ErrorFound = NotABinaryExpression;
5069 }
5070 } else {
5071 ErrorLoc = AtomicBinOp->getExprLoc();
5072 ErrorRange = AtomicBinOp->getSourceRange();
5073 NoteLoc = AtomicBinOp->getOperatorLoc();
5074 NoteRange = SourceRange(NoteLoc, NoteLoc);
5075 ErrorFound = NotAnAssignmentOp;
5076 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005077 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005078 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5079 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5080 return true;
5081 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005082 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005083 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005084}
5085
5086bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5087 unsigned NoteId) {
5088 ExprAnalysisErrorCode ErrorFound = NoError;
5089 SourceLocation ErrorLoc, NoteLoc;
5090 SourceRange ErrorRange, NoteRange;
5091 // Allowed constructs are:
5092 // x++;
5093 // x--;
5094 // ++x;
5095 // --x;
5096 // x binop= expr;
5097 // x = x binop expr;
5098 // x = expr binop x;
5099 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5100 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5101 if (AtomicBody->getType()->isScalarType() ||
5102 AtomicBody->isInstantiationDependent()) {
5103 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5104 AtomicBody->IgnoreParenImpCasts())) {
5105 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005106 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005107 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005108 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005109 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005110 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005111 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005112 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5113 AtomicBody->IgnoreParenImpCasts())) {
5114 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005115 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005116 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005117 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5118 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005119 // Check for Unary Operation
5120 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005121 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005122 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5123 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005124 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005125 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5126 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005127 } else {
5128 ErrorFound = NotAnUnaryIncDecExpression;
5129 ErrorLoc = AtomicUnaryOp->getExprLoc();
5130 ErrorRange = AtomicUnaryOp->getSourceRange();
5131 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5132 NoteRange = SourceRange(NoteLoc, NoteLoc);
5133 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005134 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005135 ErrorFound = NotABinaryOrUnaryExpression;
5136 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5137 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5138 }
5139 } else {
5140 ErrorFound = NotAScalarType;
5141 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5142 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5143 }
5144 } else {
5145 ErrorFound = NotAnExpression;
5146 NoteLoc = ErrorLoc = S->getLocStart();
5147 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5148 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005149 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005150 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5151 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5152 return true;
5153 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005154 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005155 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005156 // Build an update expression of form 'OpaqueValueExpr(x) binop
5157 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5158 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5159 auto *OVEX = new (SemaRef.getASTContext())
5160 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5161 auto *OVEExpr = new (SemaRef.getASTContext())
5162 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5163 auto Update =
5164 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5165 IsXLHSInRHSPart ? OVEExpr : OVEX);
5166 if (Update.isInvalid())
5167 return true;
5168 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5169 Sema::AA_Casting);
5170 if (Update.isInvalid())
5171 return true;
5172 UpdateExpr = Update.get();
5173 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005174 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005175}
5176
Alexey Bataev0162e452014-07-22 10:10:35 +00005177StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5178 Stmt *AStmt,
5179 SourceLocation StartLoc,
5180 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005181 if (!AStmt)
5182 return StmtError();
5183
David Majnemer9d168222016-08-05 17:44:54 +00005184 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005185 // 1.2.2 OpenMP Language Terminology
5186 // Structured block - An executable statement with a single entry at the
5187 // top and a single exit at the bottom.
5188 // The point of exit cannot be a branch out of the structured block.
5189 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005190 OpenMPClauseKind AtomicKind = OMPC_unknown;
5191 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005192 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005193 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005194 C->getClauseKind() == OMPC_update ||
5195 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005196 if (AtomicKind != OMPC_unknown) {
5197 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5198 << SourceRange(C->getLocStart(), C->getLocEnd());
5199 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5200 << getOpenMPClauseName(AtomicKind);
5201 } else {
5202 AtomicKind = C->getClauseKind();
5203 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005204 }
5205 }
5206 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005207
Alexey Bataev459dec02014-07-24 06:46:57 +00005208 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005209 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5210 Body = EWC->getSubExpr();
5211
Alexey Bataev62cec442014-11-18 10:14:22 +00005212 Expr *X = nullptr;
5213 Expr *V = nullptr;
5214 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005215 Expr *UE = nullptr;
5216 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005217 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005218 // OpenMP [2.12.6, atomic Construct]
5219 // In the next expressions:
5220 // * x and v (as applicable) are both l-value expressions with scalar type.
5221 // * During the execution of an atomic region, multiple syntactic
5222 // occurrences of x must designate the same storage location.
5223 // * Neither of v and expr (as applicable) may access the storage location
5224 // designated by x.
5225 // * Neither of x and expr (as applicable) may access the storage location
5226 // designated by v.
5227 // * expr is an expression with scalar type.
5228 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5229 // * binop, binop=, ++, and -- are not overloaded operators.
5230 // * The expression x binop expr must be numerically equivalent to x binop
5231 // (expr). This requirement is satisfied if the operators in expr have
5232 // precedence greater than binop, or by using parentheses around expr or
5233 // subexpressions of expr.
5234 // * The expression expr binop x must be numerically equivalent to (expr)
5235 // binop x. This requirement is satisfied if the operators in expr have
5236 // precedence equal to or greater than binop, or by using parentheses around
5237 // expr or subexpressions of expr.
5238 // * For forms that allow multiple occurrences of x, the number of times
5239 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005240 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005241 enum {
5242 NotAnExpression,
5243 NotAnAssignmentOp,
5244 NotAScalarType,
5245 NotAnLValue,
5246 NoError
5247 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005248 SourceLocation ErrorLoc, NoteLoc;
5249 SourceRange ErrorRange, NoteRange;
5250 // If clause is read:
5251 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005252 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5253 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005254 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5255 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5256 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5257 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5258 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5259 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5260 if (!X->isLValue() || !V->isLValue()) {
5261 auto NotLValueExpr = X->isLValue() ? V : X;
5262 ErrorFound = NotAnLValue;
5263 ErrorLoc = AtomicBinOp->getExprLoc();
5264 ErrorRange = AtomicBinOp->getSourceRange();
5265 NoteLoc = NotLValueExpr->getExprLoc();
5266 NoteRange = NotLValueExpr->getSourceRange();
5267 }
5268 } else if (!X->isInstantiationDependent() ||
5269 !V->isInstantiationDependent()) {
5270 auto NotScalarExpr =
5271 (X->isInstantiationDependent() || X->getType()->isScalarType())
5272 ? V
5273 : X;
5274 ErrorFound = NotAScalarType;
5275 ErrorLoc = AtomicBinOp->getExprLoc();
5276 ErrorRange = AtomicBinOp->getSourceRange();
5277 NoteLoc = NotScalarExpr->getExprLoc();
5278 NoteRange = NotScalarExpr->getSourceRange();
5279 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005280 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005281 ErrorFound = NotAnAssignmentOp;
5282 ErrorLoc = AtomicBody->getExprLoc();
5283 ErrorRange = AtomicBody->getSourceRange();
5284 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5285 : AtomicBody->getExprLoc();
5286 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5287 : AtomicBody->getSourceRange();
5288 }
5289 } else {
5290 ErrorFound = NotAnExpression;
5291 NoteLoc = ErrorLoc = Body->getLocStart();
5292 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005293 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005294 if (ErrorFound != NoError) {
5295 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5296 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005297 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5298 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005299 return StmtError();
5300 } else if (CurContext->isDependentContext())
5301 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005302 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005303 enum {
5304 NotAnExpression,
5305 NotAnAssignmentOp,
5306 NotAScalarType,
5307 NotAnLValue,
5308 NoError
5309 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005310 SourceLocation ErrorLoc, NoteLoc;
5311 SourceRange ErrorRange, NoteRange;
5312 // If clause is write:
5313 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005314 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5315 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005316 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5317 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005318 X = AtomicBinOp->getLHS();
5319 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005320 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5321 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5322 if (!X->isLValue()) {
5323 ErrorFound = NotAnLValue;
5324 ErrorLoc = AtomicBinOp->getExprLoc();
5325 ErrorRange = AtomicBinOp->getSourceRange();
5326 NoteLoc = X->getExprLoc();
5327 NoteRange = X->getSourceRange();
5328 }
5329 } else if (!X->isInstantiationDependent() ||
5330 !E->isInstantiationDependent()) {
5331 auto NotScalarExpr =
5332 (X->isInstantiationDependent() || X->getType()->isScalarType())
5333 ? E
5334 : X;
5335 ErrorFound = NotAScalarType;
5336 ErrorLoc = AtomicBinOp->getExprLoc();
5337 ErrorRange = AtomicBinOp->getSourceRange();
5338 NoteLoc = NotScalarExpr->getExprLoc();
5339 NoteRange = NotScalarExpr->getSourceRange();
5340 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005341 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005342 ErrorFound = NotAnAssignmentOp;
5343 ErrorLoc = AtomicBody->getExprLoc();
5344 ErrorRange = AtomicBody->getSourceRange();
5345 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5346 : AtomicBody->getExprLoc();
5347 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5348 : AtomicBody->getSourceRange();
5349 }
5350 } else {
5351 ErrorFound = NotAnExpression;
5352 NoteLoc = ErrorLoc = Body->getLocStart();
5353 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005354 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005355 if (ErrorFound != NoError) {
5356 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5357 << ErrorRange;
5358 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5359 << NoteRange;
5360 return StmtError();
5361 } else if (CurContext->isDependentContext())
5362 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005363 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005364 // If clause is update:
5365 // x++;
5366 // x--;
5367 // ++x;
5368 // --x;
5369 // x binop= expr;
5370 // x = x binop expr;
5371 // x = expr binop x;
5372 OpenMPAtomicUpdateChecker Checker(*this);
5373 if (Checker.checkStatement(
5374 Body, (AtomicKind == OMPC_update)
5375 ? diag::err_omp_atomic_update_not_expression_statement
5376 : diag::err_omp_atomic_not_expression_statement,
5377 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005378 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005379 if (!CurContext->isDependentContext()) {
5380 E = Checker.getExpr();
5381 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005382 UE = Checker.getUpdateExpr();
5383 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005384 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005385 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005386 enum {
5387 NotAnAssignmentOp,
5388 NotACompoundStatement,
5389 NotTwoSubstatements,
5390 NotASpecificExpression,
5391 NoError
5392 } ErrorFound = NoError;
5393 SourceLocation ErrorLoc, NoteLoc;
5394 SourceRange ErrorRange, NoteRange;
5395 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5396 // If clause is a capture:
5397 // v = x++;
5398 // v = x--;
5399 // v = ++x;
5400 // v = --x;
5401 // v = x binop= expr;
5402 // v = x = x binop expr;
5403 // v = x = expr binop x;
5404 auto *AtomicBinOp =
5405 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5406 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5407 V = AtomicBinOp->getLHS();
5408 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5409 OpenMPAtomicUpdateChecker Checker(*this);
5410 if (Checker.checkStatement(
5411 Body, diag::err_omp_atomic_capture_not_expression_statement,
5412 diag::note_omp_atomic_update))
5413 return StmtError();
5414 E = Checker.getExpr();
5415 X = Checker.getX();
5416 UE = Checker.getUpdateExpr();
5417 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5418 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005419 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005420 ErrorLoc = AtomicBody->getExprLoc();
5421 ErrorRange = AtomicBody->getSourceRange();
5422 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5423 : AtomicBody->getExprLoc();
5424 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5425 : AtomicBody->getSourceRange();
5426 ErrorFound = NotAnAssignmentOp;
5427 }
5428 if (ErrorFound != NoError) {
5429 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5430 << ErrorRange;
5431 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5432 return StmtError();
5433 } else if (CurContext->isDependentContext()) {
5434 UE = V = E = X = nullptr;
5435 }
5436 } else {
5437 // If clause is a capture:
5438 // { v = x; x = expr; }
5439 // { v = x; x++; }
5440 // { v = x; x--; }
5441 // { v = x; ++x; }
5442 // { v = x; --x; }
5443 // { v = x; x binop= expr; }
5444 // { v = x; x = x binop expr; }
5445 // { v = x; x = expr binop x; }
5446 // { x++; v = x; }
5447 // { x--; v = x; }
5448 // { ++x; v = x; }
5449 // { --x; v = x; }
5450 // { x binop= expr; v = x; }
5451 // { x = x binop expr; v = x; }
5452 // { x = expr binop x; v = x; }
5453 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5454 // Check that this is { expr1; expr2; }
5455 if (CS->size() == 2) {
5456 auto *First = CS->body_front();
5457 auto *Second = CS->body_back();
5458 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5459 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5460 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5461 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5462 // Need to find what subexpression is 'v' and what is 'x'.
5463 OpenMPAtomicUpdateChecker Checker(*this);
5464 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5465 BinaryOperator *BinOp = nullptr;
5466 if (IsUpdateExprFound) {
5467 BinOp = dyn_cast<BinaryOperator>(First);
5468 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5469 }
5470 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5471 // { v = x; x++; }
5472 // { v = x; x--; }
5473 // { v = x; ++x; }
5474 // { v = x; --x; }
5475 // { v = x; x binop= expr; }
5476 // { v = x; x = x binop expr; }
5477 // { v = x; x = expr binop x; }
5478 // Check that the first expression has form v = x.
5479 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5480 llvm::FoldingSetNodeID XId, PossibleXId;
5481 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5482 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5483 IsUpdateExprFound = XId == PossibleXId;
5484 if (IsUpdateExprFound) {
5485 V = BinOp->getLHS();
5486 X = Checker.getX();
5487 E = Checker.getExpr();
5488 UE = Checker.getUpdateExpr();
5489 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005490 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005491 }
5492 }
5493 if (!IsUpdateExprFound) {
5494 IsUpdateExprFound = !Checker.checkStatement(First);
5495 BinOp = nullptr;
5496 if (IsUpdateExprFound) {
5497 BinOp = dyn_cast<BinaryOperator>(Second);
5498 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5499 }
5500 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5501 // { x++; v = x; }
5502 // { x--; v = x; }
5503 // { ++x; v = x; }
5504 // { --x; v = x; }
5505 // { x binop= expr; v = x; }
5506 // { x = x binop expr; v = x; }
5507 // { x = expr binop x; v = x; }
5508 // Check that the second expression has form v = x.
5509 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5510 llvm::FoldingSetNodeID XId, PossibleXId;
5511 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5512 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5513 IsUpdateExprFound = XId == PossibleXId;
5514 if (IsUpdateExprFound) {
5515 V = BinOp->getLHS();
5516 X = Checker.getX();
5517 E = Checker.getExpr();
5518 UE = Checker.getUpdateExpr();
5519 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005520 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005521 }
5522 }
5523 }
5524 if (!IsUpdateExprFound) {
5525 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005526 auto *FirstExpr = dyn_cast<Expr>(First);
5527 auto *SecondExpr = dyn_cast<Expr>(Second);
5528 if (!FirstExpr || !SecondExpr ||
5529 !(FirstExpr->isInstantiationDependent() ||
5530 SecondExpr->isInstantiationDependent())) {
5531 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5532 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005533 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005534 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5535 : First->getLocStart();
5536 NoteRange = ErrorRange = FirstBinOp
5537 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005538 : SourceRange(ErrorLoc, ErrorLoc);
5539 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005540 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5541 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5542 ErrorFound = NotAnAssignmentOp;
5543 NoteLoc = ErrorLoc = SecondBinOp
5544 ? SecondBinOp->getOperatorLoc()
5545 : Second->getLocStart();
5546 NoteRange = ErrorRange =
5547 SecondBinOp ? SecondBinOp->getSourceRange()
5548 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005549 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005550 auto *PossibleXRHSInFirst =
5551 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5552 auto *PossibleXLHSInSecond =
5553 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5554 llvm::FoldingSetNodeID X1Id, X2Id;
5555 PossibleXRHSInFirst->Profile(X1Id, Context,
5556 /*Canonical=*/true);
5557 PossibleXLHSInSecond->Profile(X2Id, Context,
5558 /*Canonical=*/true);
5559 IsUpdateExprFound = X1Id == X2Id;
5560 if (IsUpdateExprFound) {
5561 V = FirstBinOp->getLHS();
5562 X = SecondBinOp->getLHS();
5563 E = SecondBinOp->getRHS();
5564 UE = nullptr;
5565 IsXLHSInRHSPart = false;
5566 IsPostfixUpdate = true;
5567 } else {
5568 ErrorFound = NotASpecificExpression;
5569 ErrorLoc = FirstBinOp->getExprLoc();
5570 ErrorRange = FirstBinOp->getSourceRange();
5571 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5572 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5573 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005574 }
5575 }
5576 }
5577 }
5578 } else {
5579 NoteLoc = ErrorLoc = Body->getLocStart();
5580 NoteRange = ErrorRange =
5581 SourceRange(Body->getLocStart(), Body->getLocStart());
5582 ErrorFound = NotTwoSubstatements;
5583 }
5584 } else {
5585 NoteLoc = ErrorLoc = Body->getLocStart();
5586 NoteRange = ErrorRange =
5587 SourceRange(Body->getLocStart(), Body->getLocStart());
5588 ErrorFound = NotACompoundStatement;
5589 }
5590 if (ErrorFound != NoError) {
5591 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5592 << ErrorRange;
5593 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5594 return StmtError();
5595 } else if (CurContext->isDependentContext()) {
5596 UE = V = E = X = nullptr;
5597 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005598 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005599 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005600
5601 getCurFunction()->setHasBranchProtectedScope();
5602
Alexey Bataev62cec442014-11-18 10:14:22 +00005603 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005604 X, V, E, UE, IsXLHSInRHSPart,
5605 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005606}
5607
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005608StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5609 Stmt *AStmt,
5610 SourceLocation StartLoc,
5611 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005612 if (!AStmt)
5613 return StmtError();
5614
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005615 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5616 // 1.2.2 OpenMP Language Terminology
5617 // Structured block - An executable statement with a single entry at the
5618 // top and a single exit at the bottom.
5619 // The point of exit cannot be a branch out of the structured block.
5620 // longjmp() and throw() must not violate the entry/exit criteria.
5621 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005622
Alexey Bataev13314bf2014-10-09 04:18:56 +00005623 // OpenMP [2.16, Nesting of Regions]
5624 // If specified, a teams construct must be contained within a target
5625 // construct. That target construct must contain no statements or directives
5626 // outside of the teams construct.
5627 if (DSAStack->hasInnerTeamsRegion()) {
5628 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5629 bool OMPTeamsFound = true;
5630 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5631 auto I = CS->body_begin();
5632 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005633 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005634 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5635 OMPTeamsFound = false;
5636 break;
5637 }
5638 ++I;
5639 }
5640 assert(I != CS->body_end() && "Not found statement");
5641 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005642 } else {
5643 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5644 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005645 }
5646 if (!OMPTeamsFound) {
5647 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5648 Diag(DSAStack->getInnerTeamsRegionLoc(),
5649 diag::note_omp_nested_teams_construct_here);
5650 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5651 << isa<OMPExecutableDirective>(S);
5652 return StmtError();
5653 }
5654 }
5655
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005656 getCurFunction()->setHasBranchProtectedScope();
5657
5658 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5659}
5660
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005661StmtResult
5662Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5663 Stmt *AStmt, SourceLocation StartLoc,
5664 SourceLocation EndLoc) {
5665 if (!AStmt)
5666 return StmtError();
5667
5668 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5669 // 1.2.2 OpenMP Language Terminology
5670 // Structured block - An executable statement with a single entry at the
5671 // top and a single exit at the bottom.
5672 // The point of exit cannot be a branch out of the structured block.
5673 // longjmp() and throw() must not violate the entry/exit criteria.
5674 CS->getCapturedDecl()->setNothrow();
5675
5676 getCurFunction()->setHasBranchProtectedScope();
5677
5678 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5679 AStmt);
5680}
5681
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005682StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5683 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5684 SourceLocation EndLoc,
5685 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5686 if (!AStmt)
5687 return StmtError();
5688
5689 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5690 // 1.2.2 OpenMP Language Terminology
5691 // Structured block - An executable statement with a single entry at the
5692 // top and a single exit at the bottom.
5693 // The point of exit cannot be a branch out of the structured block.
5694 // longjmp() and throw() must not violate the entry/exit criteria.
5695 CS->getCapturedDecl()->setNothrow();
5696
5697 OMPLoopDirective::HelperExprs B;
5698 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5699 // define the nested loops number.
5700 unsigned NestedLoopCount =
5701 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5702 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5703 VarsWithImplicitDSA, B);
5704 if (NestedLoopCount == 0)
5705 return StmtError();
5706
5707 assert((CurContext->isDependentContext() || B.builtAll()) &&
5708 "omp target parallel for loop exprs were not built");
5709
5710 if (!CurContext->isDependentContext()) {
5711 // Finalize the clauses that need pre-built expressions for CodeGen.
5712 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005713 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005714 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005715 B.NumIterations, *this, CurScope,
5716 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005717 return StmtError();
5718 }
5719 }
5720
5721 getCurFunction()->setHasBranchProtectedScope();
5722 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5723 NestedLoopCount, Clauses, AStmt,
5724 B, DSAStack->isCancelRegion());
5725}
5726
Samuel Antaodf67fc42016-01-19 19:15:56 +00005727/// \brief Check for existence of a map clause in the list of clauses.
5728static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5729 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5730 I != E; ++I) {
5731 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5732 return true;
5733 }
5734 }
5735
5736 return false;
5737}
5738
Michael Wong65f367f2015-07-21 13:44:28 +00005739StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5740 Stmt *AStmt,
5741 SourceLocation StartLoc,
5742 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005743 if (!AStmt)
5744 return StmtError();
5745
5746 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5747
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005748 // OpenMP [2.10.1, Restrictions, p. 97]
5749 // At least one map clause must appear on the directive.
5750 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005751 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5752 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005753 return StmtError();
5754 }
5755
Michael Wong65f367f2015-07-21 13:44:28 +00005756 getCurFunction()->setHasBranchProtectedScope();
5757
5758 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5759 AStmt);
5760}
5761
Samuel Antaodf67fc42016-01-19 19:15:56 +00005762StmtResult
5763Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5764 SourceLocation StartLoc,
5765 SourceLocation EndLoc) {
5766 // OpenMP [2.10.2, Restrictions, p. 99]
5767 // At least one map clause must appear on the directive.
5768 if (!HasMapClause(Clauses)) {
5769 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5770 << getOpenMPDirectiveName(OMPD_target_enter_data);
5771 return StmtError();
5772 }
5773
5774 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5775 Clauses);
5776}
5777
Samuel Antao72590762016-01-19 20:04:50 +00005778StmtResult
5779Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5780 SourceLocation StartLoc,
5781 SourceLocation EndLoc) {
5782 // OpenMP [2.10.3, Restrictions, p. 102]
5783 // At least one map clause must appear on the directive.
5784 if (!HasMapClause(Clauses)) {
5785 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5786 << getOpenMPDirectiveName(OMPD_target_exit_data);
5787 return StmtError();
5788 }
5789
5790 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5791}
5792
Samuel Antao686c70c2016-05-26 17:30:50 +00005793StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5794 SourceLocation StartLoc,
5795 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005796 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005797 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005798 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005799 seenMotionClause = true;
5800 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005801 if (!seenMotionClause) {
5802 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5803 return StmtError();
5804 }
5805 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5806}
5807
Alexey Bataev13314bf2014-10-09 04:18:56 +00005808StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5809 Stmt *AStmt, SourceLocation StartLoc,
5810 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005811 if (!AStmt)
5812 return StmtError();
5813
Alexey Bataev13314bf2014-10-09 04:18:56 +00005814 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5815 // 1.2.2 OpenMP Language Terminology
5816 // Structured block - An executable statement with a single entry at the
5817 // top and a single exit at the bottom.
5818 // The point of exit cannot be a branch out of the structured block.
5819 // longjmp() and throw() must not violate the entry/exit criteria.
5820 CS->getCapturedDecl()->setNothrow();
5821
5822 getCurFunction()->setHasBranchProtectedScope();
5823
5824 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5825}
5826
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005827StmtResult
5828Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5829 SourceLocation EndLoc,
5830 OpenMPDirectiveKind CancelRegion) {
5831 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5832 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5833 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5834 << getOpenMPDirectiveName(CancelRegion);
5835 return StmtError();
5836 }
5837 if (DSAStack->isParentNowaitRegion()) {
5838 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5839 return StmtError();
5840 }
5841 if (DSAStack->isParentOrderedRegion()) {
5842 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5843 return StmtError();
5844 }
5845 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5846 CancelRegion);
5847}
5848
Alexey Bataev87933c72015-09-18 08:07:34 +00005849StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5850 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005851 SourceLocation EndLoc,
5852 OpenMPDirectiveKind CancelRegion) {
5853 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5854 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5855 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5856 << getOpenMPDirectiveName(CancelRegion);
5857 return StmtError();
5858 }
5859 if (DSAStack->isParentNowaitRegion()) {
5860 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5861 return StmtError();
5862 }
5863 if (DSAStack->isParentOrderedRegion()) {
5864 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5865 return StmtError();
5866 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005867 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005868 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5869 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005870}
5871
Alexey Bataev382967a2015-12-08 12:06:20 +00005872static bool checkGrainsizeNumTasksClauses(Sema &S,
5873 ArrayRef<OMPClause *> Clauses) {
5874 OMPClause *PrevClause = nullptr;
5875 bool ErrorFound = false;
5876 for (auto *C : Clauses) {
5877 if (C->getClauseKind() == OMPC_grainsize ||
5878 C->getClauseKind() == OMPC_num_tasks) {
5879 if (!PrevClause)
5880 PrevClause = C;
5881 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5882 S.Diag(C->getLocStart(),
5883 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5884 << getOpenMPClauseName(C->getClauseKind())
5885 << getOpenMPClauseName(PrevClause->getClauseKind());
5886 S.Diag(PrevClause->getLocStart(),
5887 diag::note_omp_previous_grainsize_num_tasks)
5888 << getOpenMPClauseName(PrevClause->getClauseKind());
5889 ErrorFound = true;
5890 }
5891 }
5892 }
5893 return ErrorFound;
5894}
5895
Alexey Bataev49f6e782015-12-01 04:18:41 +00005896StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5897 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5898 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005899 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005900 if (!AStmt)
5901 return StmtError();
5902
5903 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5904 OMPLoopDirective::HelperExprs B;
5905 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5906 // define the nested loops number.
5907 unsigned NestedLoopCount =
5908 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005909 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005910 VarsWithImplicitDSA, B);
5911 if (NestedLoopCount == 0)
5912 return StmtError();
5913
5914 assert((CurContext->isDependentContext() || B.builtAll()) &&
5915 "omp for loop exprs were not built");
5916
Alexey Bataev382967a2015-12-08 12:06:20 +00005917 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5918 // The grainsize clause and num_tasks clause are mutually exclusive and may
5919 // not appear on the same taskloop directive.
5920 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5921 return StmtError();
5922
Alexey Bataev49f6e782015-12-01 04:18:41 +00005923 getCurFunction()->setHasBranchProtectedScope();
5924 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5925 NestedLoopCount, Clauses, AStmt, B);
5926}
5927
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005928StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5929 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5930 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005931 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005932 if (!AStmt)
5933 return StmtError();
5934
5935 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5936 OMPLoopDirective::HelperExprs B;
5937 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5938 // define the nested loops number.
5939 unsigned NestedLoopCount =
5940 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5941 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5942 VarsWithImplicitDSA, B);
5943 if (NestedLoopCount == 0)
5944 return StmtError();
5945
5946 assert((CurContext->isDependentContext() || B.builtAll()) &&
5947 "omp for loop exprs were not built");
5948
Alexey Bataev5a3af132016-03-29 08:58:54 +00005949 if (!CurContext->isDependentContext()) {
5950 // Finalize the clauses that need pre-built expressions for CodeGen.
5951 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005952 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005953 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005954 B.NumIterations, *this, CurScope,
5955 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005956 return StmtError();
5957 }
5958 }
5959
Alexey Bataev382967a2015-12-08 12:06:20 +00005960 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5961 // The grainsize clause and num_tasks clause are mutually exclusive and may
5962 // not appear on the same taskloop directive.
5963 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5964 return StmtError();
5965
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005966 getCurFunction()->setHasBranchProtectedScope();
5967 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5968 NestedLoopCount, Clauses, AStmt, B);
5969}
5970
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005971StmtResult Sema::ActOnOpenMPDistributeDirective(
5972 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5973 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005974 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005975 if (!AStmt)
5976 return StmtError();
5977
5978 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5979 OMPLoopDirective::HelperExprs B;
5980 // In presence of clause 'collapse' with number of loops, it will
5981 // define the nested loops number.
5982 unsigned NestedLoopCount =
5983 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5984 nullptr /*ordered not a clause on distribute*/, AStmt,
5985 *this, *DSAStack, VarsWithImplicitDSA, B);
5986 if (NestedLoopCount == 0)
5987 return StmtError();
5988
5989 assert((CurContext->isDependentContext() || B.builtAll()) &&
5990 "omp for loop exprs were not built");
5991
5992 getCurFunction()->setHasBranchProtectedScope();
5993 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5994 NestedLoopCount, Clauses, AStmt, B);
5995}
5996
Carlo Bertolli9925f152016-06-27 14:55:37 +00005997StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5998 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5999 SourceLocation EndLoc,
6000 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6001 if (!AStmt)
6002 return StmtError();
6003
6004 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6005 // 1.2.2 OpenMP Language Terminology
6006 // Structured block - An executable statement with a single entry at the
6007 // top and a single exit at the bottom.
6008 // The point of exit cannot be a branch out of the structured block.
6009 // longjmp() and throw() must not violate the entry/exit criteria.
6010 CS->getCapturedDecl()->setNothrow();
6011
6012 OMPLoopDirective::HelperExprs B;
6013 // In presence of clause 'collapse' with number of loops, it will
6014 // define the nested loops number.
6015 unsigned NestedLoopCount = CheckOpenMPLoop(
6016 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6017 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6018 VarsWithImplicitDSA, B);
6019 if (NestedLoopCount == 0)
6020 return StmtError();
6021
6022 assert((CurContext->isDependentContext() || B.builtAll()) &&
6023 "omp for loop exprs were not built");
6024
6025 getCurFunction()->setHasBranchProtectedScope();
6026 return OMPDistributeParallelForDirective::Create(
6027 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6028}
6029
Kelvin Li4a39add2016-07-05 05:00:15 +00006030StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6031 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6032 SourceLocation EndLoc,
6033 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6034 if (!AStmt)
6035 return StmtError();
6036
6037 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6038 // 1.2.2 OpenMP Language Terminology
6039 // Structured block - An executable statement with a single entry at the
6040 // top and a single exit at the bottom.
6041 // The point of exit cannot be a branch out of the structured block.
6042 // longjmp() and throw() must not violate the entry/exit criteria.
6043 CS->getCapturedDecl()->setNothrow();
6044
6045 OMPLoopDirective::HelperExprs B;
6046 // In presence of clause 'collapse' with number of loops, it will
6047 // define the nested loops number.
6048 unsigned NestedLoopCount = CheckOpenMPLoop(
6049 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6050 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6051 VarsWithImplicitDSA, B);
6052 if (NestedLoopCount == 0)
6053 return StmtError();
6054
6055 assert((CurContext->isDependentContext() || B.builtAll()) &&
6056 "omp for loop exprs were not built");
6057
Kelvin Lic5609492016-07-15 04:39:07 +00006058 if (checkSimdlenSafelenSpecified(*this, Clauses))
6059 return StmtError();
6060
Kelvin Li4a39add2016-07-05 05:00:15 +00006061 getCurFunction()->setHasBranchProtectedScope();
6062 return OMPDistributeParallelForSimdDirective::Create(
6063 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6064}
6065
Kelvin Li787f3fc2016-07-06 04:45:38 +00006066StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6067 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6068 SourceLocation EndLoc,
6069 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6070 if (!AStmt)
6071 return StmtError();
6072
6073 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6074 // 1.2.2 OpenMP Language Terminology
6075 // Structured block - An executable statement with a single entry at the
6076 // top and a single exit at the bottom.
6077 // The point of exit cannot be a branch out of the structured block.
6078 // longjmp() and throw() must not violate the entry/exit criteria.
6079 CS->getCapturedDecl()->setNothrow();
6080
6081 OMPLoopDirective::HelperExprs B;
6082 // In presence of clause 'collapse' with number of loops, it will
6083 // define the nested loops number.
6084 unsigned NestedLoopCount =
6085 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6086 nullptr /*ordered not a clause on distribute*/, AStmt,
6087 *this, *DSAStack, VarsWithImplicitDSA, B);
6088 if (NestedLoopCount == 0)
6089 return StmtError();
6090
6091 assert((CurContext->isDependentContext() || B.builtAll()) &&
6092 "omp for loop exprs were not built");
6093
Kelvin Lic5609492016-07-15 04:39:07 +00006094 if (checkSimdlenSafelenSpecified(*this, Clauses))
6095 return StmtError();
6096
Kelvin Li787f3fc2016-07-06 04:45:38 +00006097 getCurFunction()->setHasBranchProtectedScope();
6098 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6099 NestedLoopCount, Clauses, AStmt, B);
6100}
6101
Kelvin Lia579b912016-07-14 02:54:56 +00006102StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6103 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6104 SourceLocation EndLoc,
6105 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6106 if (!AStmt)
6107 return StmtError();
6108
6109 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6110 // 1.2.2 OpenMP Language Terminology
6111 // Structured block - An executable statement with a single entry at the
6112 // top and a single exit at the bottom.
6113 // The point of exit cannot be a branch out of the structured block.
6114 // longjmp() and throw() must not violate the entry/exit criteria.
6115 CS->getCapturedDecl()->setNothrow();
6116
6117 OMPLoopDirective::HelperExprs B;
6118 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6119 // define the nested loops number.
6120 unsigned NestedLoopCount = CheckOpenMPLoop(
6121 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6122 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6123 VarsWithImplicitDSA, B);
6124 if (NestedLoopCount == 0)
6125 return StmtError();
6126
6127 assert((CurContext->isDependentContext() || B.builtAll()) &&
6128 "omp target parallel for simd loop exprs were not built");
6129
6130 if (!CurContext->isDependentContext()) {
6131 // Finalize the clauses that need pre-built expressions for CodeGen.
6132 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006133 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006134 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6135 B.NumIterations, *this, CurScope,
6136 DSAStack))
6137 return StmtError();
6138 }
6139 }
Kelvin Lic5609492016-07-15 04:39:07 +00006140 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006141 return StmtError();
6142
6143 getCurFunction()->setHasBranchProtectedScope();
6144 return OMPTargetParallelForSimdDirective::Create(
6145 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6146}
6147
Kelvin Li986330c2016-07-20 22:57:10 +00006148StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6149 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6150 SourceLocation EndLoc,
6151 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6152 if (!AStmt)
6153 return StmtError();
6154
6155 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6156 // 1.2.2 OpenMP Language Terminology
6157 // Structured block - An executable statement with a single entry at the
6158 // top and a single exit at the bottom.
6159 // The point of exit cannot be a branch out of the structured block.
6160 // longjmp() and throw() must not violate the entry/exit criteria.
6161 CS->getCapturedDecl()->setNothrow();
6162
6163 OMPLoopDirective::HelperExprs B;
6164 // In presence of clause 'collapse' with number of loops, it will define the
6165 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006166 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006167 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6168 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6169 VarsWithImplicitDSA, B);
6170 if (NestedLoopCount == 0)
6171 return StmtError();
6172
6173 assert((CurContext->isDependentContext() || B.builtAll()) &&
6174 "omp target simd loop exprs were not built");
6175
6176 if (!CurContext->isDependentContext()) {
6177 // Finalize the clauses that need pre-built expressions for CodeGen.
6178 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006179 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006180 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6181 B.NumIterations, *this, CurScope,
6182 DSAStack))
6183 return StmtError();
6184 }
6185 }
6186
6187 if (checkSimdlenSafelenSpecified(*this, Clauses))
6188 return StmtError();
6189
6190 getCurFunction()->setHasBranchProtectedScope();
6191 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6192 NestedLoopCount, Clauses, AStmt, B);
6193}
6194
Kelvin Li02532872016-08-05 14:37:37 +00006195StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6196 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6197 SourceLocation EndLoc,
6198 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6199 if (!AStmt)
6200 return StmtError();
6201
6202 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6203 // 1.2.2 OpenMP Language Terminology
6204 // Structured block - An executable statement with a single entry at the
6205 // top and a single exit at the bottom.
6206 // The point of exit cannot be a branch out of the structured block.
6207 // longjmp() and throw() must not violate the entry/exit criteria.
6208 CS->getCapturedDecl()->setNothrow();
6209
6210 OMPLoopDirective::HelperExprs B;
6211 // In presence of clause 'collapse' with number of loops, it will
6212 // define the nested loops number.
6213 unsigned NestedLoopCount =
6214 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6215 nullptr /*ordered not a clause on distribute*/, AStmt,
6216 *this, *DSAStack, VarsWithImplicitDSA, B);
6217 if (NestedLoopCount == 0)
6218 return StmtError();
6219
6220 assert((CurContext->isDependentContext() || B.builtAll()) &&
6221 "omp teams distribute loop exprs were not built");
6222
6223 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006224 return OMPTeamsDistributeDirective::Create(
6225 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006226}
6227
Kelvin Li4e325f72016-10-25 12:50:55 +00006228StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6229 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6230 SourceLocation EndLoc,
6231 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6232 if (!AStmt)
6233 return StmtError();
6234
6235 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6236 // 1.2.2 OpenMP Language Terminology
6237 // Structured block - An executable statement with a single entry at the
6238 // top and a single exit at the bottom.
6239 // The point of exit cannot be a branch out of the structured block.
6240 // longjmp() and throw() must not violate the entry/exit criteria.
6241 CS->getCapturedDecl()->setNothrow();
6242
6243 OMPLoopDirective::HelperExprs B;
6244 // In presence of clause 'collapse' with number of loops, it will
6245 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006246 unsigned NestedLoopCount = CheckOpenMPLoop(
6247 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6248 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6249 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006250
6251 if (NestedLoopCount == 0)
6252 return StmtError();
6253
6254 assert((CurContext->isDependentContext() || B.builtAll()) &&
6255 "omp teams distribute simd loop exprs were not built");
6256
6257 if (!CurContext->isDependentContext()) {
6258 // Finalize the clauses that need pre-built expressions for CodeGen.
6259 for (auto C : Clauses) {
6260 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6261 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6262 B.NumIterations, *this, CurScope,
6263 DSAStack))
6264 return StmtError();
6265 }
6266 }
6267
6268 if (checkSimdlenSafelenSpecified(*this, Clauses))
6269 return StmtError();
6270
6271 getCurFunction()->setHasBranchProtectedScope();
6272 return OMPTeamsDistributeSimdDirective::Create(
6273 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6274}
6275
Kelvin Li579e41c2016-11-30 23:51:03 +00006276StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6277 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6278 SourceLocation EndLoc,
6279 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6280 if (!AStmt)
6281 return StmtError();
6282
6283 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6284 // 1.2.2 OpenMP Language Terminology
6285 // Structured block - An executable statement with a single entry at the
6286 // top and a single exit at the bottom.
6287 // The point of exit cannot be a branch out of the structured block.
6288 // longjmp() and throw() must not violate the entry/exit criteria.
6289 CS->getCapturedDecl()->setNothrow();
6290
6291 OMPLoopDirective::HelperExprs B;
6292 // In presence of clause 'collapse' with number of loops, it will
6293 // define the nested loops number.
6294 auto NestedLoopCount = CheckOpenMPLoop(
6295 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6296 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6297 VarsWithImplicitDSA, B);
6298
6299 if (NestedLoopCount == 0)
6300 return StmtError();
6301
6302 assert((CurContext->isDependentContext() || B.builtAll()) &&
6303 "omp for loop exprs were not built");
6304
6305 if (!CurContext->isDependentContext()) {
6306 // Finalize the clauses that need pre-built expressions for CodeGen.
6307 for (auto C : Clauses) {
6308 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6309 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6310 B.NumIterations, *this, CurScope,
6311 DSAStack))
6312 return StmtError();
6313 }
6314 }
6315
6316 if (checkSimdlenSafelenSpecified(*this, Clauses))
6317 return StmtError();
6318
6319 getCurFunction()->setHasBranchProtectedScope();
6320 return OMPTeamsDistributeParallelForSimdDirective::Create(
6321 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6322}
6323
Kelvin Li7ade93f2016-12-09 03:24:30 +00006324StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6325 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6326 SourceLocation EndLoc,
6327 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6328 if (!AStmt)
6329 return StmtError();
6330
6331 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6332 // 1.2.2 OpenMP Language Terminology
6333 // Structured block - An executable statement with a single entry at the
6334 // top and a single exit at the bottom.
6335 // The point of exit cannot be a branch out of the structured block.
6336 // longjmp() and throw() must not violate the entry/exit criteria.
6337 CS->getCapturedDecl()->setNothrow();
6338
6339 OMPLoopDirective::HelperExprs B;
6340 // In presence of clause 'collapse' with number of loops, it will
6341 // define the nested loops number.
6342 unsigned NestedLoopCount = CheckOpenMPLoop(
6343 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6344 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6345 VarsWithImplicitDSA, B);
6346
6347 if (NestedLoopCount == 0)
6348 return StmtError();
6349
6350 assert((CurContext->isDependentContext() || B.builtAll()) &&
6351 "omp for loop exprs were not built");
6352
6353 if (!CurContext->isDependentContext()) {
6354 // Finalize the clauses that need pre-built expressions for CodeGen.
6355 for (auto C : Clauses) {
6356 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6357 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6358 B.NumIterations, *this, CurScope,
6359 DSAStack))
6360 return StmtError();
6361 }
6362 }
6363
6364 getCurFunction()->setHasBranchProtectedScope();
6365 return OMPTeamsDistributeParallelForDirective::Create(
6366 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6367}
6368
Kelvin Libf594a52016-12-17 05:48:59 +00006369StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6370 Stmt *AStmt,
6371 SourceLocation StartLoc,
6372 SourceLocation EndLoc) {
6373 if (!AStmt)
6374 return StmtError();
6375
6376 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6377 // 1.2.2 OpenMP Language Terminology
6378 // Structured block - An executable statement with a single entry at the
6379 // top and a single exit at the bottom.
6380 // The point of exit cannot be a branch out of the structured block.
6381 // longjmp() and throw() must not violate the entry/exit criteria.
6382 CS->getCapturedDecl()->setNothrow();
6383
6384 getCurFunction()->setHasBranchProtectedScope();
6385
6386 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6387 AStmt);
6388}
6389
Kelvin Li83c451e2016-12-25 04:52:54 +00006390StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6391 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6392 SourceLocation EndLoc,
6393 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6394 if (!AStmt)
6395 return StmtError();
6396
6397 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6398 // 1.2.2 OpenMP Language Terminology
6399 // Structured block - An executable statement with a single entry at the
6400 // top and a single exit at the bottom.
6401 // The point of exit cannot be a branch out of the structured block.
6402 // longjmp() and throw() must not violate the entry/exit criteria.
6403 CS->getCapturedDecl()->setNothrow();
6404
6405 OMPLoopDirective::HelperExprs B;
6406 // In presence of clause 'collapse' with number of loops, it will
6407 // define the nested loops number.
6408 auto NestedLoopCount = CheckOpenMPLoop(
6409 OMPD_target_teams_distribute,
6410 getCollapseNumberExpr(Clauses),
6411 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6412 VarsWithImplicitDSA, B);
6413 if (NestedLoopCount == 0)
6414 return StmtError();
6415
6416 assert((CurContext->isDependentContext() || B.builtAll()) &&
6417 "omp target teams distribute loop exprs were not built");
6418
6419 getCurFunction()->setHasBranchProtectedScope();
6420 return OMPTargetTeamsDistributeDirective::Create(
6421 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6422}
6423
Kelvin Li80e8f562016-12-29 22:16:30 +00006424StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6425 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6426 SourceLocation EndLoc,
6427 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6428 if (!AStmt)
6429 return StmtError();
6430
6431 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6432 // 1.2.2 OpenMP Language Terminology
6433 // Structured block - An executable statement with a single entry at the
6434 // top and a single exit at the bottom.
6435 // The point of exit cannot be a branch out of the structured block.
6436 // longjmp() and throw() must not violate the entry/exit criteria.
6437 CS->getCapturedDecl()->setNothrow();
6438
6439 OMPLoopDirective::HelperExprs B;
6440 // In presence of clause 'collapse' with number of loops, it will
6441 // define the nested loops number.
6442 auto NestedLoopCount = CheckOpenMPLoop(
6443 OMPD_target_teams_distribute_parallel_for,
6444 getCollapseNumberExpr(Clauses),
6445 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6446 VarsWithImplicitDSA, B);
6447 if (NestedLoopCount == 0)
6448 return StmtError();
6449
6450 assert((CurContext->isDependentContext() || B.builtAll()) &&
6451 "omp target teams distribute parallel for loop exprs were not built");
6452
6453 if (!CurContext->isDependentContext()) {
6454 // Finalize the clauses that need pre-built expressions for CodeGen.
6455 for (auto C : Clauses) {
6456 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6457 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6458 B.NumIterations, *this, CurScope,
6459 DSAStack))
6460 return StmtError();
6461 }
6462 }
6463
6464 getCurFunction()->setHasBranchProtectedScope();
6465 return OMPTargetTeamsDistributeParallelForDirective::Create(
6466 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6467}
6468
Kelvin Li1851df52017-01-03 05:23:48 +00006469StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6470 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6471 SourceLocation EndLoc,
6472 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6473 if (!AStmt)
6474 return StmtError();
6475
6476 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6477 // 1.2.2 OpenMP Language Terminology
6478 // Structured block - An executable statement with a single entry at the
6479 // top and a single exit at the bottom.
6480 // The point of exit cannot be a branch out of the structured block.
6481 // longjmp() and throw() must not violate the entry/exit criteria.
6482 CS->getCapturedDecl()->setNothrow();
6483
6484 OMPLoopDirective::HelperExprs B;
6485 // In presence of clause 'collapse' with number of loops, it will
6486 // define the nested loops number.
6487 auto NestedLoopCount = CheckOpenMPLoop(
6488 OMPD_target_teams_distribute_parallel_for_simd,
6489 getCollapseNumberExpr(Clauses),
6490 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6491 VarsWithImplicitDSA, B);
6492 if (NestedLoopCount == 0)
6493 return StmtError();
6494
6495 assert((CurContext->isDependentContext() || B.builtAll()) &&
6496 "omp target teams distribute parallel for simd loop exprs were not "
6497 "built");
6498
6499 if (!CurContext->isDependentContext()) {
6500 // Finalize the clauses that need pre-built expressions for CodeGen.
6501 for (auto C : Clauses) {
6502 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6503 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6504 B.NumIterations, *this, CurScope,
6505 DSAStack))
6506 return StmtError();
6507 }
6508 }
6509
6510 getCurFunction()->setHasBranchProtectedScope();
6511 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6512 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6513}
6514
Kelvin Lida681182017-01-10 18:08:18 +00006515StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6516 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6517 SourceLocation EndLoc,
6518 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6519 if (!AStmt)
6520 return StmtError();
6521
6522 auto *CS = cast<CapturedStmt>(AStmt);
6523 // 1.2.2 OpenMP Language Terminology
6524 // Structured block - An executable statement with a single entry at the
6525 // top and a single exit at the bottom.
6526 // The point of exit cannot be a branch out of the structured block.
6527 // longjmp() and throw() must not violate the entry/exit criteria.
6528 CS->getCapturedDecl()->setNothrow();
6529
6530 OMPLoopDirective::HelperExprs B;
6531 // In presence of clause 'collapse' with number of loops, it will
6532 // define the nested loops number.
6533 auto NestedLoopCount = CheckOpenMPLoop(
6534 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6535 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6536 VarsWithImplicitDSA, B);
6537 if (NestedLoopCount == 0)
6538 return StmtError();
6539
6540 assert((CurContext->isDependentContext() || B.builtAll()) &&
6541 "omp target teams distribute simd loop exprs were not built");
6542
6543 getCurFunction()->setHasBranchProtectedScope();
6544 return OMPTargetTeamsDistributeSimdDirective::Create(
6545 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6546}
6547
Alexey Bataeved09d242014-05-28 05:53:51 +00006548OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006549 SourceLocation StartLoc,
6550 SourceLocation LParenLoc,
6551 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006552 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006553 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006554 case OMPC_final:
6555 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6556 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006557 case OMPC_num_threads:
6558 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6559 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006560 case OMPC_safelen:
6561 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6562 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006563 case OMPC_simdlen:
6564 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6565 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006566 case OMPC_collapse:
6567 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6568 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006569 case OMPC_ordered:
6570 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6571 break;
Michael Wonge710d542015-08-07 16:16:36 +00006572 case OMPC_device:
6573 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6574 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006575 case OMPC_num_teams:
6576 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6577 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006578 case OMPC_thread_limit:
6579 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6580 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006581 case OMPC_priority:
6582 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6583 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006584 case OMPC_grainsize:
6585 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6586 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006587 case OMPC_num_tasks:
6588 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6589 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006590 case OMPC_hint:
6591 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6592 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006593 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006594 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006595 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006596 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006597 case OMPC_private:
6598 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006599 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006600 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006601 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006602 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006603 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006604 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006605 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006606 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006607 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006608 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006609 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006610 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006611 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006612 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006613 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006614 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006615 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006616 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006617 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006618 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006619 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006620 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006621 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006622 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006623 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006624 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006625 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006626 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006627 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006628 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006629 llvm_unreachable("Clause is not allowed.");
6630 }
6631 return Res;
6632}
6633
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006634// An OpenMP directive such as 'target parallel' has two captured regions:
6635// for the 'target' and 'parallel' respectively. This function returns
6636// the region in which to capture expressions associated with a clause.
6637// A return value of OMPD_unknown signifies that the expression should not
6638// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006639static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6640 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6641 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006642 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6643
6644 switch (CKind) {
6645 case OMPC_if:
6646 switch (DKind) {
6647 case OMPD_target_parallel:
6648 // If this clause applies to the nested 'parallel' region, capture within
6649 // the 'target' region, otherwise do not capture.
6650 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6651 CaptureRegion = OMPD_target;
6652 break;
6653 case OMPD_cancel:
6654 case OMPD_parallel:
6655 case OMPD_parallel_sections:
6656 case OMPD_parallel_for:
6657 case OMPD_parallel_for_simd:
6658 case OMPD_target:
6659 case OMPD_target_simd:
6660 case OMPD_target_parallel_for:
6661 case OMPD_target_parallel_for_simd:
6662 case OMPD_target_teams:
6663 case OMPD_target_teams_distribute:
6664 case OMPD_target_teams_distribute_simd:
6665 case OMPD_target_teams_distribute_parallel_for:
6666 case OMPD_target_teams_distribute_parallel_for_simd:
6667 case OMPD_teams_distribute_parallel_for:
6668 case OMPD_teams_distribute_parallel_for_simd:
6669 case OMPD_distribute_parallel_for:
6670 case OMPD_distribute_parallel_for_simd:
6671 case OMPD_task:
6672 case OMPD_taskloop:
6673 case OMPD_taskloop_simd:
6674 case OMPD_target_data:
6675 case OMPD_target_enter_data:
6676 case OMPD_target_exit_data:
6677 case OMPD_target_update:
6678 // Do not capture if-clause expressions.
6679 break;
6680 case OMPD_threadprivate:
6681 case OMPD_taskyield:
6682 case OMPD_barrier:
6683 case OMPD_taskwait:
6684 case OMPD_cancellation_point:
6685 case OMPD_flush:
6686 case OMPD_declare_reduction:
6687 case OMPD_declare_simd:
6688 case OMPD_declare_target:
6689 case OMPD_end_declare_target:
6690 case OMPD_teams:
6691 case OMPD_simd:
6692 case OMPD_for:
6693 case OMPD_for_simd:
6694 case OMPD_sections:
6695 case OMPD_section:
6696 case OMPD_single:
6697 case OMPD_master:
6698 case OMPD_critical:
6699 case OMPD_taskgroup:
6700 case OMPD_distribute:
6701 case OMPD_ordered:
6702 case OMPD_atomic:
6703 case OMPD_distribute_simd:
6704 case OMPD_teams_distribute:
6705 case OMPD_teams_distribute_simd:
6706 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6707 case OMPD_unknown:
6708 llvm_unreachable("Unknown OpenMP directive");
6709 }
6710 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006711 case OMPC_num_threads:
6712 switch (DKind) {
6713 case OMPD_target_parallel:
6714 CaptureRegion = OMPD_target;
6715 break;
6716 case OMPD_cancel:
6717 case OMPD_parallel:
6718 case OMPD_parallel_sections:
6719 case OMPD_parallel_for:
6720 case OMPD_parallel_for_simd:
6721 case OMPD_target:
6722 case OMPD_target_simd:
6723 case OMPD_target_parallel_for:
6724 case OMPD_target_parallel_for_simd:
6725 case OMPD_target_teams:
6726 case OMPD_target_teams_distribute:
6727 case OMPD_target_teams_distribute_simd:
6728 case OMPD_target_teams_distribute_parallel_for:
6729 case OMPD_target_teams_distribute_parallel_for_simd:
6730 case OMPD_teams_distribute_parallel_for:
6731 case OMPD_teams_distribute_parallel_for_simd:
6732 case OMPD_distribute_parallel_for:
6733 case OMPD_distribute_parallel_for_simd:
6734 case OMPD_task:
6735 case OMPD_taskloop:
6736 case OMPD_taskloop_simd:
6737 case OMPD_target_data:
6738 case OMPD_target_enter_data:
6739 case OMPD_target_exit_data:
6740 case OMPD_target_update:
6741 // Do not capture num_threads-clause expressions.
6742 break;
6743 case OMPD_threadprivate:
6744 case OMPD_taskyield:
6745 case OMPD_barrier:
6746 case OMPD_taskwait:
6747 case OMPD_cancellation_point:
6748 case OMPD_flush:
6749 case OMPD_declare_reduction:
6750 case OMPD_declare_simd:
6751 case OMPD_declare_target:
6752 case OMPD_end_declare_target:
6753 case OMPD_teams:
6754 case OMPD_simd:
6755 case OMPD_for:
6756 case OMPD_for_simd:
6757 case OMPD_sections:
6758 case OMPD_section:
6759 case OMPD_single:
6760 case OMPD_master:
6761 case OMPD_critical:
6762 case OMPD_taskgroup:
6763 case OMPD_distribute:
6764 case OMPD_ordered:
6765 case OMPD_atomic:
6766 case OMPD_distribute_simd:
6767 case OMPD_teams_distribute:
6768 case OMPD_teams_distribute_simd:
6769 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6770 case OMPD_unknown:
6771 llvm_unreachable("Unknown OpenMP directive");
6772 }
6773 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006774 case OMPC_schedule:
6775 case OMPC_dist_schedule:
6776 case OMPC_firstprivate:
6777 case OMPC_lastprivate:
6778 case OMPC_reduction:
6779 case OMPC_linear:
6780 case OMPC_default:
6781 case OMPC_proc_bind:
6782 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006783 case OMPC_safelen:
6784 case OMPC_simdlen:
6785 case OMPC_collapse:
6786 case OMPC_private:
6787 case OMPC_shared:
6788 case OMPC_aligned:
6789 case OMPC_copyin:
6790 case OMPC_copyprivate:
6791 case OMPC_ordered:
6792 case OMPC_nowait:
6793 case OMPC_untied:
6794 case OMPC_mergeable:
6795 case OMPC_threadprivate:
6796 case OMPC_flush:
6797 case OMPC_read:
6798 case OMPC_write:
6799 case OMPC_update:
6800 case OMPC_capture:
6801 case OMPC_seq_cst:
6802 case OMPC_depend:
6803 case OMPC_device:
6804 case OMPC_threads:
6805 case OMPC_simd:
6806 case OMPC_map:
6807 case OMPC_num_teams:
6808 case OMPC_thread_limit:
6809 case OMPC_priority:
6810 case OMPC_grainsize:
6811 case OMPC_nogroup:
6812 case OMPC_num_tasks:
6813 case OMPC_hint:
6814 case OMPC_defaultmap:
6815 case OMPC_unknown:
6816 case OMPC_uniform:
6817 case OMPC_to:
6818 case OMPC_from:
6819 case OMPC_use_device_ptr:
6820 case OMPC_is_device_ptr:
6821 llvm_unreachable("Unexpected OpenMP clause.");
6822 }
6823 return CaptureRegion;
6824}
6825
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006826OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6827 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006828 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006829 SourceLocation NameModifierLoc,
6830 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006831 SourceLocation EndLoc) {
6832 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006833 Stmt *HelperValStmt = nullptr;
6834 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006835 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6836 !Condition->isInstantiationDependent() &&
6837 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006838 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006839 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006840 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006841
Richard Smith03a4aa32016-06-23 19:02:52 +00006842 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006843
6844 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6845 CaptureRegion =
6846 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
6847 if (CaptureRegion != OMPD_unknown) {
6848 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6849 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6850 HelperValStmt = buildPreInits(Context, Captures);
6851 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006852 }
6853
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006854 return new (Context)
6855 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
6856 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006857}
6858
Alexey Bataev3778b602014-07-17 07:32:53 +00006859OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6860 SourceLocation StartLoc,
6861 SourceLocation LParenLoc,
6862 SourceLocation EndLoc) {
6863 Expr *ValExpr = Condition;
6864 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6865 !Condition->isInstantiationDependent() &&
6866 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006867 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006868 if (Val.isInvalid())
6869 return nullptr;
6870
Richard Smith03a4aa32016-06-23 19:02:52 +00006871 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006872 }
6873
6874 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6875}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006876ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6877 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006878 if (!Op)
6879 return ExprError();
6880
6881 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6882 public:
6883 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006884 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006885 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6886 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006887 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6888 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006889 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6890 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006891 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6892 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006893 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6894 QualType T,
6895 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006896 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6897 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006898 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6899 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006900 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006901 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006902 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006903 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6904 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006905 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6906 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006907 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6908 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006909 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006910 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006911 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006912 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6913 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006914 llvm_unreachable("conversion functions are permitted");
6915 }
6916 } ConvertDiagnoser;
6917 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6918}
6919
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006920static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006921 OpenMPClauseKind CKind,
6922 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006923 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6924 !ValExpr->isInstantiationDependent()) {
6925 SourceLocation Loc = ValExpr->getExprLoc();
6926 ExprResult Value =
6927 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6928 if (Value.isInvalid())
6929 return false;
6930
6931 ValExpr = Value.get();
6932 // The expression must evaluate to a non-negative integer value.
6933 llvm::APSInt Result;
6934 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006935 Result.isSigned() &&
6936 !((!StrictlyPositive && Result.isNonNegative()) ||
6937 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006938 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006939 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6940 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006941 return false;
6942 }
6943 }
6944 return true;
6945}
6946
Alexey Bataev568a8332014-03-06 06:15:19 +00006947OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6948 SourceLocation StartLoc,
6949 SourceLocation LParenLoc,
6950 SourceLocation EndLoc) {
6951 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006952 Stmt *HelperValStmt = nullptr;
6953 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00006954
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006955 // OpenMP [2.5, Restrictions]
6956 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006957 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6958 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006959 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006960
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006961 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6962 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
6963 if (CaptureRegion != OMPD_unknown) {
6964 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6965 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6966 HelperValStmt = buildPreInits(Context, Captures);
6967 }
6968
6969 return new (Context) OMPNumThreadsClause(
6970 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006971}
6972
Alexey Bataev62c87d22014-03-21 04:51:18 +00006973ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006974 OpenMPClauseKind CKind,
6975 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006976 if (!E)
6977 return ExprError();
6978 if (E->isValueDependent() || E->isTypeDependent() ||
6979 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006980 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006981 llvm::APSInt Result;
6982 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6983 if (ICE.isInvalid())
6984 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006985 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6986 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006987 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006988 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6989 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006990 return ExprError();
6991 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006992 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6993 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6994 << E->getSourceRange();
6995 return ExprError();
6996 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006997 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6998 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006999 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007000 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007001 return ICE;
7002}
7003
7004OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7005 SourceLocation LParenLoc,
7006 SourceLocation EndLoc) {
7007 // OpenMP [2.8.1, simd construct, Description]
7008 // The parameter of the safelen clause must be a constant
7009 // positive integer expression.
7010 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7011 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007012 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007013 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007014 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007015}
7016
Alexey Bataev66b15b52015-08-21 11:14:16 +00007017OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7018 SourceLocation LParenLoc,
7019 SourceLocation EndLoc) {
7020 // OpenMP [2.8.1, simd construct, Description]
7021 // The parameter of the simdlen clause must be a constant
7022 // positive integer expression.
7023 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7024 if (Simdlen.isInvalid())
7025 return nullptr;
7026 return new (Context)
7027 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7028}
7029
Alexander Musman64d33f12014-06-04 07:53:32 +00007030OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7031 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007032 SourceLocation LParenLoc,
7033 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007034 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007035 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007036 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007037 // The parameter of the collapse clause must be a constant
7038 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007039 ExprResult NumForLoopsResult =
7040 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7041 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007042 return nullptr;
7043 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007044 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007045}
7046
Alexey Bataev10e775f2015-07-30 11:36:16 +00007047OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7048 SourceLocation EndLoc,
7049 SourceLocation LParenLoc,
7050 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007051 // OpenMP [2.7.1, loop construct, Description]
7052 // OpenMP [2.8.1, simd construct, Description]
7053 // OpenMP [2.9.6, distribute construct, Description]
7054 // The parameter of the ordered clause must be a constant
7055 // positive integer expression if any.
7056 if (NumForLoops && LParenLoc.isValid()) {
7057 ExprResult NumForLoopsResult =
7058 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7059 if (NumForLoopsResult.isInvalid())
7060 return nullptr;
7061 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007062 } else
7063 NumForLoops = nullptr;
7064 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007065 return new (Context)
7066 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7067}
7068
Alexey Bataeved09d242014-05-28 05:53:51 +00007069OMPClause *Sema::ActOnOpenMPSimpleClause(
7070 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7071 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007072 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007073 switch (Kind) {
7074 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007075 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007076 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7077 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007078 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007079 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007080 Res = ActOnOpenMPProcBindClause(
7081 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7082 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007083 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007084 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007085 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007086 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007087 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007088 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007089 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007090 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007091 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007092 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007093 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007094 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007095 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007096 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007097 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007098 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007099 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007100 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007101 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007102 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007103 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007104 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007105 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007106 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007107 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007108 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007109 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007110 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007111 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007112 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007113 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007114 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007115 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007116 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007117 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007118 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007119 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007120 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007121 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007122 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007123 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007124 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007125 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007126 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007127 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007128 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007129 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007130 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007131 llvm_unreachable("Clause is not allowed.");
7132 }
7133 return Res;
7134}
7135
Alexey Bataev6402bca2015-12-28 07:25:51 +00007136static std::string
7137getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7138 ArrayRef<unsigned> Exclude = llvm::None) {
7139 std::string Values;
7140 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7141 unsigned Skipped = Exclude.size();
7142 auto S = Exclude.begin(), E = Exclude.end();
7143 for (unsigned i = First; i < Last; ++i) {
7144 if (std::find(S, E, i) != E) {
7145 --Skipped;
7146 continue;
7147 }
7148 Values += "'";
7149 Values += getOpenMPSimpleClauseTypeName(K, i);
7150 Values += "'";
7151 if (i == Bound - Skipped)
7152 Values += " or ";
7153 else if (i != Bound + 1 - Skipped)
7154 Values += ", ";
7155 }
7156 return Values;
7157}
7158
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007159OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7160 SourceLocation KindKwLoc,
7161 SourceLocation StartLoc,
7162 SourceLocation LParenLoc,
7163 SourceLocation EndLoc) {
7164 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007165 static_assert(OMPC_DEFAULT_unknown > 0,
7166 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007167 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007168 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7169 /*Last=*/OMPC_DEFAULT_unknown)
7170 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007171 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007172 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007173 switch (Kind) {
7174 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007175 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007176 break;
7177 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007178 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007179 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007180 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007181 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007182 break;
7183 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007184 return new (Context)
7185 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007186}
7187
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007188OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7189 SourceLocation KindKwLoc,
7190 SourceLocation StartLoc,
7191 SourceLocation LParenLoc,
7192 SourceLocation EndLoc) {
7193 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007194 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007195 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7196 /*Last=*/OMPC_PROC_BIND_unknown)
7197 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007198 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007199 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007200 return new (Context)
7201 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007202}
7203
Alexey Bataev56dafe82014-06-20 07:16:17 +00007204OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007205 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007206 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007207 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007208 SourceLocation EndLoc) {
7209 OMPClause *Res = nullptr;
7210 switch (Kind) {
7211 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007212 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7213 assert(Argument.size() == NumberOfElements &&
7214 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007215 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007216 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7217 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7218 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7219 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7220 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007221 break;
7222 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007223 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7224 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7225 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7226 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007227 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007228 case OMPC_dist_schedule:
7229 Res = ActOnOpenMPDistScheduleClause(
7230 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7231 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7232 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007233 case OMPC_defaultmap:
7234 enum { Modifier, DefaultmapKind };
7235 Res = ActOnOpenMPDefaultmapClause(
7236 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7237 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007238 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7239 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007240 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007241 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007242 case OMPC_num_threads:
7243 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007244 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007245 case OMPC_collapse:
7246 case OMPC_default:
7247 case OMPC_proc_bind:
7248 case OMPC_private:
7249 case OMPC_firstprivate:
7250 case OMPC_lastprivate:
7251 case OMPC_shared:
7252 case OMPC_reduction:
7253 case OMPC_linear:
7254 case OMPC_aligned:
7255 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007256 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007257 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007258 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007259 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007260 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007261 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007262 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007263 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007264 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007265 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007266 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007267 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007268 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007269 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007270 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007271 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007272 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007273 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007274 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007275 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007276 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007277 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007278 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007279 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007280 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007281 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007282 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007283 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007284 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007285 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007286 llvm_unreachable("Clause is not allowed.");
7287 }
7288 return Res;
7289}
7290
Alexey Bataev6402bca2015-12-28 07:25:51 +00007291static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7292 OpenMPScheduleClauseModifier M2,
7293 SourceLocation M1Loc, SourceLocation M2Loc) {
7294 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7295 SmallVector<unsigned, 2> Excluded;
7296 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7297 Excluded.push_back(M2);
7298 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7299 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7300 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7301 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7302 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7303 << getListOfPossibleValues(OMPC_schedule,
7304 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7305 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7306 Excluded)
7307 << getOpenMPClauseName(OMPC_schedule);
7308 return true;
7309 }
7310 return false;
7311}
7312
Alexey Bataev56dafe82014-06-20 07:16:17 +00007313OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007314 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007315 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007316 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7317 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7318 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7319 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7320 return nullptr;
7321 // OpenMP, 2.7.1, Loop Construct, Restrictions
7322 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7323 // but not both.
7324 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7325 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7326 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7327 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7328 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7329 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7330 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7331 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7332 return nullptr;
7333 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007334 if (Kind == OMPC_SCHEDULE_unknown) {
7335 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007336 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7337 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7338 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7339 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7340 Exclude);
7341 } else {
7342 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7343 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007344 }
7345 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7346 << Values << getOpenMPClauseName(OMPC_schedule);
7347 return nullptr;
7348 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007349 // OpenMP, 2.7.1, Loop Construct, Restrictions
7350 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7351 // schedule(guided).
7352 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7353 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7354 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7355 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7356 diag::err_omp_schedule_nonmonotonic_static);
7357 return nullptr;
7358 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007359 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007360 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007361 if (ChunkSize) {
7362 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7363 !ChunkSize->isInstantiationDependent() &&
7364 !ChunkSize->containsUnexpandedParameterPack()) {
7365 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7366 ExprResult Val =
7367 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7368 if (Val.isInvalid())
7369 return nullptr;
7370
7371 ValExpr = Val.get();
7372
7373 // OpenMP [2.7.1, Restrictions]
7374 // chunk_size must be a loop invariant integer expression with a positive
7375 // value.
7376 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007377 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7378 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7379 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007380 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007381 return nullptr;
7382 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007383 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7384 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007385 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7386 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7387 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007388 }
7389 }
7390 }
7391
Alexey Bataev6402bca2015-12-28 07:25:51 +00007392 return new (Context)
7393 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007394 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007395}
7396
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007397OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7398 SourceLocation StartLoc,
7399 SourceLocation EndLoc) {
7400 OMPClause *Res = nullptr;
7401 switch (Kind) {
7402 case OMPC_ordered:
7403 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7404 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007405 case OMPC_nowait:
7406 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7407 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007408 case OMPC_untied:
7409 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7410 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007411 case OMPC_mergeable:
7412 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7413 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007414 case OMPC_read:
7415 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7416 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007417 case OMPC_write:
7418 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7419 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007420 case OMPC_update:
7421 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7422 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007423 case OMPC_capture:
7424 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7425 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007426 case OMPC_seq_cst:
7427 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7428 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007429 case OMPC_threads:
7430 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7431 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007432 case OMPC_simd:
7433 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7434 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007435 case OMPC_nogroup:
7436 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7437 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007438 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007439 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007440 case OMPC_num_threads:
7441 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007442 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007443 case OMPC_collapse:
7444 case OMPC_schedule:
7445 case OMPC_private:
7446 case OMPC_firstprivate:
7447 case OMPC_lastprivate:
7448 case OMPC_shared:
7449 case OMPC_reduction:
7450 case OMPC_linear:
7451 case OMPC_aligned:
7452 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007453 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007454 case OMPC_default:
7455 case OMPC_proc_bind:
7456 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007457 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007458 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007459 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007460 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007461 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007462 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007463 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007464 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007465 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007466 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007467 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007468 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007469 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007470 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007471 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007472 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007473 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007474 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007475 llvm_unreachable("Clause is not allowed.");
7476 }
7477 return Res;
7478}
7479
Alexey Bataev236070f2014-06-20 11:19:47 +00007480OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7481 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007482 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007483 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7484}
7485
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007486OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7487 SourceLocation EndLoc) {
7488 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7489}
7490
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007491OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7492 SourceLocation EndLoc) {
7493 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7494}
7495
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007496OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7497 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007498 return new (Context) OMPReadClause(StartLoc, EndLoc);
7499}
7500
Alexey Bataevdea47612014-07-23 07:46:59 +00007501OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7502 SourceLocation EndLoc) {
7503 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7504}
7505
Alexey Bataev67a4f222014-07-23 10:25:33 +00007506OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7507 SourceLocation EndLoc) {
7508 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7509}
7510
Alexey Bataev459dec02014-07-24 06:46:57 +00007511OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7512 SourceLocation EndLoc) {
7513 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7514}
7515
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007516OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7517 SourceLocation EndLoc) {
7518 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7519}
7520
Alexey Bataev346265e2015-09-25 10:37:12 +00007521OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7522 SourceLocation EndLoc) {
7523 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7524}
7525
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007526OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7527 SourceLocation EndLoc) {
7528 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7529}
7530
Alexey Bataevb825de12015-12-07 10:51:44 +00007531OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7532 SourceLocation EndLoc) {
7533 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7534}
7535
Alexey Bataevc5e02582014-06-16 07:08:35 +00007536OMPClause *Sema::ActOnOpenMPVarListClause(
7537 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7538 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7539 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007540 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007541 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7542 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7543 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007544 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007545 switch (Kind) {
7546 case OMPC_private:
7547 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7548 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007549 case OMPC_firstprivate:
7550 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7551 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007552 case OMPC_lastprivate:
7553 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7554 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007555 case OMPC_shared:
7556 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7557 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007558 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007559 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7560 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007561 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007562 case OMPC_linear:
7563 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007564 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007565 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007566 case OMPC_aligned:
7567 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7568 ColonLoc, EndLoc);
7569 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007570 case OMPC_copyin:
7571 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7572 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007573 case OMPC_copyprivate:
7574 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7575 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007576 case OMPC_flush:
7577 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7578 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007579 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007580 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007581 StartLoc, LParenLoc, EndLoc);
7582 break;
7583 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007584 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7585 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7586 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007587 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007588 case OMPC_to:
7589 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7590 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007591 case OMPC_from:
7592 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7593 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007594 case OMPC_use_device_ptr:
7595 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7596 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007597 case OMPC_is_device_ptr:
7598 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7599 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007600 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007601 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007602 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007603 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007604 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007605 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007606 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007607 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007608 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007609 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007610 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007611 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007612 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007613 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007614 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007615 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007616 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007617 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007618 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007619 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007620 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007621 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007622 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007623 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007624 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007625 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007626 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007627 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007628 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007629 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007630 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007631 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007632 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007633 llvm_unreachable("Clause is not allowed.");
7634 }
7635 return Res;
7636}
7637
Alexey Bataev90c228f2016-02-08 09:29:13 +00007638ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007639 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007640 ExprResult Res = BuildDeclRefExpr(
7641 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7642 if (!Res.isUsable())
7643 return ExprError();
7644 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7645 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7646 if (!Res.isUsable())
7647 return ExprError();
7648 }
7649 if (VK != VK_LValue && Res.get()->isGLValue()) {
7650 Res = DefaultLvalueConversion(Res.get());
7651 if (!Res.isUsable())
7652 return ExprError();
7653 }
7654 return Res;
7655}
7656
Alexey Bataev60da77e2016-02-29 05:54:20 +00007657static std::pair<ValueDecl *, bool>
7658getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7659 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007660 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7661 RefExpr->containsUnexpandedParameterPack())
7662 return std::make_pair(nullptr, true);
7663
Alexey Bataevd985eda2016-02-10 11:29:16 +00007664 // OpenMP [3.1, C/C++]
7665 // A list item is a variable name.
7666 // OpenMP [2.9.3.3, Restrictions, p.1]
7667 // A variable that is part of another variable (as an array or
7668 // structure element) cannot appear in a private clause.
7669 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007670 enum {
7671 NoArrayExpr = -1,
7672 ArraySubscript = 0,
7673 OMPArraySection = 1
7674 } IsArrayExpr = NoArrayExpr;
7675 if (AllowArraySection) {
7676 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7677 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7678 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7679 Base = TempASE->getBase()->IgnoreParenImpCasts();
7680 RefExpr = Base;
7681 IsArrayExpr = ArraySubscript;
7682 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7683 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7684 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7685 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7686 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7687 Base = TempASE->getBase()->IgnoreParenImpCasts();
7688 RefExpr = Base;
7689 IsArrayExpr = OMPArraySection;
7690 }
7691 }
7692 ELoc = RefExpr->getExprLoc();
7693 ERange = RefExpr->getSourceRange();
7694 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007695 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7696 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7697 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7698 (S.getCurrentThisType().isNull() || !ME ||
7699 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7700 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007701 if (IsArrayExpr != NoArrayExpr)
7702 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7703 << ERange;
7704 else {
7705 S.Diag(ELoc,
7706 AllowArraySection
7707 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7708 : diag::err_omp_expected_var_name_member_expr)
7709 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7710 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007711 return std::make_pair(nullptr, false);
7712 }
7713 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7714}
7715
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007716OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7717 SourceLocation StartLoc,
7718 SourceLocation LParenLoc,
7719 SourceLocation EndLoc) {
7720 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007721 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007722 for (auto &RefExpr : VarList) {
7723 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007724 SourceLocation ELoc;
7725 SourceRange ERange;
7726 Expr *SimpleRefExpr = RefExpr;
7727 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007728 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007729 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007730 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007731 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007732 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007733 ValueDecl *D = Res.first;
7734 if (!D)
7735 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007736
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007737 QualType Type = D->getType();
7738 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007739
7740 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7741 // A variable that appears in a private clause must not have an incomplete
7742 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007743 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007744 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007745 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007746
Alexey Bataev758e55e2013-09-06 18:03:48 +00007747 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7748 // in a Construct]
7749 // Variables with the predetermined data-sharing attributes may not be
7750 // listed in data-sharing attributes clauses, except for the cases
7751 // listed below. For these exceptions only, listing a predetermined
7752 // variable in a data-sharing attribute clause is allowed and overrides
7753 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007754 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007755 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007756 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7757 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007758 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007759 continue;
7760 }
7761
Kelvin Libf594a52016-12-17 05:48:59 +00007762 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007763 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007764 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007765 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007766 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7767 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007768 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007769 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007770 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007771 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007772 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007773 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007774 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007775 continue;
7776 }
7777
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007778 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7779 // A list item cannot appear in both a map clause and a data-sharing
7780 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007781 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007782 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007783 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007784 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007785 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007786 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007787 CurrDir == OMPD_target_parallel_for_simd ||
7788 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007789 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007790 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007791 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007792 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7793 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7794 ConflictKind = WhereFoundClauseKind;
7795 return true;
7796 })) {
7797 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007798 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007799 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007800 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007801 ReportOriginalDSA(*this, DSAStack, D, DVar);
7802 continue;
7803 }
7804 }
7805
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007806 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7807 // A variable of class type (or array thereof) that appears in a private
7808 // clause requires an accessible, unambiguous default constructor for the
7809 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007810 // Generate helper private variable and initialize it with the default
7811 // value. The address of the original variable is replaced by the address of
7812 // the new private variable in CodeGen. This new variable is not added to
7813 // IdResolver, so the code in the OpenMP region uses original variable for
7814 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007815 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007816 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7817 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00007818 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007819 if (VDPrivate->isInvalidDecl())
7820 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007821 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007822 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007823
Alexey Bataev90c228f2016-02-08 09:29:13 +00007824 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007825 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007826 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007827 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007828 Vars.push_back((VD || CurContext->isDependentContext())
7829 ? RefExpr->IgnoreParens()
7830 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007831 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007832 }
7833
Alexey Bataeved09d242014-05-28 05:53:51 +00007834 if (Vars.empty())
7835 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007836
Alexey Bataev03b340a2014-10-21 03:16:40 +00007837 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7838 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007839}
7840
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007841namespace {
7842class DiagsUninitializedSeveretyRAII {
7843private:
7844 DiagnosticsEngine &Diags;
7845 SourceLocation SavedLoc;
7846 bool IsIgnored;
7847
7848public:
7849 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7850 bool IsIgnored)
7851 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7852 if (!IsIgnored) {
7853 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7854 /*Map*/ diag::Severity::Ignored, Loc);
7855 }
7856 }
7857 ~DiagsUninitializedSeveretyRAII() {
7858 if (!IsIgnored)
7859 Diags.popMappings(SavedLoc);
7860 }
7861};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007862}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007863
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007864OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7865 SourceLocation StartLoc,
7866 SourceLocation LParenLoc,
7867 SourceLocation EndLoc) {
7868 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007869 SmallVector<Expr *, 8> PrivateCopies;
7870 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007871 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007872 bool IsImplicitClause =
7873 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7874 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7875
Alexey Bataeved09d242014-05-28 05:53:51 +00007876 for (auto &RefExpr : VarList) {
7877 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007878 SourceLocation ELoc;
7879 SourceRange ERange;
7880 Expr *SimpleRefExpr = RefExpr;
7881 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007882 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007883 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007884 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007885 PrivateCopies.push_back(nullptr);
7886 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007887 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007888 ValueDecl *D = Res.first;
7889 if (!D)
7890 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007891
Alexey Bataev60da77e2016-02-29 05:54:20 +00007892 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007893 QualType Type = D->getType();
7894 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007895
7896 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7897 // A variable that appears in a private clause must not have an incomplete
7898 // type or a reference type.
7899 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007900 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007901 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007902 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007903
7904 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7905 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007906 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007907 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007908 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007909
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007910 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007911 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007912 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007913 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007914 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007915 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007916 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7917 // A list item that specifies a given variable may not appear in more
7918 // than one clause on the same directive, except that a variable may be
7919 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007920 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007921 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007922 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007923 << getOpenMPClauseName(DVar.CKind)
7924 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007925 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007926 continue;
7927 }
7928
7929 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7930 // in a Construct]
7931 // Variables with the predetermined data-sharing attributes may not be
7932 // listed in data-sharing attributes clauses, except for the cases
7933 // listed below. For these exceptions only, listing a predetermined
7934 // variable in a data-sharing attribute clause is allowed and overrides
7935 // the variable's predetermined data-sharing attributes.
7936 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7937 // in a Construct, C/C++, p.2]
7938 // Variables with const-qualified type having no mutable member may be
7939 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007940 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007941 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7942 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007943 << getOpenMPClauseName(DVar.CKind)
7944 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007945 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007946 continue;
7947 }
7948
Alexey Bataevf29276e2014-06-18 04:14:57 +00007949 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007950 // OpenMP [2.9.3.4, Restrictions, p.2]
7951 // A list item that is private within a parallel region must not appear
7952 // in a firstprivate clause on a worksharing construct if any of the
7953 // worksharing regions arising from the worksharing construct ever bind
7954 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007955 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007956 !isOpenMPParallelDirective(CurrDir) &&
7957 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007958 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007959 if (DVar.CKind != OMPC_shared &&
7960 (isOpenMPParallelDirective(DVar.DKind) ||
7961 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007962 Diag(ELoc, diag::err_omp_required_access)
7963 << getOpenMPClauseName(OMPC_firstprivate)
7964 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007965 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007966 continue;
7967 }
7968 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007969 // OpenMP [2.9.3.4, Restrictions, p.3]
7970 // A list item that appears in a reduction clause of a parallel construct
7971 // must not appear in a firstprivate clause on a worksharing or task
7972 // construct if any of the worksharing or task regions arising from the
7973 // worksharing or task construct ever bind to any of the parallel regions
7974 // arising from the parallel construct.
7975 // OpenMP [2.9.3.4, Restrictions, p.4]
7976 // A list item that appears in a reduction clause in worksharing
7977 // construct must not appear in a firstprivate clause in a task construct
7978 // encountered during execution of any of the worksharing regions arising
7979 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007980 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007981 DVar = DSAStack->hasInnermostDSA(
7982 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7983 [](OpenMPDirectiveKind K) -> bool {
7984 return isOpenMPParallelDirective(K) ||
7985 isOpenMPWorksharingDirective(K);
7986 },
7987 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007988 if (DVar.CKind == OMPC_reduction &&
7989 (isOpenMPParallelDirective(DVar.DKind) ||
7990 isOpenMPWorksharingDirective(DVar.DKind))) {
7991 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7992 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007993 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007994 continue;
7995 }
7996 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007997
7998 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7999 // A list item that is private within a teams region must not appear in a
8000 // firstprivate clause on a distribute construct if any of the distribute
8001 // regions arising from the distribute construct ever bind to any of the
8002 // teams regions arising from the teams construct.
8003 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8004 // A list item that appears in a reduction clause of a teams construct
8005 // must not appear in a firstprivate clause on a distribute construct if
8006 // any of the distribute regions arising from the distribute construct
8007 // ever bind to any of the teams regions arising from the teams construct.
8008 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8009 // A list item may appear in a firstprivate or lastprivate clause but not
8010 // both.
8011 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008012 DVar = DSAStack->hasInnermostDSA(
8013 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8014 [](OpenMPDirectiveKind K) -> bool {
8015 return isOpenMPTeamsDirective(K);
8016 },
8017 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008018 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8019 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008020 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008021 continue;
8022 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008023 DVar = DSAStack->hasInnermostDSA(
8024 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8025 [](OpenMPDirectiveKind K) -> bool {
8026 return isOpenMPTeamsDirective(K);
8027 },
8028 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008029 if (DVar.CKind == OMPC_reduction &&
8030 isOpenMPTeamsDirective(DVar.DKind)) {
8031 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008032 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008033 continue;
8034 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008035 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008036 if (DVar.CKind == OMPC_lastprivate) {
8037 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008038 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008039 continue;
8040 }
8041 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008042 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8043 // A list item cannot appear in both a map clause and a data-sharing
8044 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008045 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008046 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008047 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008048 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008049 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008050 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008051 CurrDir == OMPD_target_parallel_for_simd ||
8052 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008053 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008054 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008055 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008056 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8057 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8058 ConflictKind = WhereFoundClauseKind;
8059 return true;
8060 })) {
8061 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008062 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008063 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008064 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8065 ReportOriginalDSA(*this, DSAStack, D, DVar);
8066 continue;
8067 }
8068 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008069 }
8070
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008071 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008072 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008073 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008074 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8075 << getOpenMPClauseName(OMPC_firstprivate) << Type
8076 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8077 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008078 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008079 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008080 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008081 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008082 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008083 continue;
8084 }
8085
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008086 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008087 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8088 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008089 // Generate helper private variable and initialize it with the value of the
8090 // original variable. The address of the original variable is replaced by
8091 // the address of the new private variable in the CodeGen. This new variable
8092 // is not added to IdResolver, so the code in the OpenMP region uses
8093 // original variable for proper diagnostics and variable capturing.
8094 Expr *VDInitRefExpr = nullptr;
8095 // For arrays generate initializer for single element and replace it by the
8096 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008097 if (Type->isArrayType()) {
8098 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008099 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008100 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008101 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008102 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008103 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008104 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008105 InitializedEntity Entity =
8106 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008107 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8108
8109 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8110 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8111 if (Result.isInvalid())
8112 VDPrivate->setInvalidDecl();
8113 else
8114 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008115 // Remove temp variable declaration.
8116 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008117 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008118 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8119 ".firstprivate.temp");
8120 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8121 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008122 AddInitializerToDecl(VDPrivate,
8123 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008124 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008125 }
8126 if (VDPrivate->isInvalidDecl()) {
8127 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008128 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008129 diag::note_omp_task_predetermined_firstprivate_here);
8130 }
8131 continue;
8132 }
8133 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008134 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008135 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8136 RefExpr->getExprLoc());
8137 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008138 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008139 if (TopDVar.CKind == OMPC_lastprivate)
8140 Ref = TopDVar.PrivateCopy;
8141 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008142 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008143 if (!IsOpenMPCapturedDecl(D))
8144 ExprCaptures.push_back(Ref->getDecl());
8145 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008146 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008147 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008148 Vars.push_back((VD || CurContext->isDependentContext())
8149 ? RefExpr->IgnoreParens()
8150 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008151 PrivateCopies.push_back(VDPrivateRefExpr);
8152 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008153 }
8154
Alexey Bataeved09d242014-05-28 05:53:51 +00008155 if (Vars.empty())
8156 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008157
8158 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008159 Vars, PrivateCopies, Inits,
8160 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008161}
8162
Alexander Musman1bb328c2014-06-04 13:06:39 +00008163OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8164 SourceLocation StartLoc,
8165 SourceLocation LParenLoc,
8166 SourceLocation EndLoc) {
8167 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008168 SmallVector<Expr *, 8> SrcExprs;
8169 SmallVector<Expr *, 8> DstExprs;
8170 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008171 SmallVector<Decl *, 4> ExprCaptures;
8172 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008173 for (auto &RefExpr : VarList) {
8174 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008175 SourceLocation ELoc;
8176 SourceRange ERange;
8177 Expr *SimpleRefExpr = RefExpr;
8178 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008179 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008180 // It will be analyzed later.
8181 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008182 SrcExprs.push_back(nullptr);
8183 DstExprs.push_back(nullptr);
8184 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008185 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008186 ValueDecl *D = Res.first;
8187 if (!D)
8188 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008189
Alexey Bataev74caaf22016-02-20 04:09:36 +00008190 QualType Type = D->getType();
8191 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008192
8193 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8194 // A variable that appears in a lastprivate clause must not have an
8195 // incomplete type or a reference type.
8196 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008197 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008198 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008199 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008200
8201 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8202 // in a Construct]
8203 // Variables with the predetermined data-sharing attributes may not be
8204 // listed in data-sharing attributes clauses, except for the cases
8205 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008206 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008207 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8208 DVar.CKind != OMPC_firstprivate &&
8209 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8210 Diag(ELoc, diag::err_omp_wrong_dsa)
8211 << getOpenMPClauseName(DVar.CKind)
8212 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008213 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008214 continue;
8215 }
8216
Alexey Bataevf29276e2014-06-18 04:14:57 +00008217 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8218 // OpenMP [2.14.3.5, Restrictions, p.2]
8219 // A list item that is private within a parallel region, or that appears in
8220 // the reduction clause of a parallel construct, must not appear in a
8221 // lastprivate clause on a worksharing construct if any of the corresponding
8222 // worksharing regions ever binds to any of the corresponding parallel
8223 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008224 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008225 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008226 !isOpenMPParallelDirective(CurrDir) &&
8227 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008228 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008229 if (DVar.CKind != OMPC_shared) {
8230 Diag(ELoc, diag::err_omp_required_access)
8231 << getOpenMPClauseName(OMPC_lastprivate)
8232 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008233 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008234 continue;
8235 }
8236 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008237
8238 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8239 // A list item may appear in a firstprivate or lastprivate clause but not
8240 // both.
8241 if (CurrDir == OMPD_distribute) {
8242 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8243 if (DVar.CKind == OMPC_firstprivate) {
8244 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8245 ReportOriginalDSA(*this, DSAStack, D, DVar);
8246 continue;
8247 }
8248 }
8249
Alexander Musman1bb328c2014-06-04 13:06:39 +00008250 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008251 // A variable of class type (or array thereof) that appears in a
8252 // lastprivate clause requires an accessible, unambiguous default
8253 // constructor for the class type, unless the list item is also specified
8254 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008255 // A variable of class type (or array thereof) that appears in a
8256 // lastprivate clause requires an accessible, unambiguous copy assignment
8257 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008258 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008259 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008260 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008261 D->hasAttrs() ? &D->getAttrs() : nullptr);
8262 auto *PseudoSrcExpr =
8263 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008264 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008265 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008266 D->hasAttrs() ? &D->getAttrs() : nullptr);
8267 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008268 // For arrays generate assignment operation for single element and replace
8269 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008270 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008271 PseudoDstExpr, PseudoSrcExpr);
8272 if (AssignmentOp.isInvalid())
8273 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008274 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008275 /*DiscardedValue=*/true);
8276 if (AssignmentOp.isInvalid())
8277 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008278
Alexey Bataev74caaf22016-02-20 04:09:36 +00008279 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008280 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008281 if (TopDVar.CKind == OMPC_firstprivate)
8282 Ref = TopDVar.PrivateCopy;
8283 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008284 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008285 if (!IsOpenMPCapturedDecl(D))
8286 ExprCaptures.push_back(Ref->getDecl());
8287 }
8288 if (TopDVar.CKind == OMPC_firstprivate ||
8289 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008290 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008291 ExprResult RefRes = DefaultLvalueConversion(Ref);
8292 if (!RefRes.isUsable())
8293 continue;
8294 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008295 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8296 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008297 if (!PostUpdateRes.isUsable())
8298 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008299 ExprPostUpdates.push_back(
8300 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008301 }
8302 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008303 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008304 Vars.push_back((VD || CurContext->isDependentContext())
8305 ? RefExpr->IgnoreParens()
8306 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008307 SrcExprs.push_back(PseudoSrcExpr);
8308 DstExprs.push_back(PseudoDstExpr);
8309 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008310 }
8311
8312 if (Vars.empty())
8313 return nullptr;
8314
8315 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008316 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008317 buildPreInits(Context, ExprCaptures),
8318 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008319}
8320
Alexey Bataev758e55e2013-09-06 18:03:48 +00008321OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8322 SourceLocation StartLoc,
8323 SourceLocation LParenLoc,
8324 SourceLocation EndLoc) {
8325 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008326 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008327 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008328 SourceLocation ELoc;
8329 SourceRange ERange;
8330 Expr *SimpleRefExpr = RefExpr;
8331 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008332 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008333 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008334 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008335 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008336 ValueDecl *D = Res.first;
8337 if (!D)
8338 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008339
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008340 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008341 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8342 // in a Construct]
8343 // Variables with the predetermined data-sharing attributes may not be
8344 // listed in data-sharing attributes clauses, except for the cases
8345 // listed below. For these exceptions only, listing a predetermined
8346 // variable in a data-sharing attribute clause is allowed and overrides
8347 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008348 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008349 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8350 DVar.RefExpr) {
8351 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8352 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008353 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008354 continue;
8355 }
8356
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008357 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008358 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008359 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008360 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008361 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8362 ? RefExpr->IgnoreParens()
8363 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008364 }
8365
Alexey Bataeved09d242014-05-28 05:53:51 +00008366 if (Vars.empty())
8367 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008368
8369 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8370}
8371
Alexey Bataevc5e02582014-06-16 07:08:35 +00008372namespace {
8373class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8374 DSAStackTy *Stack;
8375
8376public:
8377 bool VisitDeclRefExpr(DeclRefExpr *E) {
8378 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008379 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008380 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8381 return false;
8382 if (DVar.CKind != OMPC_unknown)
8383 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008384 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8385 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8386 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008387 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008388 return true;
8389 return false;
8390 }
8391 return false;
8392 }
8393 bool VisitStmt(Stmt *S) {
8394 for (auto Child : S->children()) {
8395 if (Child && Visit(Child))
8396 return true;
8397 }
8398 return false;
8399 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008400 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008401};
Alexey Bataev23b69422014-06-18 07:08:49 +00008402} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008403
Alexey Bataev60da77e2016-02-29 05:54:20 +00008404namespace {
8405// Transform MemberExpression for specified FieldDecl of current class to
8406// DeclRefExpr to specified OMPCapturedExprDecl.
8407class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8408 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8409 ValueDecl *Field;
8410 DeclRefExpr *CapturedExpr;
8411
8412public:
8413 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8414 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8415
8416 ExprResult TransformMemberExpr(MemberExpr *E) {
8417 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8418 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008419 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008420 return CapturedExpr;
8421 }
8422 return BaseTransform::TransformMemberExpr(E);
8423 }
8424 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8425};
8426} // namespace
8427
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008428template <typename T>
8429static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8430 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8431 for (auto &Set : Lookups) {
8432 for (auto *D : Set) {
8433 if (auto Res = Gen(cast<ValueDecl>(D)))
8434 return Res;
8435 }
8436 }
8437 return T();
8438}
8439
8440static ExprResult
8441buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8442 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8443 const DeclarationNameInfo &ReductionId, QualType Ty,
8444 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8445 if (ReductionIdScopeSpec.isInvalid())
8446 return ExprError();
8447 SmallVector<UnresolvedSet<8>, 4> Lookups;
8448 if (S) {
8449 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8450 Lookup.suppressDiagnostics();
8451 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8452 auto *D = Lookup.getRepresentativeDecl();
8453 do {
8454 S = S->getParent();
8455 } while (S && !S->isDeclScope(D));
8456 if (S)
8457 S = S->getParent();
8458 Lookups.push_back(UnresolvedSet<8>());
8459 Lookups.back().append(Lookup.begin(), Lookup.end());
8460 Lookup.clear();
8461 }
8462 } else if (auto *ULE =
8463 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8464 Lookups.push_back(UnresolvedSet<8>());
8465 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008466 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008467 if (D == PrevD)
8468 Lookups.push_back(UnresolvedSet<8>());
8469 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8470 Lookups.back().addDecl(DRD);
8471 PrevD = D;
8472 }
8473 }
8474 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8475 Ty->containsUnexpandedParameterPack() ||
8476 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8477 return !D->isInvalidDecl() &&
8478 (D->getType()->isDependentType() ||
8479 D->getType()->isInstantiationDependentType() ||
8480 D->getType()->containsUnexpandedParameterPack());
8481 })) {
8482 UnresolvedSet<8> ResSet;
8483 for (auto &Set : Lookups) {
8484 ResSet.append(Set.begin(), Set.end());
8485 // The last item marks the end of all declarations at the specified scope.
8486 ResSet.addDecl(Set[Set.size() - 1]);
8487 }
8488 return UnresolvedLookupExpr::Create(
8489 SemaRef.Context, /*NamingClass=*/nullptr,
8490 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8491 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8492 }
8493 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8494 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8495 if (!D->isInvalidDecl() &&
8496 SemaRef.Context.hasSameType(D->getType(), Ty))
8497 return D;
8498 return nullptr;
8499 }))
8500 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8501 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8502 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8503 if (!D->isInvalidDecl() &&
8504 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8505 !Ty.isMoreQualifiedThan(D->getType()))
8506 return D;
8507 return nullptr;
8508 })) {
8509 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8510 /*DetectVirtual=*/false);
8511 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8512 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8513 VD->getType().getUnqualifiedType()))) {
8514 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8515 /*DiagID=*/0) !=
8516 Sema::AR_inaccessible) {
8517 SemaRef.BuildBasePathArray(Paths, BasePath);
8518 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8519 }
8520 }
8521 }
8522 }
8523 if (ReductionIdScopeSpec.isSet()) {
8524 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8525 return ExprError();
8526 }
8527 return ExprEmpty();
8528}
8529
Alexey Bataevc5e02582014-06-16 07:08:35 +00008530OMPClause *Sema::ActOnOpenMPReductionClause(
8531 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8532 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008533 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8534 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008535 auto DN = ReductionId.getName();
8536 auto OOK = DN.getCXXOverloadedOperator();
8537 BinaryOperatorKind BOK = BO_Comma;
8538
8539 // OpenMP [2.14.3.6, reduction clause]
8540 // C
8541 // reduction-identifier is either an identifier or one of the following
8542 // operators: +, -, *, &, |, ^, && and ||
8543 // C++
8544 // reduction-identifier is either an id-expression or one of the following
8545 // operators: +, -, *, &, |, ^, && and ||
8546 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8547 switch (OOK) {
8548 case OO_Plus:
8549 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008550 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008551 break;
8552 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008553 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008554 break;
8555 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008556 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008557 break;
8558 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008559 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008560 break;
8561 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008562 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008563 break;
8564 case OO_AmpAmp:
8565 BOK = BO_LAnd;
8566 break;
8567 case OO_PipePipe:
8568 BOK = BO_LOr;
8569 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008570 case OO_New:
8571 case OO_Delete:
8572 case OO_Array_New:
8573 case OO_Array_Delete:
8574 case OO_Slash:
8575 case OO_Percent:
8576 case OO_Tilde:
8577 case OO_Exclaim:
8578 case OO_Equal:
8579 case OO_Less:
8580 case OO_Greater:
8581 case OO_LessEqual:
8582 case OO_GreaterEqual:
8583 case OO_PlusEqual:
8584 case OO_MinusEqual:
8585 case OO_StarEqual:
8586 case OO_SlashEqual:
8587 case OO_PercentEqual:
8588 case OO_CaretEqual:
8589 case OO_AmpEqual:
8590 case OO_PipeEqual:
8591 case OO_LessLess:
8592 case OO_GreaterGreater:
8593 case OO_LessLessEqual:
8594 case OO_GreaterGreaterEqual:
8595 case OO_EqualEqual:
8596 case OO_ExclaimEqual:
8597 case OO_PlusPlus:
8598 case OO_MinusMinus:
8599 case OO_Comma:
8600 case OO_ArrowStar:
8601 case OO_Arrow:
8602 case OO_Call:
8603 case OO_Subscript:
8604 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008605 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008606 case NUM_OVERLOADED_OPERATORS:
8607 llvm_unreachable("Unexpected reduction identifier");
8608 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008609 if (auto II = DN.getAsIdentifierInfo()) {
8610 if (II->isStr("max"))
8611 BOK = BO_GT;
8612 else if (II->isStr("min"))
8613 BOK = BO_LT;
8614 }
8615 break;
8616 }
8617 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008618 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008619 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008620 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008621
8622 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008623 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008624 SmallVector<Expr *, 8> LHSs;
8625 SmallVector<Expr *, 8> RHSs;
8626 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008627 SmallVector<Decl *, 4> ExprCaptures;
8628 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008629 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8630 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008631 for (auto RefExpr : VarList) {
8632 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008633 // OpenMP [2.1, C/C++]
8634 // A list item is a variable or array section, subject to the restrictions
8635 // specified in Section 2.4 on page 42 and in each of the sections
8636 // describing clauses and directives for which a list appears.
8637 // OpenMP [2.14.3.3, Restrictions, p.1]
8638 // A variable that is part of another variable (as an array or
8639 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008640 if (!FirstIter && IR != ER)
8641 ++IR;
8642 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008643 SourceLocation ELoc;
8644 SourceRange ERange;
8645 Expr *SimpleRefExpr = RefExpr;
8646 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8647 /*AllowArraySection=*/true);
8648 if (Res.second) {
8649 // It will be analyzed later.
8650 Vars.push_back(RefExpr);
8651 Privates.push_back(nullptr);
8652 LHSs.push_back(nullptr);
8653 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008654 // Try to find 'declare reduction' corresponding construct before using
8655 // builtin/overloaded operators.
8656 QualType Type = Context.DependentTy;
8657 CXXCastPath BasePath;
8658 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8659 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8660 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8661 if (CurContext->isDependentContext() &&
8662 (DeclareReductionRef.isUnset() ||
8663 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8664 ReductionOps.push_back(DeclareReductionRef.get());
8665 else
8666 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008667 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008668 ValueDecl *D = Res.first;
8669 if (!D)
8670 continue;
8671
Alexey Bataeva1764212015-09-30 09:22:36 +00008672 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008673 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8674 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8675 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008676 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008677 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008678 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8679 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8680 Type = ATy->getElementType();
8681 else
8682 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008683 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008684 } else
8685 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8686 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008687
Alexey Bataevc5e02582014-06-16 07:08:35 +00008688 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8689 // A variable that appears in a private clause must not have an incomplete
8690 // type or a reference type.
8691 if (RequireCompleteType(ELoc, Type,
8692 diag::err_omp_reduction_incomplete_type))
8693 continue;
8694 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008695 // A list item that appears in a reduction clause must not be
8696 // const-qualified.
8697 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008698 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008699 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008700 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008701 bool IsDecl = !VD ||
8702 VD->isThisDeclarationADefinition(Context) ==
8703 VarDecl::DeclarationOnly;
8704 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008705 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008706 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008707 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008708 continue;
8709 }
8710 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8711 // If a list-item is a reference type then it must bind to the same object
8712 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008713 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008714 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008715 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008716 DSARefChecker Check(DSAStack);
8717 if (Check.Visit(VDDef->getInit())) {
8718 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8719 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8720 continue;
8721 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008722 }
8723 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008724
Alexey Bataevc5e02582014-06-16 07:08:35 +00008725 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8726 // in a Construct]
8727 // Variables with the predetermined data-sharing attributes may not be
8728 // listed in data-sharing attributes clauses, except for the cases
8729 // listed below. For these exceptions only, listing a predetermined
8730 // variable in a data-sharing attribute clause is allowed and overrides
8731 // the variable's predetermined data-sharing attributes.
8732 // OpenMP [2.14.3.6, Restrictions, p.3]
8733 // Any number of reduction clauses can be specified on the directive,
8734 // but a list item can appear only once in the reduction clauses for that
8735 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008736 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008737 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008738 if (DVar.CKind == OMPC_reduction) {
8739 Diag(ELoc, diag::err_omp_once_referenced)
8740 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008741 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008742 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008743 } else if (DVar.CKind != OMPC_unknown) {
8744 Diag(ELoc, diag::err_omp_wrong_dsa)
8745 << getOpenMPClauseName(DVar.CKind)
8746 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008747 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008748 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008749 }
8750
8751 // OpenMP [2.14.3.6, Restrictions, p.1]
8752 // A list item that appears in a reduction clause of a worksharing
8753 // construct must be shared in the parallel regions to which any of the
8754 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008755 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8756 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008757 !isOpenMPParallelDirective(CurrDir) &&
8758 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008759 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008760 if (DVar.CKind != OMPC_shared) {
8761 Diag(ELoc, diag::err_omp_required_access)
8762 << getOpenMPClauseName(OMPC_reduction)
8763 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008764 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008765 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008766 }
8767 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008768
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008769 // Try to find 'declare reduction' corresponding construct before using
8770 // builtin/overloaded operators.
8771 CXXCastPath BasePath;
8772 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8773 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8774 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8775 if (DeclareReductionRef.isInvalid())
8776 continue;
8777 if (CurContext->isDependentContext() &&
8778 (DeclareReductionRef.isUnset() ||
8779 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8780 Vars.push_back(RefExpr);
8781 Privates.push_back(nullptr);
8782 LHSs.push_back(nullptr);
8783 RHSs.push_back(nullptr);
8784 ReductionOps.push_back(DeclareReductionRef.get());
8785 continue;
8786 }
8787 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8788 // Not allowed reduction identifier is found.
8789 Diag(ReductionId.getLocStart(),
8790 diag::err_omp_unknown_reduction_identifier)
8791 << Type << ReductionIdRange;
8792 continue;
8793 }
8794
8795 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8796 // The type of a list item that appears in a reduction clause must be valid
8797 // for the reduction-identifier. For a max or min reduction in C, the type
8798 // of the list item must be an allowed arithmetic data type: char, int,
8799 // float, double, or _Bool, possibly modified with long, short, signed, or
8800 // unsigned. For a max or min reduction in C++, the type of the list item
8801 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8802 // double, or bool, possibly modified with long, short, signed, or unsigned.
8803 if (DeclareReductionRef.isUnset()) {
8804 if ((BOK == BO_GT || BOK == BO_LT) &&
8805 !(Type->isScalarType() ||
8806 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8807 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8808 << getLangOpts().CPlusPlus;
8809 if (!ASE && !OASE) {
8810 bool IsDecl = !VD ||
8811 VD->isThisDeclarationADefinition(Context) ==
8812 VarDecl::DeclarationOnly;
8813 Diag(D->getLocation(),
8814 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8815 << D;
8816 }
8817 continue;
8818 }
8819 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8820 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8821 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8822 if (!ASE && !OASE) {
8823 bool IsDecl = !VD ||
8824 VD->isThisDeclarationADefinition(Context) ==
8825 VarDecl::DeclarationOnly;
8826 Diag(D->getLocation(),
8827 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8828 << D;
8829 }
8830 continue;
8831 }
8832 }
8833
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008834 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008835 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008836 D->hasAttrs() ? &D->getAttrs() : nullptr);
8837 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8838 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008839 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008840 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008841 (!ASE &&
8842 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008843 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008844 // Create pseudo array type for private copy. The size for this array will
8845 // be generated during codegen.
8846 // For array subscripts or single variables Private Ty is the same as Type
8847 // (type of the variable or single array element).
8848 PrivateTy = Context.getVariableArrayType(
8849 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8850 Context.getSizeType(), VK_RValue),
8851 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008852 } else if (!ASE && !OASE &&
8853 Context.getAsArrayType(D->getType().getNonReferenceType()))
8854 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008855 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008856 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8857 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008858 // Add initializer for private variable.
8859 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008860 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8861 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8862 if (DeclareReductionRef.isUsable()) {
8863 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8864 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8865 if (DRD->getInitializer()) {
8866 Init = DRDRef;
8867 RHSVD->setInit(DRDRef);
8868 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008869 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008870 } else {
8871 switch (BOK) {
8872 case BO_Add:
8873 case BO_Xor:
8874 case BO_Or:
8875 case BO_LOr:
8876 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8877 if (Type->isScalarType() || Type->isAnyComplexType())
8878 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8879 break;
8880 case BO_Mul:
8881 case BO_LAnd:
8882 if (Type->isScalarType() || Type->isAnyComplexType()) {
8883 // '*' and '&&' reduction ops - initializer is '1'.
8884 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008885 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008886 break;
8887 case BO_And: {
8888 // '&' reduction op - initializer is '~0'.
8889 QualType OrigType = Type;
8890 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8891 Type = ComplexTy->getElementType();
8892 if (Type->isRealFloatingType()) {
8893 llvm::APFloat InitValue =
8894 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8895 /*isIEEE=*/true);
8896 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8897 Type, ELoc);
8898 } else if (Type->isScalarType()) {
8899 auto Size = Context.getTypeSize(Type);
8900 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8901 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8902 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8903 }
8904 if (Init && OrigType->isAnyComplexType()) {
8905 // Init = 0xFFFF + 0xFFFFi;
8906 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8907 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8908 }
8909 Type = OrigType;
8910 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008911 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008912 case BO_LT:
8913 case BO_GT: {
8914 // 'min' reduction op - initializer is 'Largest representable number in
8915 // the reduction list item type'.
8916 // 'max' reduction op - initializer is 'Least representable number in
8917 // the reduction list item type'.
8918 if (Type->isIntegerType() || Type->isPointerType()) {
8919 bool IsSigned = Type->hasSignedIntegerRepresentation();
8920 auto Size = Context.getTypeSize(Type);
8921 QualType IntTy =
8922 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8923 llvm::APInt InitValue =
8924 (BOK != BO_LT)
8925 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8926 : llvm::APInt::getMinValue(Size)
8927 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8928 : llvm::APInt::getMaxValue(Size);
8929 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8930 if (Type->isPointerType()) {
8931 // Cast to pointer type.
8932 auto CastExpr = BuildCStyleCastExpr(
8933 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8934 SourceLocation(), Init);
8935 if (CastExpr.isInvalid())
8936 continue;
8937 Init = CastExpr.get();
8938 }
8939 } else if (Type->isRealFloatingType()) {
8940 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8941 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8942 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8943 Type, ELoc);
8944 }
8945 break;
8946 }
8947 case BO_PtrMemD:
8948 case BO_PtrMemI:
8949 case BO_MulAssign:
8950 case BO_Div:
8951 case BO_Rem:
8952 case BO_Sub:
8953 case BO_Shl:
8954 case BO_Shr:
8955 case BO_LE:
8956 case BO_GE:
8957 case BO_EQ:
8958 case BO_NE:
8959 case BO_AndAssign:
8960 case BO_XorAssign:
8961 case BO_OrAssign:
8962 case BO_Assign:
8963 case BO_AddAssign:
8964 case BO_SubAssign:
8965 case BO_DivAssign:
8966 case BO_RemAssign:
8967 case BO_ShlAssign:
8968 case BO_ShrAssign:
8969 case BO_Comma:
8970 llvm_unreachable("Unexpected reduction operation");
8971 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008972 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008973 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00008974 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008975 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00008976 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008977 if (RHSVD->isInvalidDecl())
8978 continue;
8979 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008980 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8981 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008982 bool IsDecl =
8983 !VD ||
8984 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8985 Diag(D->getLocation(),
8986 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8987 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008988 continue;
8989 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008990 // Store initializer for single element in private copy. Will be used during
8991 // codegen.
8992 PrivateVD->setInit(RHSVD->getInit());
8993 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008994 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008995 ExprResult ReductionOp;
8996 if (DeclareReductionRef.isUsable()) {
8997 QualType RedTy = DeclareReductionRef.get()->getType();
8998 QualType PtrRedTy = Context.getPointerType(RedTy);
8999 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9000 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9001 if (!BasePath.empty()) {
9002 LHS = DefaultLvalueConversion(LHS.get());
9003 RHS = DefaultLvalueConversion(RHS.get());
9004 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9005 CK_UncheckedDerivedToBase, LHS.get(),
9006 &BasePath, LHS.get()->getValueKind());
9007 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9008 CK_UncheckedDerivedToBase, RHS.get(),
9009 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009010 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009011 FunctionProtoType::ExtProtoInfo EPI;
9012 QualType Params[] = {PtrRedTy, PtrRedTy};
9013 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9014 auto *OVE = new (Context) OpaqueValueExpr(
9015 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9016 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9017 Expr *Args[] = {LHS.get(), RHS.get()};
9018 ReductionOp = new (Context)
9019 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9020 } else {
9021 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9022 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9023 if (ReductionOp.isUsable()) {
9024 if (BOK != BO_LT && BOK != BO_GT) {
9025 ReductionOp =
9026 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9027 BO_Assign, LHSDRE, ReductionOp.get());
9028 } else {
9029 auto *ConditionalOp = new (Context) ConditionalOperator(
9030 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9031 RHSDRE, Type, VK_LValue, OK_Ordinary);
9032 ReductionOp =
9033 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9034 BO_Assign, LHSDRE, ConditionalOp);
9035 }
9036 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9037 }
9038 if (ReductionOp.isInvalid())
9039 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009040 }
9041
Alexey Bataev60da77e2016-02-29 05:54:20 +00009042 DeclRefExpr *Ref = nullptr;
9043 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009044 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009045 if (ASE || OASE) {
9046 TransformExprToCaptures RebuildToCapture(*this, D);
9047 VarsExpr =
9048 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9049 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009050 } else {
9051 VarsExpr = Ref =
9052 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009053 }
9054 if (!IsOpenMPCapturedDecl(D)) {
9055 ExprCaptures.push_back(Ref->getDecl());
9056 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9057 ExprResult RefRes = DefaultLvalueConversion(Ref);
9058 if (!RefRes.isUsable())
9059 continue;
9060 ExprResult PostUpdateRes =
9061 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9062 SimpleRefExpr, RefRes.get());
9063 if (!PostUpdateRes.isUsable())
9064 continue;
9065 ExprPostUpdates.push_back(
9066 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009067 }
9068 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009069 }
9070 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9071 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009072 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009073 LHSs.push_back(LHSDRE);
9074 RHSs.push_back(RHSDRE);
9075 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009076 }
9077
9078 if (Vars.empty())
9079 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009080
Alexey Bataevc5e02582014-06-16 07:08:35 +00009081 return OMPReductionClause::Create(
9082 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009083 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009084 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9085 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009086}
9087
Alexey Bataevecba70f2016-04-12 11:02:11 +00009088bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9089 SourceLocation LinLoc) {
9090 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9091 LinKind == OMPC_LINEAR_unknown) {
9092 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9093 return true;
9094 }
9095 return false;
9096}
9097
9098bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9099 OpenMPLinearClauseKind LinKind,
9100 QualType Type) {
9101 auto *VD = dyn_cast_or_null<VarDecl>(D);
9102 // A variable must not have an incomplete type or a reference type.
9103 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9104 return true;
9105 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9106 !Type->isReferenceType()) {
9107 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9108 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9109 return true;
9110 }
9111 Type = Type.getNonReferenceType();
9112
9113 // A list item must not be const-qualified.
9114 if (Type.isConstant(Context)) {
9115 Diag(ELoc, diag::err_omp_const_variable)
9116 << getOpenMPClauseName(OMPC_linear);
9117 if (D) {
9118 bool IsDecl =
9119 !VD ||
9120 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9121 Diag(D->getLocation(),
9122 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9123 << D;
9124 }
9125 return true;
9126 }
9127
9128 // A list item must be of integral or pointer type.
9129 Type = Type.getUnqualifiedType().getCanonicalType();
9130 const auto *Ty = Type.getTypePtrOrNull();
9131 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9132 !Ty->isPointerType())) {
9133 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9134 if (D) {
9135 bool IsDecl =
9136 !VD ||
9137 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9138 Diag(D->getLocation(),
9139 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9140 << D;
9141 }
9142 return true;
9143 }
9144 return false;
9145}
9146
Alexey Bataev182227b2015-08-20 10:54:39 +00009147OMPClause *Sema::ActOnOpenMPLinearClause(
9148 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9149 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9150 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009151 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009152 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009153 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009154 SmallVector<Decl *, 4> ExprCaptures;
9155 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009156 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009157 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009158 for (auto &RefExpr : VarList) {
9159 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009160 SourceLocation ELoc;
9161 SourceRange ERange;
9162 Expr *SimpleRefExpr = RefExpr;
9163 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9164 /*AllowArraySection=*/false);
9165 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009166 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009167 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009168 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009169 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009170 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009171 ValueDecl *D = Res.first;
9172 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009173 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009174
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009175 QualType Type = D->getType();
9176 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009177
9178 // OpenMP [2.14.3.7, linear clause]
9179 // A list-item cannot appear in more than one linear clause.
9180 // A list-item that appears in a linear clause cannot appear in any
9181 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009182 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009183 if (DVar.RefExpr) {
9184 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9185 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009186 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009187 continue;
9188 }
9189
Alexey Bataevecba70f2016-04-12 11:02:11 +00009190 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009191 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009192 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009193
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009194 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009195 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9196 D->hasAttrs() ? &D->getAttrs() : nullptr);
9197 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009198 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009199 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009200 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009201 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009202 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009203 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9204 if (!IsOpenMPCapturedDecl(D)) {
9205 ExprCaptures.push_back(Ref->getDecl());
9206 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9207 ExprResult RefRes = DefaultLvalueConversion(Ref);
9208 if (!RefRes.isUsable())
9209 continue;
9210 ExprResult PostUpdateRes =
9211 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9212 SimpleRefExpr, RefRes.get());
9213 if (!PostUpdateRes.isUsable())
9214 continue;
9215 ExprPostUpdates.push_back(
9216 IgnoredValueConversions(PostUpdateRes.get()).get());
9217 }
9218 }
9219 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009220 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009221 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009222 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009223 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009224 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009225 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009226 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9227
9228 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009229 Vars.push_back((VD || CurContext->isDependentContext())
9230 ? RefExpr->IgnoreParens()
9231 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009232 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009233 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009234 }
9235
9236 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009237 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009238
9239 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009240 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009241 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9242 !Step->isInstantiationDependent() &&
9243 !Step->containsUnexpandedParameterPack()) {
9244 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009245 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009246 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009247 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009248 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009249
Alexander Musman3276a272015-03-21 10:12:56 +00009250 // Build var to save the step value.
9251 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009252 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009253 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009254 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009255 ExprResult CalcStep =
9256 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009257 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009258
Alexander Musman8dba6642014-04-22 13:09:42 +00009259 // Warn about zero linear step (it would be probably better specified as
9260 // making corresponding variables 'const').
9261 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009262 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9263 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009264 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9265 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009266 if (!IsConstant && CalcStep.isUsable()) {
9267 // Calculate the step beforehand instead of doing this on each iteration.
9268 // (This is not used if the number of iterations may be kfold-ed).
9269 CalcStepExpr = CalcStep.get();
9270 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009271 }
9272
Alexey Bataev182227b2015-08-20 10:54:39 +00009273 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9274 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009275 StepExpr, CalcStepExpr,
9276 buildPreInits(Context, ExprCaptures),
9277 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009278}
9279
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009280static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9281 Expr *NumIterations, Sema &SemaRef,
9282 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009283 // Walk the vars and build update/final expressions for the CodeGen.
9284 SmallVector<Expr *, 8> Updates;
9285 SmallVector<Expr *, 8> Finals;
9286 Expr *Step = Clause.getStep();
9287 Expr *CalcStep = Clause.getCalcStep();
9288 // OpenMP [2.14.3.7, linear clause]
9289 // If linear-step is not specified it is assumed to be 1.
9290 if (Step == nullptr)
9291 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009292 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009293 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009294 }
Alexander Musman3276a272015-03-21 10:12:56 +00009295 bool HasErrors = false;
9296 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009297 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009298 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009299 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009300 SourceLocation ELoc;
9301 SourceRange ERange;
9302 Expr *SimpleRefExpr = RefExpr;
9303 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9304 /*AllowArraySection=*/false);
9305 ValueDecl *D = Res.first;
9306 if (Res.second || !D) {
9307 Updates.push_back(nullptr);
9308 Finals.push_back(nullptr);
9309 HasErrors = true;
9310 continue;
9311 }
9312 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9313 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9314 ->getMemberDecl();
9315 }
9316 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009317 Expr *InitExpr = *CurInit;
9318
9319 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009320 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009321 Expr *CapturedRef;
9322 if (LinKind == OMPC_LINEAR_uval)
9323 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9324 else
9325 CapturedRef =
9326 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9327 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9328 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009329
9330 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009331 ExprResult Update;
9332 if (!Info.first) {
9333 Update =
9334 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9335 InitExpr, IV, Step, /* Subtract */ false);
9336 } else
9337 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009338 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9339 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009340
9341 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009342 ExprResult Final;
9343 if (!Info.first) {
9344 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9345 InitExpr, NumIterations, Step,
9346 /* Subtract */ false);
9347 } else
9348 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009349 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9350 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009351
Alexander Musman3276a272015-03-21 10:12:56 +00009352 if (!Update.isUsable() || !Final.isUsable()) {
9353 Updates.push_back(nullptr);
9354 Finals.push_back(nullptr);
9355 HasErrors = true;
9356 } else {
9357 Updates.push_back(Update.get());
9358 Finals.push_back(Final.get());
9359 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009360 ++CurInit;
9361 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009362 }
9363 Clause.setUpdates(Updates);
9364 Clause.setFinals(Finals);
9365 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009366}
9367
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009368OMPClause *Sema::ActOnOpenMPAlignedClause(
9369 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9370 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9371
9372 SmallVector<Expr *, 8> Vars;
9373 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009374 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9375 SourceLocation ELoc;
9376 SourceRange ERange;
9377 Expr *SimpleRefExpr = RefExpr;
9378 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9379 /*AllowArraySection=*/false);
9380 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009381 // It will be analyzed later.
9382 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009383 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009384 ValueDecl *D = Res.first;
9385 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009386 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009387
Alexey Bataev1efd1662016-03-29 10:59:56 +00009388 QualType QType = D->getType();
9389 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009390
9391 // OpenMP [2.8.1, simd construct, Restrictions]
9392 // The type of list items appearing in the aligned clause must be
9393 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009394 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009395 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009396 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009397 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009398 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009399 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009400 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009401 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009402 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009403 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009404 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009405 continue;
9406 }
9407
9408 // OpenMP [2.8.1, simd construct, Restrictions]
9409 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009410 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009411 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009412 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9413 << getOpenMPClauseName(OMPC_aligned);
9414 continue;
9415 }
9416
Alexey Bataev1efd1662016-03-29 10:59:56 +00009417 DeclRefExpr *Ref = nullptr;
9418 if (!VD && IsOpenMPCapturedDecl(D))
9419 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9420 Vars.push_back(DefaultFunctionArrayConversion(
9421 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9422 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009423 }
9424
9425 // OpenMP [2.8.1, simd construct, Description]
9426 // The parameter of the aligned clause, alignment, must be a constant
9427 // positive integer expression.
9428 // If no optional parameter is specified, implementation-defined default
9429 // alignments for SIMD instructions on the target platforms are assumed.
9430 if (Alignment != nullptr) {
9431 ExprResult AlignResult =
9432 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9433 if (AlignResult.isInvalid())
9434 return nullptr;
9435 Alignment = AlignResult.get();
9436 }
9437 if (Vars.empty())
9438 return nullptr;
9439
9440 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9441 EndLoc, Vars, Alignment);
9442}
9443
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009444OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9445 SourceLocation StartLoc,
9446 SourceLocation LParenLoc,
9447 SourceLocation EndLoc) {
9448 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009449 SmallVector<Expr *, 8> SrcExprs;
9450 SmallVector<Expr *, 8> DstExprs;
9451 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009452 for (auto &RefExpr : VarList) {
9453 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9454 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009455 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009456 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009457 SrcExprs.push_back(nullptr);
9458 DstExprs.push_back(nullptr);
9459 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009460 continue;
9461 }
9462
Alexey Bataeved09d242014-05-28 05:53:51 +00009463 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009464 // OpenMP [2.1, C/C++]
9465 // A list item is a variable name.
9466 // OpenMP [2.14.4.1, Restrictions, p.1]
9467 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009468 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009469 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009470 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9471 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009472 continue;
9473 }
9474
9475 Decl *D = DE->getDecl();
9476 VarDecl *VD = cast<VarDecl>(D);
9477
9478 QualType Type = VD->getType();
9479 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9480 // It will be analyzed later.
9481 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009482 SrcExprs.push_back(nullptr);
9483 DstExprs.push_back(nullptr);
9484 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009485 continue;
9486 }
9487
9488 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9489 // A list item that appears in a copyin clause must be threadprivate.
9490 if (!DSAStack->isThreadPrivate(VD)) {
9491 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009492 << getOpenMPClauseName(OMPC_copyin)
9493 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009494 continue;
9495 }
9496
9497 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9498 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009499 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009500 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009501 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009502 auto *SrcVD =
9503 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9504 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009505 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009506 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9507 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009508 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9509 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009510 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009511 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009512 // For arrays generate assignment operation for single element and replace
9513 // it by the original array element in CodeGen.
9514 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9515 PseudoDstExpr, PseudoSrcExpr);
9516 if (AssignmentOp.isInvalid())
9517 continue;
9518 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9519 /*DiscardedValue=*/true);
9520 if (AssignmentOp.isInvalid())
9521 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009522
9523 DSAStack->addDSA(VD, DE, OMPC_copyin);
9524 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009525 SrcExprs.push_back(PseudoSrcExpr);
9526 DstExprs.push_back(PseudoDstExpr);
9527 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009528 }
9529
Alexey Bataeved09d242014-05-28 05:53:51 +00009530 if (Vars.empty())
9531 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009532
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009533 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9534 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009535}
9536
Alexey Bataevbae9a792014-06-27 10:37:06 +00009537OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9538 SourceLocation StartLoc,
9539 SourceLocation LParenLoc,
9540 SourceLocation EndLoc) {
9541 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009542 SmallVector<Expr *, 8> SrcExprs;
9543 SmallVector<Expr *, 8> DstExprs;
9544 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009545 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009546 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9547 SourceLocation ELoc;
9548 SourceRange ERange;
9549 Expr *SimpleRefExpr = RefExpr;
9550 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9551 /*AllowArraySection=*/false);
9552 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009553 // It will be analyzed later.
9554 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009555 SrcExprs.push_back(nullptr);
9556 DstExprs.push_back(nullptr);
9557 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009558 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009559 ValueDecl *D = Res.first;
9560 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009561 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009562
Alexey Bataeve122da12016-03-17 10:50:17 +00009563 QualType Type = D->getType();
9564 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009565
9566 // OpenMP [2.14.4.2, Restrictions, p.2]
9567 // A list item that appears in a copyprivate clause may not appear in a
9568 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009569 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9570 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009571 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9572 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009573 Diag(ELoc, diag::err_omp_wrong_dsa)
9574 << getOpenMPClauseName(DVar.CKind)
9575 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009576 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009577 continue;
9578 }
9579
9580 // OpenMP [2.11.4.2, Restrictions, p.1]
9581 // All list items that appear in a copyprivate clause must be either
9582 // threadprivate or private in the enclosing context.
9583 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009584 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009585 if (DVar.CKind == OMPC_shared) {
9586 Diag(ELoc, diag::err_omp_required_access)
9587 << getOpenMPClauseName(OMPC_copyprivate)
9588 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009589 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009590 continue;
9591 }
9592 }
9593 }
9594
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009595 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009596 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009597 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009598 << getOpenMPClauseName(OMPC_copyprivate) << Type
9599 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009600 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009601 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009602 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009603 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009604 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009605 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009606 continue;
9607 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009608
Alexey Bataevbae9a792014-06-27 10:37:06 +00009609 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9610 // A variable of class type (or array thereof) that appears in a
9611 // copyin clause requires an accessible, unambiguous copy assignment
9612 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009613 Type = Context.getBaseElementType(Type.getNonReferenceType())
9614 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009615 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009616 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9617 D->hasAttrs() ? &D->getAttrs() : nullptr);
9618 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009619 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009620 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9621 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009622 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009623 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009624 PseudoDstExpr, PseudoSrcExpr);
9625 if (AssignmentOp.isInvalid())
9626 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009627 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009628 /*DiscardedValue=*/true);
9629 if (AssignmentOp.isInvalid())
9630 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009631
9632 // No need to mark vars as copyprivate, they are already threadprivate or
9633 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009634 assert(VD || IsOpenMPCapturedDecl(D));
9635 Vars.push_back(
9636 VD ? RefExpr->IgnoreParens()
9637 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009638 SrcExprs.push_back(PseudoSrcExpr);
9639 DstExprs.push_back(PseudoDstExpr);
9640 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009641 }
9642
9643 if (Vars.empty())
9644 return nullptr;
9645
Alexey Bataeva63048e2015-03-23 06:18:07 +00009646 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9647 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009648}
9649
Alexey Bataev6125da92014-07-21 11:26:11 +00009650OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9651 SourceLocation StartLoc,
9652 SourceLocation LParenLoc,
9653 SourceLocation EndLoc) {
9654 if (VarList.empty())
9655 return nullptr;
9656
9657 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9658}
Alexey Bataevdea47612014-07-23 07:46:59 +00009659
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009660OMPClause *
9661Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9662 SourceLocation DepLoc, SourceLocation ColonLoc,
9663 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9664 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009665 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009666 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009667 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009668 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009669 return nullptr;
9670 }
9671 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009672 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9673 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009674 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009675 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009676 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9677 /*Last=*/OMPC_DEPEND_unknown, Except)
9678 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009679 return nullptr;
9680 }
9681 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009682 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009683 llvm::APSInt DepCounter(/*BitWidth=*/32);
9684 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9685 if (DepKind == OMPC_DEPEND_sink) {
9686 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9687 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9688 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009689 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009690 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009691 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9692 DSAStack->getParentOrderedRegionParam()) {
9693 for (auto &RefExpr : VarList) {
9694 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009695 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009696 // It will be analyzed later.
9697 Vars.push_back(RefExpr);
9698 continue;
9699 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009700
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009701 SourceLocation ELoc = RefExpr->getExprLoc();
9702 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9703 if (DepKind == OMPC_DEPEND_sink) {
9704 if (DepCounter >= TotalDepCount) {
9705 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9706 continue;
9707 }
9708 ++DepCounter;
9709 // OpenMP [2.13.9, Summary]
9710 // depend(dependence-type : vec), where dependence-type is:
9711 // 'sink' and where vec is the iteration vector, which has the form:
9712 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9713 // where n is the value specified by the ordered clause in the loop
9714 // directive, xi denotes the loop iteration variable of the i-th nested
9715 // loop associated with the loop directive, and di is a constant
9716 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009717 if (CurContext->isDependentContext()) {
9718 // It will be analyzed later.
9719 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009720 continue;
9721 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009722 SimpleExpr = SimpleExpr->IgnoreImplicit();
9723 OverloadedOperatorKind OOK = OO_None;
9724 SourceLocation OOLoc;
9725 Expr *LHS = SimpleExpr;
9726 Expr *RHS = nullptr;
9727 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9728 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9729 OOLoc = BO->getOperatorLoc();
9730 LHS = BO->getLHS()->IgnoreParenImpCasts();
9731 RHS = BO->getRHS()->IgnoreParenImpCasts();
9732 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9733 OOK = OCE->getOperator();
9734 OOLoc = OCE->getOperatorLoc();
9735 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9736 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9737 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9738 OOK = MCE->getMethodDecl()
9739 ->getNameInfo()
9740 .getName()
9741 .getCXXOverloadedOperator();
9742 OOLoc = MCE->getCallee()->getExprLoc();
9743 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9744 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9745 }
9746 SourceLocation ELoc;
9747 SourceRange ERange;
9748 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9749 /*AllowArraySection=*/false);
9750 if (Res.second) {
9751 // It will be analyzed later.
9752 Vars.push_back(RefExpr);
9753 }
9754 ValueDecl *D = Res.first;
9755 if (!D)
9756 continue;
9757
9758 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9759 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9760 continue;
9761 }
9762 if (RHS) {
9763 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9764 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9765 if (RHSRes.isInvalid())
9766 continue;
9767 }
9768 if (!CurContext->isDependentContext() &&
9769 DSAStack->getParentOrderedRegionParam() &&
9770 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9771 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9772 << DSAStack->getParentLoopControlVariable(
9773 DepCounter.getZExtValue());
9774 continue;
9775 }
9776 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009777 } else {
9778 // OpenMP [2.11.1.1, Restrictions, p.3]
9779 // A variable that is part of another variable (such as a field of a
9780 // structure) but is not an array element or an array section cannot
9781 // appear in a depend clause.
9782 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9783 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9784 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9785 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9786 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009787 (ASE &&
9788 !ASE->getBase()
9789 ->getType()
9790 .getNonReferenceType()
9791 ->isPointerType() &&
9792 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009793 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9794 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009795 continue;
9796 }
9797 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009798 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9799 }
9800
9801 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9802 TotalDepCount > VarList.size() &&
9803 DSAStack->getParentOrderedRegionParam()) {
9804 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9805 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9806 }
9807 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9808 Vars.empty())
9809 return nullptr;
9810 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009811 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9812 DepKind, DepLoc, ColonLoc, Vars);
9813 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9814 DSAStack->addDoacrossDependClause(C, OpsOffs);
9815 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009816}
Michael Wonge710d542015-08-07 16:16:36 +00009817
9818OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9819 SourceLocation LParenLoc,
9820 SourceLocation EndLoc) {
9821 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009822
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009823 // OpenMP [2.9.1, Restrictions]
9824 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009825 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9826 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009827 return nullptr;
9828
Michael Wonge710d542015-08-07 16:16:36 +00009829 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9830}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009831
9832static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9833 DSAStackTy *Stack, CXXRecordDecl *RD) {
9834 if (!RD || RD->isInvalidDecl())
9835 return true;
9836
9837 auto QTy = SemaRef.Context.getRecordType(RD);
9838 if (RD->isDynamicClass()) {
9839 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9840 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9841 return false;
9842 }
9843 auto *DC = RD;
9844 bool IsCorrect = true;
9845 for (auto *I : DC->decls()) {
9846 if (I) {
9847 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9848 if (MD->isStatic()) {
9849 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9850 SemaRef.Diag(MD->getLocation(),
9851 diag::note_omp_static_member_in_target);
9852 IsCorrect = false;
9853 }
9854 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9855 if (VD->isStaticDataMember()) {
9856 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9857 SemaRef.Diag(VD->getLocation(),
9858 diag::note_omp_static_member_in_target);
9859 IsCorrect = false;
9860 }
9861 }
9862 }
9863 }
9864
9865 for (auto &I : RD->bases()) {
9866 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9867 I.getType()->getAsCXXRecordDecl()))
9868 IsCorrect = false;
9869 }
9870 return IsCorrect;
9871}
9872
9873static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9874 DSAStackTy *Stack, QualType QTy) {
9875 NamedDecl *ND;
9876 if (QTy->isIncompleteType(&ND)) {
9877 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9878 return false;
9879 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009880 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009881 return false;
9882 }
9883 return true;
9884}
9885
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009886/// \brief Return true if it can be proven that the provided array expression
9887/// (array section or array subscript) does NOT specify the whole size of the
9888/// array whose base type is \a BaseQTy.
9889static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9890 const Expr *E,
9891 QualType BaseQTy) {
9892 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9893
9894 // If this is an array subscript, it refers to the whole size if the size of
9895 // the dimension is constant and equals 1. Also, an array section assumes the
9896 // format of an array subscript if no colon is used.
9897 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9898 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9899 return ATy->getSize().getSExtValue() != 1;
9900 // Size can't be evaluated statically.
9901 return false;
9902 }
9903
9904 assert(OASE && "Expecting array section if not an array subscript.");
9905 auto *LowerBound = OASE->getLowerBound();
9906 auto *Length = OASE->getLength();
9907
9908 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009909 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009910 if (LowerBound) {
9911 llvm::APSInt ConstLowerBound;
9912 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9913 return false; // Can't get the integer value as a constant.
9914 if (ConstLowerBound.getSExtValue())
9915 return true;
9916 }
9917
9918 // If we don't have a length we covering the whole dimension.
9919 if (!Length)
9920 return false;
9921
9922 // If the base is a pointer, we don't have a way to get the size of the
9923 // pointee.
9924 if (BaseQTy->isPointerType())
9925 return false;
9926
9927 // We can only check if the length is the same as the size of the dimension
9928 // if we have a constant array.
9929 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9930 if (!CATy)
9931 return false;
9932
9933 llvm::APSInt ConstLength;
9934 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9935 return false; // Can't get the integer value as a constant.
9936
9937 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9938}
9939
9940// Return true if it can be proven that the provided array expression (array
9941// section or array subscript) does NOT specify a single element of the array
9942// whose base type is \a BaseQTy.
9943static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009944 const Expr *E,
9945 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009946 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9947
9948 // An array subscript always refer to a single element. Also, an array section
9949 // assumes the format of an array subscript if no colon is used.
9950 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9951 return false;
9952
9953 assert(OASE && "Expecting array section if not an array subscript.");
9954 auto *Length = OASE->getLength();
9955
9956 // If we don't have a length we have to check if the array has unitary size
9957 // for this dimension. Also, we should always expect a length if the base type
9958 // is pointer.
9959 if (!Length) {
9960 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9961 return ATy->getSize().getSExtValue() != 1;
9962 // We cannot assume anything.
9963 return false;
9964 }
9965
9966 // Check if the length evaluates to 1.
9967 llvm::APSInt ConstLength;
9968 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9969 return false; // Can't get the integer value as a constant.
9970
9971 return ConstLength.getSExtValue() != 1;
9972}
9973
Samuel Antao661c0902016-05-26 17:39:58 +00009974// Return the expression of the base of the mappable expression or null if it
9975// cannot be determined and do all the necessary checks to see if the expression
9976// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009977// components of the expression.
9978static Expr *CheckMapClauseExpressionBase(
9979 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009980 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9981 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009982 SourceLocation ELoc = E->getExprLoc();
9983 SourceRange ERange = E->getSourceRange();
9984
9985 // The base of elements of list in a map clause have to be either:
9986 // - a reference to variable or field.
9987 // - a member expression.
9988 // - an array expression.
9989 //
9990 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9991 // reference to 'r'.
9992 //
9993 // If we have:
9994 //
9995 // struct SS {
9996 // Bla S;
9997 // foo() {
9998 // #pragma omp target map (S.Arr[:12]);
9999 // }
10000 // }
10001 //
10002 // We want to retrieve the member expression 'this->S';
10003
10004 Expr *RelevantExpr = nullptr;
10005
Samuel Antao5de996e2016-01-22 20:21:36 +000010006 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10007 // If a list item is an array section, it must specify contiguous storage.
10008 //
10009 // For this restriction it is sufficient that we make sure only references
10010 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010011 // exist except in the rightmost expression (unless they cover the whole
10012 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010013 //
10014 // r.ArrS[3:5].Arr[6:7]
10015 //
10016 // r.ArrS[3:5].x
10017 //
10018 // but these would be valid:
10019 // r.ArrS[3].Arr[6:7]
10020 //
10021 // r.ArrS[3].x
10022
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010023 bool AllowUnitySizeArraySection = true;
10024 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010025
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010026 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010027 E = E->IgnoreParenImpCasts();
10028
10029 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10030 if (!isa<VarDecl>(CurE->getDecl()))
10031 break;
10032
10033 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010034
10035 // If we got a reference to a declaration, we should not expect any array
10036 // section before that.
10037 AllowUnitySizeArraySection = false;
10038 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010039
10040 // Record the component.
10041 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10042 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010043 continue;
10044 }
10045
10046 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10047 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10048
10049 if (isa<CXXThisExpr>(BaseE))
10050 // We found a base expression: this->Val.
10051 RelevantExpr = CurE;
10052 else
10053 E = BaseE;
10054
10055 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10056 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10057 << CurE->getSourceRange();
10058 break;
10059 }
10060
10061 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10062
10063 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10064 // A bit-field cannot appear in a map clause.
10065 //
10066 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010067 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10068 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010069 break;
10070 }
10071
10072 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10073 // If the type of a list item is a reference to a type T then the type
10074 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010075 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010076
10077 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10078 // A list item cannot be a variable that is a member of a structure with
10079 // a union type.
10080 //
10081 if (auto *RT = CurType->getAs<RecordType>())
10082 if (RT->isUnionType()) {
10083 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10084 << CurE->getSourceRange();
10085 break;
10086 }
10087
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010088 // If we got a member expression, we should not expect any array section
10089 // before that:
10090 //
10091 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10092 // If a list item is an element of a structure, only the rightmost symbol
10093 // of the variable reference can be an array section.
10094 //
10095 AllowUnitySizeArraySection = false;
10096 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010097
10098 // Record the component.
10099 CurComponents.push_back(
10100 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010101 continue;
10102 }
10103
10104 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10105 E = CurE->getBase()->IgnoreParenImpCasts();
10106
10107 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10108 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10109 << 0 << CurE->getSourceRange();
10110 break;
10111 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010112
10113 // If we got an array subscript that express the whole dimension we
10114 // can have any array expressions before. If it only expressing part of
10115 // the dimension, we can only have unitary-size array expressions.
10116 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10117 E->getType()))
10118 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010119
10120 // Record the component - we don't have any declaration associated.
10121 CurComponents.push_back(
10122 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010123 continue;
10124 }
10125
10126 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010127 E = CurE->getBase()->IgnoreParenImpCasts();
10128
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010129 auto CurType =
10130 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10131
Samuel Antao5de996e2016-01-22 20:21:36 +000010132 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10133 // If the type of a list item is a reference to a type T then the type
10134 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010135 if (CurType->isReferenceType())
10136 CurType = CurType->getPointeeType();
10137
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010138 bool IsPointer = CurType->isAnyPointerType();
10139
10140 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010141 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10142 << 0 << CurE->getSourceRange();
10143 break;
10144 }
10145
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010146 bool NotWhole =
10147 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10148 bool NotUnity =
10149 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10150
Samuel Antaodab51bb2016-07-18 23:22:11 +000010151 if (AllowWholeSizeArraySection) {
10152 // Any array section is currently allowed. Allowing a whole size array
10153 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010154 //
10155 // If this array section refers to the whole dimension we can still
10156 // accept other array sections before this one, except if the base is a
10157 // pointer. Otherwise, only unitary sections are accepted.
10158 if (NotWhole || IsPointer)
10159 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010160 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010161 // A unity or whole array section is not allowed and that is not
10162 // compatible with the properties of the current array section.
10163 SemaRef.Diag(
10164 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10165 << CurE->getSourceRange();
10166 break;
10167 }
Samuel Antao90927002016-04-26 14:54:23 +000010168
10169 // Record the component - we don't have any declaration associated.
10170 CurComponents.push_back(
10171 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010172 continue;
10173 }
10174
10175 // If nothing else worked, this is not a valid map clause expression.
10176 SemaRef.Diag(ELoc,
10177 diag::err_omp_expected_named_var_member_or_array_expression)
10178 << ERange;
10179 break;
10180 }
10181
10182 return RelevantExpr;
10183}
10184
10185// Return true if expression E associated with value VD has conflicts with other
10186// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010187static bool CheckMapConflicts(
10188 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10189 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010190 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10191 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010192 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010193 SourceLocation ELoc = E->getExprLoc();
10194 SourceRange ERange = E->getSourceRange();
10195
10196 // In order to easily check the conflicts we need to match each component of
10197 // the expression under test with the components of the expressions that are
10198 // already in the stack.
10199
Samuel Antao5de996e2016-01-22 20:21:36 +000010200 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010201 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010202 "Map clause expression with unexpected base!");
10203
10204 // Variables to help detecting enclosing problems in data environment nests.
10205 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010206 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010207
Samuel Antao90927002016-04-26 14:54:23 +000010208 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10209 VD, CurrentRegionOnly,
10210 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010211 StackComponents,
10212 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010213
Samuel Antao5de996e2016-01-22 20:21:36 +000010214 assert(!StackComponents.empty() &&
10215 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010216 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010217 "Map clause expression with unexpected base!");
10218
Samuel Antao90927002016-04-26 14:54:23 +000010219 // The whole expression in the stack.
10220 auto *RE = StackComponents.front().getAssociatedExpression();
10221
Samuel Antao5de996e2016-01-22 20:21:36 +000010222 // Expressions must start from the same base. Here we detect at which
10223 // point both expressions diverge from each other and see if we can
10224 // detect if the memory referred to both expressions is contiguous and
10225 // do not overlap.
10226 auto CI = CurComponents.rbegin();
10227 auto CE = CurComponents.rend();
10228 auto SI = StackComponents.rbegin();
10229 auto SE = StackComponents.rend();
10230 for (; CI != CE && SI != SE; ++CI, ++SI) {
10231
10232 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10233 // At most one list item can be an array item derived from a given
10234 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010235 if (CurrentRegionOnly &&
10236 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10237 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10238 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10239 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10240 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010241 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010242 << CI->getAssociatedExpression()->getSourceRange();
10243 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10244 diag::note_used_here)
10245 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010246 return true;
10247 }
10248
10249 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010250 if (CI->getAssociatedExpression()->getStmtClass() !=
10251 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010252 break;
10253
10254 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010255 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010256 break;
10257 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010258 // Check if the extra components of the expressions in the enclosing
10259 // data environment are redundant for the current base declaration.
10260 // If they are, the maps completely overlap, which is legal.
10261 for (; SI != SE; ++SI) {
10262 QualType Type;
10263 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010264 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010265 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010266 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10267 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010268 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10269 Type =
10270 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10271 }
10272 if (Type.isNull() || Type->isAnyPointerType() ||
10273 CheckArrayExpressionDoesNotReferToWholeSize(
10274 SemaRef, SI->getAssociatedExpression(), Type))
10275 break;
10276 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010277
10278 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10279 // List items of map clauses in the same construct must not share
10280 // original storage.
10281 //
10282 // If the expressions are exactly the same or one is a subset of the
10283 // other, it means they are sharing storage.
10284 if (CI == CE && SI == SE) {
10285 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010286 if (CKind == OMPC_map)
10287 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10288 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010289 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010290 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10291 << ERange;
10292 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010293 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10294 << RE->getSourceRange();
10295 return true;
10296 } else {
10297 // If we find the same expression in the enclosing data environment,
10298 // that is legal.
10299 IsEnclosedByDataEnvironmentExpr = true;
10300 return false;
10301 }
10302 }
10303
Samuel Antao90927002016-04-26 14:54:23 +000010304 QualType DerivedType =
10305 std::prev(CI)->getAssociatedDeclaration()->getType();
10306 SourceLocation DerivedLoc =
10307 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010308
10309 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10310 // If the type of a list item is a reference to a type T then the type
10311 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010312 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010313
10314 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10315 // A variable for which the type is pointer and an array section
10316 // derived from that variable must not appear as list items of map
10317 // clauses of the same construct.
10318 //
10319 // Also, cover one of the cases in:
10320 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10321 // If any part of the original storage of a list item has corresponding
10322 // storage in the device data environment, all of the original storage
10323 // must have corresponding storage in the device data environment.
10324 //
10325 if (DerivedType->isAnyPointerType()) {
10326 if (CI == CE || SI == SE) {
10327 SemaRef.Diag(
10328 DerivedLoc,
10329 diag::err_omp_pointer_mapped_along_with_derived_section)
10330 << DerivedLoc;
10331 } else {
10332 assert(CI != CE && SI != SE);
10333 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10334 << DerivedLoc;
10335 }
10336 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10337 << RE->getSourceRange();
10338 return true;
10339 }
10340
10341 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10342 // List items of map clauses in the same construct must not share
10343 // original storage.
10344 //
10345 // An expression is a subset of the other.
10346 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010347 if (CKind == OMPC_map)
10348 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10349 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010350 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010351 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10352 << ERange;
10353 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010354 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10355 << RE->getSourceRange();
10356 return true;
10357 }
10358
10359 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010360 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010361 if (!CurrentRegionOnly && SI != SE)
10362 EnclosingExpr = RE;
10363
10364 // The current expression is a subset of the expression in the data
10365 // environment.
10366 IsEnclosedByDataEnvironmentExpr |=
10367 (!CurrentRegionOnly && CI != CE && SI == SE);
10368
10369 return false;
10370 });
10371
10372 if (CurrentRegionOnly)
10373 return FoundError;
10374
10375 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10376 // If any part of the original storage of a list item has corresponding
10377 // storage in the device data environment, all of the original storage must
10378 // have corresponding storage in the device data environment.
10379 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10380 // If a list item is an element of a structure, and a different element of
10381 // the structure has a corresponding list item in the device data environment
10382 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010383 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010384 // data environment prior to the task encountering the construct.
10385 //
10386 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10387 SemaRef.Diag(ELoc,
10388 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10389 << ERange;
10390 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10391 << EnclosingExpr->getSourceRange();
10392 return true;
10393 }
10394
10395 return FoundError;
10396}
10397
Samuel Antao661c0902016-05-26 17:39:58 +000010398namespace {
10399// Utility struct that gathers all the related lists associated with a mappable
10400// expression.
10401struct MappableVarListInfo final {
10402 // The list of expressions.
10403 ArrayRef<Expr *> VarList;
10404 // The list of processed expressions.
10405 SmallVector<Expr *, 16> ProcessedVarList;
10406 // The mappble components for each expression.
10407 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10408 // The base declaration of the variable.
10409 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10410
10411 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10412 // We have a list of components and base declarations for each entry in the
10413 // variable list.
10414 VarComponents.reserve(VarList.size());
10415 VarBaseDeclarations.reserve(VarList.size());
10416 }
10417};
10418}
10419
10420// Check the validity of the provided variable list for the provided clause kind
10421// \a CKind. In the check process the valid expressions, and mappable expression
10422// components and variables are extracted and used to fill \a Vars,
10423// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10424// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10425static void
10426checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10427 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10428 SourceLocation StartLoc,
10429 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10430 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010431 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10432 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010433 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010434
Samuel Antao90927002016-04-26 14:54:23 +000010435 // Keep track of the mappable components and base declarations in this clause.
10436 // Each entry in the list is going to have a list of components associated. We
10437 // record each set of the components so that we can build the clause later on.
10438 // In the end we should have the same amount of declarations and component
10439 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010440
Samuel Antao661c0902016-05-26 17:39:58 +000010441 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010442 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010443 SourceLocation ELoc = RE->getExprLoc();
10444
Kelvin Li0bff7af2015-11-23 05:32:03 +000010445 auto *VE = RE->IgnoreParenLValueCasts();
10446
10447 if (VE->isValueDependent() || VE->isTypeDependent() ||
10448 VE->isInstantiationDependent() ||
10449 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010450 // We can only analyze this information once the missing information is
10451 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010452 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010453 continue;
10454 }
10455
10456 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010457
Samuel Antao5de996e2016-01-22 20:21:36 +000010458 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010459 SemaRef.Diag(ELoc,
10460 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010461 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010462 continue;
10463 }
10464
Samuel Antao90927002016-04-26 14:54:23 +000010465 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10466 ValueDecl *CurDeclaration = nullptr;
10467
10468 // Obtain the array or member expression bases if required. Also, fill the
10469 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010470 auto *BE =
10471 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010472 if (!BE)
10473 continue;
10474
Samuel Antao90927002016-04-26 14:54:23 +000010475 assert(!CurComponents.empty() &&
10476 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010477
Samuel Antao90927002016-04-26 14:54:23 +000010478 // For the following checks, we rely on the base declaration which is
10479 // expected to be associated with the last component. The declaration is
10480 // expected to be a variable or a field (if 'this' is being mapped).
10481 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10482 assert(CurDeclaration && "Null decl on map clause.");
10483 assert(
10484 CurDeclaration->isCanonicalDecl() &&
10485 "Expecting components to have associated only canonical declarations.");
10486
10487 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10488 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010489
10490 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010491 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010492
10493 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010494 // threadprivate variables cannot appear in a map clause.
10495 // OpenMP 4.5 [2.10.5, target update Construct]
10496 // threadprivate variables cannot appear in a from clause.
10497 if (VD && DSAS->isThreadPrivate(VD)) {
10498 auto DVar = DSAS->getTopDSA(VD, false);
10499 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10500 << getOpenMPClauseName(CKind);
10501 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010502 continue;
10503 }
10504
Samuel Antao5de996e2016-01-22 20:21:36 +000010505 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10506 // A list item cannot appear in both a map clause and a data-sharing
10507 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010508
Samuel Antao5de996e2016-01-22 20:21:36 +000010509 // Check conflicts with other map clause expressions. We check the conflicts
10510 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010511 // environment, because the restrictions are different. We only have to
10512 // check conflicts across regions for the map clauses.
10513 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10514 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010515 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010516 if (CKind == OMPC_map &&
10517 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10518 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010519 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010520
Samuel Antao661c0902016-05-26 17:39:58 +000010521 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010522 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10523 // If the type of a list item is a reference to a type T then the type will
10524 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010525 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010526
Samuel Antao661c0902016-05-26 17:39:58 +000010527 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10528 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010529 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010530 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010531 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10532 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010533 continue;
10534
Samuel Antao661c0902016-05-26 17:39:58 +000010535 if (CKind == OMPC_map) {
10536 // target enter data
10537 // OpenMP [2.10.2, Restrictions, p. 99]
10538 // A map-type must be specified in all map clauses and must be either
10539 // to or alloc.
10540 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10541 if (DKind == OMPD_target_enter_data &&
10542 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10543 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10544 << (IsMapTypeImplicit ? 1 : 0)
10545 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10546 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010547 continue;
10548 }
Samuel Antao661c0902016-05-26 17:39:58 +000010549
10550 // target exit_data
10551 // OpenMP [2.10.3, Restrictions, p. 102]
10552 // A map-type must be specified in all map clauses and must be either
10553 // from, release, or delete.
10554 if (DKind == OMPD_target_exit_data &&
10555 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10556 MapType == OMPC_MAP_delete)) {
10557 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10558 << (IsMapTypeImplicit ? 1 : 0)
10559 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10560 << getOpenMPDirectiveName(DKind);
10561 continue;
10562 }
10563
10564 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10565 // A list item cannot appear in both a map clause and a data-sharing
10566 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010567 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010568 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010569 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010570 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10571 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010572 auto DVar = DSAS->getTopDSA(VD, false);
10573 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010574 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010575 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010576 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010577 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10578 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10579 continue;
10580 }
10581 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010582 }
10583
Samuel Antao90927002016-04-26 14:54:23 +000010584 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010585 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010586
10587 // Store the components in the stack so that they can be used to check
10588 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010589 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10590 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010591
10592 // Save the components and declaration to create the clause. For purposes of
10593 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010594 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010595 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10596 MVLI.VarComponents.back().append(CurComponents.begin(),
10597 CurComponents.end());
10598 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10599 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010600 }
Samuel Antao661c0902016-05-26 17:39:58 +000010601}
10602
10603OMPClause *
10604Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10605 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10606 SourceLocation MapLoc, SourceLocation ColonLoc,
10607 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10608 SourceLocation LParenLoc, SourceLocation EndLoc) {
10609 MappableVarListInfo MVLI(VarList);
10610 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10611 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010612
Samuel Antao5de996e2016-01-22 20:21:36 +000010613 // We need to produce a map clause even if we don't have variables so that
10614 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010615 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10616 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10617 MVLI.VarComponents, MapTypeModifier, MapType,
10618 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010619}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010620
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010621QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10622 TypeResult ParsedType) {
10623 assert(ParsedType.isUsable());
10624
10625 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10626 if (ReductionType.isNull())
10627 return QualType();
10628
10629 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10630 // A type name in a declare reduction directive cannot be a function type, an
10631 // array type, a reference type, or a type qualified with const, volatile or
10632 // restrict.
10633 if (ReductionType.hasQualifiers()) {
10634 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10635 return QualType();
10636 }
10637
10638 if (ReductionType->isFunctionType()) {
10639 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10640 return QualType();
10641 }
10642 if (ReductionType->isReferenceType()) {
10643 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10644 return QualType();
10645 }
10646 if (ReductionType->isArrayType()) {
10647 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10648 return QualType();
10649 }
10650 return ReductionType;
10651}
10652
10653Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10654 Scope *S, DeclContext *DC, DeclarationName Name,
10655 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10656 AccessSpecifier AS, Decl *PrevDeclInScope) {
10657 SmallVector<Decl *, 8> Decls;
10658 Decls.reserve(ReductionTypes.size());
10659
10660 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10661 ForRedeclaration);
10662 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10663 // A reduction-identifier may not be re-declared in the current scope for the
10664 // same type or for a type that is compatible according to the base language
10665 // rules.
10666 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10667 OMPDeclareReductionDecl *PrevDRD = nullptr;
10668 bool InCompoundScope = true;
10669 if (S != nullptr) {
10670 // Find previous declaration with the same name not referenced in other
10671 // declarations.
10672 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10673 InCompoundScope =
10674 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10675 LookupName(Lookup, S);
10676 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10677 /*AllowInlineNamespace=*/false);
10678 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10679 auto Filter = Lookup.makeFilter();
10680 while (Filter.hasNext()) {
10681 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10682 if (InCompoundScope) {
10683 auto I = UsedAsPrevious.find(PrevDecl);
10684 if (I == UsedAsPrevious.end())
10685 UsedAsPrevious[PrevDecl] = false;
10686 if (auto *D = PrevDecl->getPrevDeclInScope())
10687 UsedAsPrevious[D] = true;
10688 }
10689 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10690 PrevDecl->getLocation();
10691 }
10692 Filter.done();
10693 if (InCompoundScope) {
10694 for (auto &PrevData : UsedAsPrevious) {
10695 if (!PrevData.second) {
10696 PrevDRD = PrevData.first;
10697 break;
10698 }
10699 }
10700 }
10701 } else if (PrevDeclInScope != nullptr) {
10702 auto *PrevDRDInScope = PrevDRD =
10703 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10704 do {
10705 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10706 PrevDRDInScope->getLocation();
10707 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10708 } while (PrevDRDInScope != nullptr);
10709 }
10710 for (auto &TyData : ReductionTypes) {
10711 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10712 bool Invalid = false;
10713 if (I != PreviousRedeclTypes.end()) {
10714 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10715 << TyData.first;
10716 Diag(I->second, diag::note_previous_definition);
10717 Invalid = true;
10718 }
10719 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10720 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10721 Name, TyData.first, PrevDRD);
10722 DC->addDecl(DRD);
10723 DRD->setAccess(AS);
10724 Decls.push_back(DRD);
10725 if (Invalid)
10726 DRD->setInvalidDecl();
10727 else
10728 PrevDRD = DRD;
10729 }
10730
10731 return DeclGroupPtrTy::make(
10732 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10733}
10734
10735void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10736 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10737
10738 // Enter new function scope.
10739 PushFunctionScope();
10740 getCurFunction()->setHasBranchProtectedScope();
10741 getCurFunction()->setHasOMPDeclareReductionCombiner();
10742
10743 if (S != nullptr)
10744 PushDeclContext(S, DRD);
10745 else
10746 CurContext = DRD;
10747
10748 PushExpressionEvaluationContext(PotentiallyEvaluated);
10749
10750 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010751 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10752 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10753 // uses semantics of argument handles by value, but it should be passed by
10754 // reference. C lang does not support references, so pass all parameters as
10755 // pointers.
10756 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010757 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010758 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010759 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10760 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10761 // uses semantics of argument handles by value, but it should be passed by
10762 // reference. C lang does not support references, so pass all parameters as
10763 // pointers.
10764 // Create 'T omp_out;' variable.
10765 auto *OmpOutParm =
10766 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10767 if (S != nullptr) {
10768 PushOnScopeChains(OmpInParm, S);
10769 PushOnScopeChains(OmpOutParm, S);
10770 } else {
10771 DRD->addDecl(OmpInParm);
10772 DRD->addDecl(OmpOutParm);
10773 }
10774}
10775
10776void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10777 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10778 DiscardCleanupsInEvaluationContext();
10779 PopExpressionEvaluationContext();
10780
10781 PopDeclContext();
10782 PopFunctionScopeInfo();
10783
10784 if (Combiner != nullptr)
10785 DRD->setCombiner(Combiner);
10786 else
10787 DRD->setInvalidDecl();
10788}
10789
10790void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10791 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10792
10793 // Enter new function scope.
10794 PushFunctionScope();
10795 getCurFunction()->setHasBranchProtectedScope();
10796
10797 if (S != nullptr)
10798 PushDeclContext(S, DRD);
10799 else
10800 CurContext = DRD;
10801
10802 PushExpressionEvaluationContext(PotentiallyEvaluated);
10803
10804 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010805 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10806 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10807 // uses semantics of argument handles by value, but it should be passed by
10808 // reference. C lang does not support references, so pass all parameters as
10809 // pointers.
10810 // Create 'T omp_priv;' variable.
10811 auto *OmpPrivParm =
10812 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010813 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10814 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10815 // uses semantics of argument handles by value, but it should be passed by
10816 // reference. C lang does not support references, so pass all parameters as
10817 // pointers.
10818 // Create 'T omp_orig;' variable.
10819 auto *OmpOrigParm =
10820 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010821 if (S != nullptr) {
10822 PushOnScopeChains(OmpPrivParm, S);
10823 PushOnScopeChains(OmpOrigParm, S);
10824 } else {
10825 DRD->addDecl(OmpPrivParm);
10826 DRD->addDecl(OmpOrigParm);
10827 }
10828}
10829
10830void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10831 Expr *Initializer) {
10832 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10833 DiscardCleanupsInEvaluationContext();
10834 PopExpressionEvaluationContext();
10835
10836 PopDeclContext();
10837 PopFunctionScopeInfo();
10838
10839 if (Initializer != nullptr)
10840 DRD->setInitializer(Initializer);
10841 else
10842 DRD->setInvalidDecl();
10843}
10844
10845Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10846 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10847 for (auto *D : DeclReductions.get()) {
10848 if (IsValid) {
10849 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10850 if (S != nullptr)
10851 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10852 } else
10853 D->setInvalidDecl();
10854 }
10855 return DeclReductions;
10856}
10857
David Majnemer9d168222016-08-05 17:44:54 +000010858OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010859 SourceLocation StartLoc,
10860 SourceLocation LParenLoc,
10861 SourceLocation EndLoc) {
10862 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010863
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010864 // OpenMP [teams Constrcut, Restrictions]
10865 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010866 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10867 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010868 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010869
10870 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10871}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010872
10873OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10874 SourceLocation StartLoc,
10875 SourceLocation LParenLoc,
10876 SourceLocation EndLoc) {
10877 Expr *ValExpr = ThreadLimit;
10878
10879 // OpenMP [teams Constrcut, Restrictions]
10880 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010881 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10882 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010883 return nullptr;
10884
David Majnemer9d168222016-08-05 17:44:54 +000010885 return new (Context)
10886 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010887}
Alexey Bataeva0569352015-12-01 10:17:31 +000010888
10889OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10890 SourceLocation StartLoc,
10891 SourceLocation LParenLoc,
10892 SourceLocation EndLoc) {
10893 Expr *ValExpr = Priority;
10894
10895 // OpenMP [2.9.1, task Constrcut]
10896 // The priority-value is a non-negative numerical scalar expression.
10897 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10898 /*StrictlyPositive=*/false))
10899 return nullptr;
10900
10901 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10902}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010903
10904OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10905 SourceLocation StartLoc,
10906 SourceLocation LParenLoc,
10907 SourceLocation EndLoc) {
10908 Expr *ValExpr = Grainsize;
10909
10910 // OpenMP [2.9.2, taskloop Constrcut]
10911 // The parameter of the grainsize clause must be a positive integer
10912 // expression.
10913 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10914 /*StrictlyPositive=*/true))
10915 return nullptr;
10916
10917 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10918}
Alexey Bataev382967a2015-12-08 12:06:20 +000010919
10920OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10921 SourceLocation StartLoc,
10922 SourceLocation LParenLoc,
10923 SourceLocation EndLoc) {
10924 Expr *ValExpr = NumTasks;
10925
10926 // OpenMP [2.9.2, taskloop Constrcut]
10927 // The parameter of the num_tasks clause must be a positive integer
10928 // expression.
10929 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10930 /*StrictlyPositive=*/true))
10931 return nullptr;
10932
10933 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10934}
10935
Alexey Bataev28c75412015-12-15 08:19:24 +000010936OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10937 SourceLocation LParenLoc,
10938 SourceLocation EndLoc) {
10939 // OpenMP [2.13.2, critical construct, Description]
10940 // ... where hint-expression is an integer constant expression that evaluates
10941 // to a valid lock hint.
10942 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10943 if (HintExpr.isInvalid())
10944 return nullptr;
10945 return new (Context)
10946 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10947}
10948
Carlo Bertollib4adf552016-01-15 18:50:31 +000010949OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10950 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10951 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10952 SourceLocation EndLoc) {
10953 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10954 std::string Values;
10955 Values += "'";
10956 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10957 Values += "'";
10958 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10959 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10960 return nullptr;
10961 }
10962 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010963 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010964 if (ChunkSize) {
10965 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10966 !ChunkSize->isInstantiationDependent() &&
10967 !ChunkSize->containsUnexpandedParameterPack()) {
10968 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10969 ExprResult Val =
10970 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10971 if (Val.isInvalid())
10972 return nullptr;
10973
10974 ValExpr = Val.get();
10975
10976 // OpenMP [2.7.1, Restrictions]
10977 // chunk_size must be a loop invariant integer expression with a positive
10978 // value.
10979 llvm::APSInt Result;
10980 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10981 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10982 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10983 << "dist_schedule" << ChunkSize->getSourceRange();
10984 return nullptr;
10985 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010986 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10987 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010988 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10989 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10990 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010991 }
10992 }
10993 }
10994
10995 return new (Context)
10996 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010997 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010998}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010999
11000OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11001 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11002 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11003 SourceLocation KindLoc, SourceLocation EndLoc) {
11004 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011005 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011006 std::string Value;
11007 SourceLocation Loc;
11008 Value += "'";
11009 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11010 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011011 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011012 Loc = MLoc;
11013 } else {
11014 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011015 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011016 Loc = KindLoc;
11017 }
11018 Value += "'";
11019 Diag(Loc, diag::err_omp_unexpected_clause_value)
11020 << Value << getOpenMPClauseName(OMPC_defaultmap);
11021 return nullptr;
11022 }
11023
11024 return new (Context)
11025 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11026}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011027
11028bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11029 DeclContext *CurLexicalContext = getCurLexicalContext();
11030 if (!CurLexicalContext->isFileContext() &&
11031 !CurLexicalContext->isExternCContext() &&
11032 !CurLexicalContext->isExternCXXContext()) {
11033 Diag(Loc, diag::err_omp_region_not_file_context);
11034 return false;
11035 }
11036 if (IsInOpenMPDeclareTargetContext) {
11037 Diag(Loc, diag::err_omp_enclosed_declare_target);
11038 return false;
11039 }
11040
11041 IsInOpenMPDeclareTargetContext = true;
11042 return true;
11043}
11044
11045void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11046 assert(IsInOpenMPDeclareTargetContext &&
11047 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11048
11049 IsInOpenMPDeclareTargetContext = false;
11050}
11051
David Majnemer9d168222016-08-05 17:44:54 +000011052void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11053 CXXScopeSpec &ScopeSpec,
11054 const DeclarationNameInfo &Id,
11055 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11056 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011057 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11058 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11059
11060 if (Lookup.isAmbiguous())
11061 return;
11062 Lookup.suppressDiagnostics();
11063
11064 if (!Lookup.isSingleResult()) {
11065 if (TypoCorrection Corrected =
11066 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11067 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11068 CTK_ErrorRecovery)) {
11069 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11070 << Id.getName());
11071 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11072 return;
11073 }
11074
11075 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11076 return;
11077 }
11078
11079 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11080 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11081 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11082 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11083
11084 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11085 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11086 ND->addAttr(A);
11087 if (ASTMutationListener *ML = Context.getASTMutationListener())
11088 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11089 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11090 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11091 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11092 << Id.getName();
11093 }
11094 } else
11095 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11096}
11097
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011098static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11099 Sema &SemaRef, Decl *D) {
11100 if (!D)
11101 return;
11102 Decl *LD = nullptr;
11103 if (isa<TagDecl>(D)) {
11104 LD = cast<TagDecl>(D)->getDefinition();
11105 } else if (isa<VarDecl>(D)) {
11106 LD = cast<VarDecl>(D)->getDefinition();
11107
11108 // If this is an implicit variable that is legal and we do not need to do
11109 // anything.
11110 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011111 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11112 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11113 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011114 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011115 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011116 return;
11117 }
11118
11119 } else if (isa<FunctionDecl>(D)) {
11120 const FunctionDecl *FD = nullptr;
11121 if (cast<FunctionDecl>(D)->hasBody(FD))
11122 LD = const_cast<FunctionDecl *>(FD);
11123
11124 // If the definition is associated with the current declaration in the
11125 // target region (it can be e.g. a lambda) that is legal and we do not need
11126 // to do anything else.
11127 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011128 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11129 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11130 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011131 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011132 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011133 return;
11134 }
11135 }
11136 if (!LD)
11137 LD = D;
11138 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11139 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11140 // Outlined declaration is not declared target.
11141 if (LD->isOutOfLine()) {
11142 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11143 SemaRef.Diag(SL, diag::note_used_here) << SR;
11144 } else {
11145 DeclContext *DC = LD->getDeclContext();
11146 while (DC) {
11147 if (isa<FunctionDecl>(DC) &&
11148 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11149 break;
11150 DC = DC->getParent();
11151 }
11152 if (DC)
11153 return;
11154
11155 // Is not declared in target context.
11156 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11157 SemaRef.Diag(SL, diag::note_used_here) << SR;
11158 }
11159 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011160 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11161 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11162 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011163 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011164 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011165 }
11166}
11167
11168static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11169 Sema &SemaRef, DSAStackTy *Stack,
11170 ValueDecl *VD) {
11171 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11172 return true;
11173 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11174 return false;
11175 return true;
11176}
11177
11178void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11179 if (!D || D->isInvalidDecl())
11180 return;
11181 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11182 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11183 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11184 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11185 if (DSAStack->isThreadPrivate(VD)) {
11186 Diag(SL, diag::err_omp_threadprivate_in_target);
11187 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11188 return;
11189 }
11190 }
11191 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11192 // Problem if any with var declared with incomplete type will be reported
11193 // as normal, so no need to check it here.
11194 if ((E || !VD->getType()->isIncompleteType()) &&
11195 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11196 // Mark decl as declared target to prevent further diagnostic.
11197 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011198 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11199 Context, OMPDeclareTargetDeclAttr::MT_To);
11200 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011201 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011202 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011203 }
11204 return;
11205 }
11206 }
11207 if (!E) {
11208 // Checking declaration inside declare target region.
11209 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11210 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011211 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11212 Context, OMPDeclareTargetDeclAttr::MT_To);
11213 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011214 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011215 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011216 }
11217 return;
11218 }
11219 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11220}
Samuel Antao661c0902016-05-26 17:39:58 +000011221
11222OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11223 SourceLocation StartLoc,
11224 SourceLocation LParenLoc,
11225 SourceLocation EndLoc) {
11226 MappableVarListInfo MVLI(VarList);
11227 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11228 if (MVLI.ProcessedVarList.empty())
11229 return nullptr;
11230
11231 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11232 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11233 MVLI.VarComponents);
11234}
Samuel Antaoec172c62016-05-26 17:49:04 +000011235
11236OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11237 SourceLocation StartLoc,
11238 SourceLocation LParenLoc,
11239 SourceLocation EndLoc) {
11240 MappableVarListInfo MVLI(VarList);
11241 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11242 if (MVLI.ProcessedVarList.empty())
11243 return nullptr;
11244
11245 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11246 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11247 MVLI.VarComponents);
11248}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011249
11250OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11251 SourceLocation StartLoc,
11252 SourceLocation LParenLoc,
11253 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011254 MappableVarListInfo MVLI(VarList);
11255 SmallVector<Expr *, 8> PrivateCopies;
11256 SmallVector<Expr *, 8> Inits;
11257
Carlo Bertolli2404b172016-07-13 15:37:16 +000011258 for (auto &RefExpr : VarList) {
11259 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11260 SourceLocation ELoc;
11261 SourceRange ERange;
11262 Expr *SimpleRefExpr = RefExpr;
11263 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11264 if (Res.second) {
11265 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011266 MVLI.ProcessedVarList.push_back(RefExpr);
11267 PrivateCopies.push_back(nullptr);
11268 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011269 }
11270 ValueDecl *D = Res.first;
11271 if (!D)
11272 continue;
11273
11274 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011275 Type = Type.getNonReferenceType().getUnqualifiedType();
11276
11277 auto *VD = dyn_cast<VarDecl>(D);
11278
11279 // Item should be a pointer or reference to pointer.
11280 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011281 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11282 << 0 << RefExpr->getSourceRange();
11283 continue;
11284 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011285
11286 // Build the private variable and the expression that refers to it.
11287 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11288 D->hasAttrs() ? &D->getAttrs() : nullptr);
11289 if (VDPrivate->isInvalidDecl())
11290 continue;
11291
11292 CurContext->addDecl(VDPrivate);
11293 auto VDPrivateRefExpr = buildDeclRefExpr(
11294 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11295
11296 // Add temporary variable to initialize the private copy of the pointer.
11297 auto *VDInit =
11298 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11299 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11300 RefExpr->getExprLoc());
11301 AddInitializerToDecl(VDPrivate,
11302 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011303 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011304
11305 // If required, build a capture to implement the privatization initialized
11306 // with the current list item value.
11307 DeclRefExpr *Ref = nullptr;
11308 if (!VD)
11309 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11310 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11311 PrivateCopies.push_back(VDPrivateRefExpr);
11312 Inits.push_back(VDInitRefExpr);
11313
11314 // We need to add a data sharing attribute for this variable to make sure it
11315 // is correctly captured. A variable that shows up in a use_device_ptr has
11316 // similar properties of a first private variable.
11317 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11318
11319 // Create a mappable component for the list item. List items in this clause
11320 // only need a component.
11321 MVLI.VarBaseDeclarations.push_back(D);
11322 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11323 MVLI.VarComponents.back().push_back(
11324 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011325 }
11326
Samuel Antaocc10b852016-07-28 14:23:26 +000011327 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011328 return nullptr;
11329
Samuel Antaocc10b852016-07-28 14:23:26 +000011330 return OMPUseDevicePtrClause::Create(
11331 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11332 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011333}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011334
11335OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11336 SourceLocation StartLoc,
11337 SourceLocation LParenLoc,
11338 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011339 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011340 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011341 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011342 SourceLocation ELoc;
11343 SourceRange ERange;
11344 Expr *SimpleRefExpr = RefExpr;
11345 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11346 if (Res.second) {
11347 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011348 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011349 }
11350 ValueDecl *D = Res.first;
11351 if (!D)
11352 continue;
11353
11354 QualType Type = D->getType();
11355 // item should be a pointer or array or reference to pointer or array
11356 if (!Type.getNonReferenceType()->isPointerType() &&
11357 !Type.getNonReferenceType()->isArrayType()) {
11358 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11359 << 0 << RefExpr->getSourceRange();
11360 continue;
11361 }
Samuel Antao6890b092016-07-28 14:25:09 +000011362
11363 // Check if the declaration in the clause does not show up in any data
11364 // sharing attribute.
11365 auto DVar = DSAStack->getTopDSA(D, false);
11366 if (isOpenMPPrivate(DVar.CKind)) {
11367 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11368 << getOpenMPClauseName(DVar.CKind)
11369 << getOpenMPClauseName(OMPC_is_device_ptr)
11370 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11371 ReportOriginalDSA(*this, DSAStack, D, DVar);
11372 continue;
11373 }
11374
11375 Expr *ConflictExpr;
11376 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011377 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011378 [&ConflictExpr](
11379 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11380 OpenMPClauseKind) -> bool {
11381 ConflictExpr = R.front().getAssociatedExpression();
11382 return true;
11383 })) {
11384 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11385 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11386 << ConflictExpr->getSourceRange();
11387 continue;
11388 }
11389
11390 // Store the components in the stack so that they can be used to check
11391 // against other clauses later on.
11392 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11393 DSAStack->addMappableExpressionComponents(
11394 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11395
11396 // Record the expression we've just processed.
11397 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11398
11399 // Create a mappable component for the list item. List items in this clause
11400 // only need a component. We use a null declaration to signal fields in
11401 // 'this'.
11402 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11403 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11404 "Unexpected device pointer expression!");
11405 MVLI.VarBaseDeclarations.push_back(
11406 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11407 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11408 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011409 }
11410
Samuel Antao6890b092016-07-28 14:25:09 +000011411 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011412 return nullptr;
11413
Samuel Antao6890b092016-07-28 14:25:09 +000011414 return OMPIsDevicePtrClause::Create(
11415 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11416 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011417}