blob: f8d1956a2d482d6adda03ef02c5416acf678690e [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);
Alexey Bataev38e89532015-04-16 04:54:05 +00001092 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093 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:
Kelvin Libf594a52016-12-17 05:48:59 +00001597 case OMPD_teams:
1598 case OMPD_target_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001602 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001609 break;
1610 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001611 case OMPD_simd:
1612 case OMPD_for:
1613 case OMPD_for_simd:
1614 case OMPD_sections:
1615 case OMPD_section:
1616 case OMPD_single:
1617 case OMPD_master:
1618 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001619 case OMPD_taskgroup:
1620 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001621 case OMPD_ordered:
1622 case OMPD_atomic:
1623 case OMPD_target_data:
1624 case OMPD_target:
1625 case OMPD_target_parallel:
1626 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001627 case OMPD_target_parallel_for_simd:
1628 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001629 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001630 std::make_pair(StringRef(), QualType()) // __context with shared vars
1631 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001632 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1633 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001634 break;
1635 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001636 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001637 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001638 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1639 FunctionProtoType::ExtProtoInfo EPI;
1640 EPI.Variadic = true;
1641 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001642 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001643 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001644 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1645 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1646 std::make_pair(".copy_fn.",
1647 Context.getPointerType(CopyFnType).withConst()),
1648 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1650 };
1651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001653 // Mark this captured region as inlined, because we don't use outlined
1654 // function directly.
1655 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1656 AlwaysInlineAttr::CreateImplicit(
1657 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001658 break;
1659 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001660 case OMPD_taskloop:
1661 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001662 QualType KmpInt32Ty =
1663 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1664 QualType KmpUInt64Ty =
1665 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1666 QualType KmpInt64Ty =
1667 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1668 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1669 FunctionProtoType::ExtProtoInfo EPI;
1670 EPI.Variadic = true;
1671 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001672 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001673 std::make_pair(".global_tid.", KmpInt32Ty),
1674 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1675 std::make_pair(".privates.",
1676 Context.VoidPtrTy.withConst().withRestrict()),
1677 std::make_pair(
1678 ".copy_fn.",
1679 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1680 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1681 std::make_pair(".lb.", KmpUInt64Ty),
1682 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1683 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001684 std::make_pair(StringRef(), QualType()) // __context with shared vars
1685 };
1686 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1687 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001688 // Mark this captured region as inlined, because we don't use outlined
1689 // function directly.
1690 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1691 AlwaysInlineAttr::CreateImplicit(
1692 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001693 break;
1694 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001695 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001696 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001697 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001698 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001699 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001700 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001701 case OMPD_teams_distribute_parallel_for:
1702 case OMPD_target_teams_distribute: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001703 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1704 QualType KmpInt32PtrTy =
1705 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1706 Sema::CapturedParamNameType Params[] = {
1707 std::make_pair(".global_tid.", KmpInt32PtrTy),
1708 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1709 std::make_pair(".previous.lb.", Context.getSizeType()),
1710 std::make_pair(".previous.ub.", Context.getSizeType()),
1711 std::make_pair(StringRef(), QualType()) // __context with shared vars
1712 };
1713 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1714 Params);
1715 break;
1716 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001717 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001718 case OMPD_taskyield:
1719 case OMPD_barrier:
1720 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001721 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001722 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001723 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001724 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001725 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001726 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001727 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001728 case OMPD_declare_target:
1729 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001730 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001731 llvm_unreachable("OpenMP Directive is not allowed");
1732 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001733 llvm_unreachable("Unknown OpenMP directive");
1734 }
1735}
1736
Alexey Bataev3392d762016-02-16 11:18:12 +00001737static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001738 Expr *CaptureExpr, bool WithInit,
1739 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001740 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001741 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001742 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001743 QualType Ty = Init->getType();
1744 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1745 if (S.getLangOpts().CPlusPlus)
1746 Ty = C.getLValueReferenceType(Ty);
1747 else {
1748 Ty = C.getPointerType(Ty);
1749 ExprResult Res =
1750 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1751 if (!Res.isUsable())
1752 return nullptr;
1753 Init = Res.get();
1754 }
Alexey Bataev61205072016-03-02 04:57:40 +00001755 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001756 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001757 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1758 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001759 if (!WithInit)
1760 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001761 S.CurContext->addHiddenDecl(CED);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001762 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1763 /*TypeMayContainAuto=*/true);
Alexey Bataev3392d762016-02-16 11:18:12 +00001764 return CED;
1765}
1766
Alexey Bataev61205072016-03-02 04:57:40 +00001767static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1768 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001769 OMPCapturedExprDecl *CD;
1770 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1771 CD = cast<OMPCapturedExprDecl>(VD);
1772 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001773 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1774 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001775 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001776 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001777}
1778
Alexey Bataev5a3af132016-03-29 08:58:54 +00001779static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1780 if (!Ref) {
1781 auto *CD =
1782 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1783 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1784 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1785 CaptureExpr->getExprLoc());
1786 }
1787 ExprResult Res = Ref;
1788 if (!S.getLangOpts().CPlusPlus &&
1789 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1790 Ref->getType()->isPointerType())
1791 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1792 if (!Res.isUsable())
1793 return ExprError();
1794 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001795}
1796
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001797StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1798 ArrayRef<OMPClause *> Clauses) {
1799 if (!S.isUsable()) {
1800 ActOnCapturedRegionError();
1801 return StmtError();
1802 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001803
1804 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001805 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001806 SmallVector<OMPLinearClause *, 4> LCs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001807 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001808 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001809 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001810 Clause->getClauseKind() == OMPC_copyprivate ||
1811 (getLangOpts().OpenMPUseTLS &&
1812 getASTContext().getTargetInfo().isTLSSupported() &&
1813 Clause->getClauseKind() == OMPC_copyin)) {
1814 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001815 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001816 for (auto *VarRef : Clause->children()) {
1817 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001818 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001819 }
1820 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001821 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001822 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Alexey Bataev040d5402015-05-12 08:35:28 +00001823 // Mark all variables in private list clauses as used in inner region.
1824 // Required for proper codegen of combined directives.
1825 // TODO: add processing for other clauses.
Alexey Bataev3392d762016-02-16 11:18:12 +00001826 if (auto *C = OMPClauseWithPreInit::get(Clause)) {
Alexey Bataev005248a2016-02-25 05:25:57 +00001827 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1828 for (auto *D : DS->decls())
Alexey Bataev3392d762016-02-16 11:18:12 +00001829 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1830 }
Alexey Bataev4244be22016-02-11 05:35:55 +00001831 }
Alexey Bataev005248a2016-02-25 05:25:57 +00001832 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1833 if (auto *E = C->getPostUpdateExpr())
1834 MarkDeclarationsReferencedInExpr(E);
1835 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001836 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001837 if (Clause->getClauseKind() == OMPC_schedule)
1838 SC = cast<OMPScheduleClause>(Clause);
1839 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001840 OC = cast<OMPOrderedClause>(Clause);
1841 else if (Clause->getClauseKind() == OMPC_linear)
1842 LCs.push_back(cast<OMPLinearClause>(Clause));
1843 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001844 bool ErrorFound = false;
1845 // OpenMP, 2.7.1 Loop Construct, Restrictions
1846 // The nonmonotonic modifier cannot be specified if an ordered clause is
1847 // specified.
1848 if (SC &&
1849 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1850 SC->getSecondScheduleModifier() ==
1851 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1852 OC) {
1853 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1854 ? SC->getFirstScheduleModifierLoc()
1855 : SC->getSecondScheduleModifierLoc(),
1856 diag::err_omp_schedule_nonmonotonic_ordered)
1857 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1858 ErrorFound = true;
1859 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001860 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1861 for (auto *C : LCs) {
1862 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1863 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1864 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001865 ErrorFound = true;
1866 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001867 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1868 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1869 OC->getNumForLoops()) {
1870 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1871 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1872 ErrorFound = true;
1873 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001874 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001875 ActOnCapturedRegionError();
1876 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001877 }
1878 return ActOnCapturedRegionEnd(S.get());
1879}
1880
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001881static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1882 OpenMPDirectiveKind CurrentRegion,
1883 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001884 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001885 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001886 if (Stack->getCurScope()) {
1887 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001888 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001889 bool NestingProhibited = false;
1890 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001891 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001892 enum {
1893 NoRecommend,
1894 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001895 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001896 ShouldBeInTargetRegion,
1897 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001898 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001899 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001900 // OpenMP [2.16, Nesting of Regions]
1901 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001902 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001903 // An ordered construct with the simd clause is the only OpenMP
1904 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001905 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001906 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1907 // message.
1908 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1909 ? diag::err_omp_prohibited_region_simd
1910 : diag::warn_omp_nesting_simd);
1911 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001912 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001913 if (ParentRegion == OMPD_atomic) {
1914 // OpenMP [2.16, Nesting of Regions]
1915 // OpenMP constructs may not be nested inside an atomic region.
1916 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1917 return true;
1918 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001919 if (CurrentRegion == OMPD_section) {
1920 // OpenMP [2.7.2, sections Construct, Restrictions]
1921 // Orphaned section directives are prohibited. That is, the section
1922 // directives must appear within the sections construct and must not be
1923 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00001924 if (ParentRegion != OMPD_sections &&
1925 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001926 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1927 << (ParentRegion != OMPD_unknown)
1928 << getOpenMPDirectiveName(ParentRegion);
1929 return true;
1930 }
1931 return false;
1932 }
Kelvin Li2b51f722016-07-26 04:32:50 +00001933 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00001934 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00001935 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00001936 if (ParentRegion == OMPD_unknown &&
1937 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001938 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00001939 if (CurrentRegion == OMPD_cancellation_point ||
1940 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001941 // OpenMP [2.16, Nesting of Regions]
1942 // A cancellation point construct for which construct-type-clause is
1943 // taskgroup must be nested inside a task construct. A cancellation
1944 // point construct for which construct-type-clause is not taskgroup must
1945 // be closely nested inside an OpenMP construct that matches the type
1946 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00001947 // A cancel construct for which construct-type-clause is taskgroup must be
1948 // nested inside a task construct. A cancel construct for which
1949 // construct-type-clause is not taskgroup must be closely nested inside an
1950 // OpenMP construct that matches the type specified in
1951 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001952 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00001953 !((CancelRegion == OMPD_parallel &&
1954 (ParentRegion == OMPD_parallel ||
1955 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00001956 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00001957 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1958 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001959 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1960 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00001961 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1962 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001963 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00001964 // OpenMP [2.16, Nesting of Regions]
1965 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001966 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00001967 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00001968 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001969 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1970 // OpenMP [2.16, Nesting of Regions]
1971 // A critical region may not be nested (closely or otherwise) inside a
1972 // critical region with the same name. Note that this restriction is not
1973 // sufficient to prevent deadlock.
1974 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00001975 bool DeadLock = Stack->hasDirective(
1976 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1977 const DeclarationNameInfo &DNI,
1978 SourceLocation Loc) -> bool {
1979 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1980 PreviousCriticalLoc = Loc;
1981 return true;
1982 } else
1983 return false;
1984 },
1985 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001986 if (DeadLock) {
1987 SemaRef.Diag(StartLoc,
1988 diag::err_omp_prohibited_region_critical_same_name)
1989 << CurrentName.getName();
1990 if (PreviousCriticalLoc.isValid())
1991 SemaRef.Diag(PreviousCriticalLoc,
1992 diag::note_omp_previous_critical_region);
1993 return true;
1994 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00001995 } else if (CurrentRegion == OMPD_barrier) {
1996 // OpenMP [2.16, Nesting of Regions]
1997 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00001998 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001999 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2000 isOpenMPTaskingDirective(ParentRegion) ||
2001 ParentRegion == OMPD_master ||
2002 ParentRegion == OMPD_critical ||
2003 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002004 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002005 !isOpenMPParallelDirective(CurrentRegion) &&
2006 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002007 // OpenMP [2.16, Nesting of Regions]
2008 // A worksharing region may not be closely nested inside a worksharing,
2009 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002010 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2011 isOpenMPTaskingDirective(ParentRegion) ||
2012 ParentRegion == OMPD_master ||
2013 ParentRegion == OMPD_critical ||
2014 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002015 Recommend = ShouldBeInParallelRegion;
2016 } else if (CurrentRegion == OMPD_ordered) {
2017 // OpenMP [2.16, Nesting of Regions]
2018 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002019 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002020 // An ordered region must be closely nested inside a loop region (or
2021 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002022 // OpenMP [2.8.1,simd Construct, Restrictions]
2023 // An ordered construct with the simd clause is the only OpenMP construct
2024 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002025 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002026 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002027 !(isOpenMPSimdDirective(ParentRegion) ||
2028 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002029 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002030 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002031 // OpenMP [2.16, Nesting of Regions]
2032 // If specified, a teams construct must be contained within a target
2033 // construct.
2034 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002035 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002036 Recommend = ShouldBeInTargetRegion;
2037 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2038 }
Kelvin Libf594a52016-12-17 05:48:59 +00002039 if (!NestingProhibited &&
2040 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2041 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2042 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002043 // OpenMP [2.16, Nesting of Regions]
2044 // distribute, parallel, parallel sections, parallel workshare, and the
2045 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2046 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002047 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2048 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002049 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002050 }
David Majnemer9d168222016-08-05 17:44:54 +00002051 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002052 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002053 // OpenMP 4.5 [2.17 Nesting of Regions]
2054 // The region associated with the distribute construct must be strictly
2055 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002056 NestingProhibited =
2057 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002058 Recommend = ShouldBeInTeamsRegion;
2059 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002060 if (!NestingProhibited &&
2061 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2062 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2063 // OpenMP 4.5 [2.17 Nesting of Regions]
2064 // If a target, target update, target data, target enter data, or
2065 // target exit data construct is encountered during execution of a
2066 // target region, the behavior is unspecified.
2067 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002068 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2069 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002070 if (isOpenMPTargetExecutionDirective(K)) {
2071 OffendingRegion = K;
2072 return true;
2073 } else
2074 return false;
2075 },
2076 false /* don't skip top directive */);
2077 CloseNesting = false;
2078 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002079 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002080 if (OrphanSeen) {
2081 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2082 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2083 } else {
2084 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2085 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2086 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2087 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002088 return true;
2089 }
2090 }
2091 return false;
2092}
2093
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002094static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2095 ArrayRef<OMPClause *> Clauses,
2096 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2097 bool ErrorFound = false;
2098 unsigned NamedModifiersNumber = 0;
2099 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2100 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002101 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002102 for (const auto *C : Clauses) {
2103 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2104 // At most one if clause without a directive-name-modifier can appear on
2105 // the directive.
2106 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2107 if (FoundNameModifiers[CurNM]) {
2108 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2109 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2110 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2111 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002112 } else if (CurNM != OMPD_unknown) {
2113 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002114 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002115 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002116 FoundNameModifiers[CurNM] = IC;
2117 if (CurNM == OMPD_unknown)
2118 continue;
2119 // Check if the specified name modifier is allowed for the current
2120 // directive.
2121 // At most one if clause with the particular directive-name-modifier can
2122 // appear on the directive.
2123 bool MatchFound = false;
2124 for (auto NM : AllowedNameModifiers) {
2125 if (CurNM == NM) {
2126 MatchFound = true;
2127 break;
2128 }
2129 }
2130 if (!MatchFound) {
2131 S.Diag(IC->getNameModifierLoc(),
2132 diag::err_omp_wrong_if_directive_name_modifier)
2133 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2134 ErrorFound = true;
2135 }
2136 }
2137 }
2138 // If any if clause on the directive includes a directive-name-modifier then
2139 // all if clauses on the directive must include a directive-name-modifier.
2140 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2141 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2142 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2143 diag::err_omp_no_more_if_clause);
2144 } else {
2145 std::string Values;
2146 std::string Sep(", ");
2147 unsigned AllowedCnt = 0;
2148 unsigned TotalAllowedNum =
2149 AllowedNameModifiers.size() - NamedModifiersNumber;
2150 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2151 ++Cnt) {
2152 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2153 if (!FoundNameModifiers[NM]) {
2154 Values += "'";
2155 Values += getOpenMPDirectiveName(NM);
2156 Values += "'";
2157 if (AllowedCnt + 2 == TotalAllowedNum)
2158 Values += " or ";
2159 else if (AllowedCnt + 1 != TotalAllowedNum)
2160 Values += Sep;
2161 ++AllowedCnt;
2162 }
2163 }
2164 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2165 diag::err_omp_unnamed_if_clause)
2166 << (TotalAllowedNum > 1) << Values;
2167 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002168 for (auto Loc : NameModifierLoc) {
2169 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2170 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002171 ErrorFound = true;
2172 }
2173 return ErrorFound;
2174}
2175
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002176StmtResult Sema::ActOnOpenMPExecutableDirective(
2177 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2178 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2179 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002180 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002181 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2182 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002183 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002184
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002185 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002186 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002187 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002188 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002189 if (AStmt) {
2190 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2191
2192 // Check default data sharing attributes for referenced variables.
2193 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2194 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2195 if (DSAChecker.isErrorFound())
2196 return StmtError();
2197 // Generate list of implicitly defined firstprivate variables.
2198 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002199
2200 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2201 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2202 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2203 SourceLocation(), SourceLocation())) {
2204 ClausesWithImplicit.push_back(Implicit);
2205 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2206 DSAChecker.getImplicitFirstprivate().size();
2207 } else
2208 ErrorFound = true;
2209 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002210 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002211
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002212 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002213 switch (Kind) {
2214 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002215 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2216 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002217 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002218 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002219 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002220 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2221 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002222 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002223 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002224 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2225 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002226 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002227 case OMPD_for_simd:
2228 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2229 EndLoc, VarsWithInheritedDSA);
2230 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002231 case OMPD_sections:
2232 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2233 EndLoc);
2234 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002235 case OMPD_section:
2236 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002237 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002238 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2239 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002240 case OMPD_single:
2241 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2242 EndLoc);
2243 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002244 case OMPD_master:
2245 assert(ClausesWithImplicit.empty() &&
2246 "No clauses are allowed for 'omp master' directive");
2247 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2248 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002249 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002250 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2251 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002252 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002253 case OMPD_parallel_for:
2254 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2255 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002256 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002257 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002258 case OMPD_parallel_for_simd:
2259 Res = ActOnOpenMPParallelForSimdDirective(
2260 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002261 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002262 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002263 case OMPD_parallel_sections:
2264 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2265 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002266 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002267 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002268 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002269 Res =
2270 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002271 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002272 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002273 case OMPD_taskyield:
2274 assert(ClausesWithImplicit.empty() &&
2275 "No clauses are allowed for 'omp taskyield' directive");
2276 assert(AStmt == nullptr &&
2277 "No associated statement allowed for 'omp taskyield' directive");
2278 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2279 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002280 case OMPD_barrier:
2281 assert(ClausesWithImplicit.empty() &&
2282 "No clauses are allowed for 'omp barrier' directive");
2283 assert(AStmt == nullptr &&
2284 "No associated statement allowed for 'omp barrier' directive");
2285 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2286 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002287 case OMPD_taskwait:
2288 assert(ClausesWithImplicit.empty() &&
2289 "No clauses are allowed for 'omp taskwait' directive");
2290 assert(AStmt == nullptr &&
2291 "No associated statement allowed for 'omp taskwait' directive");
2292 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2293 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002294 case OMPD_taskgroup:
2295 assert(ClausesWithImplicit.empty() &&
2296 "No clauses are allowed for 'omp taskgroup' directive");
2297 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2298 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002299 case OMPD_flush:
2300 assert(AStmt == nullptr &&
2301 "No associated statement allowed for 'omp flush' directive");
2302 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2303 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002304 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002305 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2306 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002307 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002308 case OMPD_atomic:
2309 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2310 EndLoc);
2311 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002312 case OMPD_teams:
2313 Res =
2314 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2315 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002316 case OMPD_target:
2317 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2318 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002319 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002320 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002321 case OMPD_target_parallel:
2322 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2323 StartLoc, EndLoc);
2324 AllowedNameModifiers.push_back(OMPD_target);
2325 AllowedNameModifiers.push_back(OMPD_parallel);
2326 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002327 case OMPD_target_parallel_for:
2328 Res = ActOnOpenMPTargetParallelForDirective(
2329 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2330 AllowedNameModifiers.push_back(OMPD_target);
2331 AllowedNameModifiers.push_back(OMPD_parallel);
2332 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002333 case OMPD_cancellation_point:
2334 assert(ClausesWithImplicit.empty() &&
2335 "No clauses are allowed for 'omp cancellation point' directive");
2336 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2337 "cancellation point' directive");
2338 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2339 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002340 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002341 assert(AStmt == nullptr &&
2342 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002343 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2344 CancelRegion);
2345 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002346 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002347 case OMPD_target_data:
2348 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2349 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002350 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002351 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002352 case OMPD_target_enter_data:
2353 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2354 EndLoc);
2355 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2356 break;
Samuel Antao72590762016-01-19 20:04:50 +00002357 case OMPD_target_exit_data:
2358 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2359 EndLoc);
2360 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2361 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002362 case OMPD_taskloop:
2363 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2364 EndLoc, VarsWithInheritedDSA);
2365 AllowedNameModifiers.push_back(OMPD_taskloop);
2366 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002367 case OMPD_taskloop_simd:
2368 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2369 EndLoc, VarsWithInheritedDSA);
2370 AllowedNameModifiers.push_back(OMPD_taskloop);
2371 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002372 case OMPD_distribute:
2373 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2374 EndLoc, VarsWithInheritedDSA);
2375 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002376 case OMPD_target_update:
2377 assert(!AStmt && "Statement is not allowed for target update");
2378 Res =
2379 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2380 AllowedNameModifiers.push_back(OMPD_target_update);
2381 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002382 case OMPD_distribute_parallel_for:
2383 Res = ActOnOpenMPDistributeParallelForDirective(
2384 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2385 AllowedNameModifiers.push_back(OMPD_parallel);
2386 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002387 case OMPD_distribute_parallel_for_simd:
2388 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2389 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2390 AllowedNameModifiers.push_back(OMPD_parallel);
2391 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002392 case OMPD_distribute_simd:
2393 Res = ActOnOpenMPDistributeSimdDirective(
2394 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2395 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002396 case OMPD_target_parallel_for_simd:
2397 Res = ActOnOpenMPTargetParallelForSimdDirective(
2398 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2399 AllowedNameModifiers.push_back(OMPD_target);
2400 AllowedNameModifiers.push_back(OMPD_parallel);
2401 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002402 case OMPD_target_simd:
2403 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2404 EndLoc, VarsWithInheritedDSA);
2405 AllowedNameModifiers.push_back(OMPD_target);
2406 break;
Kelvin Li02532872016-08-05 14:37:37 +00002407 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002408 Res = ActOnOpenMPTeamsDistributeDirective(
2409 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002410 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002411 case OMPD_teams_distribute_simd:
2412 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2413 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2414 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002415 case OMPD_teams_distribute_parallel_for_simd:
2416 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2417 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2418 AllowedNameModifiers.push_back(OMPD_parallel);
2419 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002420 case OMPD_teams_distribute_parallel_for:
2421 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2422 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2423 AllowedNameModifiers.push_back(OMPD_parallel);
2424 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002425 case OMPD_target_teams:
2426 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2427 EndLoc);
2428 AllowedNameModifiers.push_back(OMPD_target);
2429 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002430 case OMPD_target_teams_distribute:
2431 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2432 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2433 AllowedNameModifiers.push_back(OMPD_target);
2434 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002435 case OMPD_declare_target:
2436 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002437 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002438 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002439 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002440 llvm_unreachable("OpenMP Directive is not allowed");
2441 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002442 llvm_unreachable("Unknown OpenMP directive");
2443 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002444
Alexey Bataev4acb8592014-07-07 13:01:15 +00002445 for (auto P : VarsWithInheritedDSA) {
2446 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2447 << P.first << P.second->getSourceRange();
2448 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002449 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2450
2451 if (!AllowedNameModifiers.empty())
2452 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2453 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002454
Alexey Bataeved09d242014-05-28 05:53:51 +00002455 if (ErrorFound)
2456 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002457 return Res;
2458}
2459
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002460Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2461 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002462 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002463 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2464 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002465 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002466 assert(Linears.size() == LinModifiers.size());
2467 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002468 if (!DG || DG.get().isNull())
2469 return DeclGroupPtrTy();
2470
2471 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002472 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002473 return DG;
2474 }
2475 auto *ADecl = DG.get().getSingleDecl();
2476 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2477 ADecl = FTD->getTemplatedDecl();
2478
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002479 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2480 if (!FD) {
2481 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002482 return DeclGroupPtrTy();
2483 }
2484
Alexey Bataev2af33e32016-04-07 12:45:37 +00002485 // OpenMP [2.8.2, declare simd construct, Description]
2486 // The parameter of the simdlen clause must be a constant positive integer
2487 // expression.
2488 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002489 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002490 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002491 // OpenMP [2.8.2, declare simd construct, Description]
2492 // The special this pointer can be used as if was one of the arguments to the
2493 // function in any of the linear, aligned, or uniform clauses.
2494 // The uniform clause declares one or more arguments to have an invariant
2495 // value for all concurrent invocations of the function in the execution of a
2496 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002497 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2498 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002499 for (auto *E : Uniforms) {
2500 E = E->IgnoreParenImpCasts();
2501 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2502 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2503 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2504 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002505 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2506 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002507 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002508 }
2509 if (isa<CXXThisExpr>(E)) {
2510 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002511 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002512 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002513 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2514 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002515 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002516 // OpenMP [2.8.2, declare simd construct, Description]
2517 // The aligned clause declares that the object to which each list item points
2518 // is aligned to the number of bytes expressed in the optional parameter of
2519 // the aligned clause.
2520 // The special this pointer can be used as if was one of the arguments to the
2521 // function in any of the linear, aligned, or uniform clauses.
2522 // The type of list items appearing in the aligned clause must be array,
2523 // pointer, reference to array, or reference to pointer.
2524 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2525 Expr *AlignedThis = nullptr;
2526 for (auto *E : Aligneds) {
2527 E = E->IgnoreParenImpCasts();
2528 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2529 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2530 auto *CanonPVD = PVD->getCanonicalDecl();
2531 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2532 FD->getParamDecl(PVD->getFunctionScopeIndex())
2533 ->getCanonicalDecl() == CanonPVD) {
2534 // OpenMP [2.8.1, simd construct, Restrictions]
2535 // A list-item cannot appear in more than one aligned clause.
2536 if (AlignedArgs.count(CanonPVD) > 0) {
2537 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2538 << 1 << E->getSourceRange();
2539 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2540 diag::note_omp_explicit_dsa)
2541 << getOpenMPClauseName(OMPC_aligned);
2542 continue;
2543 }
2544 AlignedArgs[CanonPVD] = E;
2545 QualType QTy = PVD->getType()
2546 .getNonReferenceType()
2547 .getUnqualifiedType()
2548 .getCanonicalType();
2549 const Type *Ty = QTy.getTypePtrOrNull();
2550 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2551 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2552 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2553 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2554 }
2555 continue;
2556 }
2557 }
2558 if (isa<CXXThisExpr>(E)) {
2559 if (AlignedThis) {
2560 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2561 << 2 << E->getSourceRange();
2562 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2563 << getOpenMPClauseName(OMPC_aligned);
2564 }
2565 AlignedThis = E;
2566 continue;
2567 }
2568 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2569 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2570 }
2571 // The optional parameter of the aligned clause, alignment, must be a constant
2572 // positive integer expression. If no optional parameter is specified,
2573 // implementation-defined default alignments for SIMD instructions on the
2574 // target platforms are assumed.
2575 SmallVector<Expr *, 4> NewAligns;
2576 for (auto *E : Alignments) {
2577 ExprResult Align;
2578 if (E)
2579 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2580 NewAligns.push_back(Align.get());
2581 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002582 // OpenMP [2.8.2, declare simd construct, Description]
2583 // The linear clause declares one or more list items to be private to a SIMD
2584 // lane and to have a linear relationship with respect to the iteration space
2585 // of a loop.
2586 // The special this pointer can be used as if was one of the arguments to the
2587 // function in any of the linear, aligned, or uniform clauses.
2588 // When a linear-step expression is specified in a linear clause it must be
2589 // either a constant integer expression or an integer-typed parameter that is
2590 // specified in a uniform clause on the directive.
2591 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2592 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2593 auto MI = LinModifiers.begin();
2594 for (auto *E : Linears) {
2595 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2596 ++MI;
2597 E = E->IgnoreParenImpCasts();
2598 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2599 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2600 auto *CanonPVD = PVD->getCanonicalDecl();
2601 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2602 FD->getParamDecl(PVD->getFunctionScopeIndex())
2603 ->getCanonicalDecl() == CanonPVD) {
2604 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2605 // A list-item cannot appear in more than one linear clause.
2606 if (LinearArgs.count(CanonPVD) > 0) {
2607 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2608 << getOpenMPClauseName(OMPC_linear)
2609 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2610 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2611 diag::note_omp_explicit_dsa)
2612 << getOpenMPClauseName(OMPC_linear);
2613 continue;
2614 }
2615 // Each argument can appear in at most one uniform or linear clause.
2616 if (UniformedArgs.count(CanonPVD) > 0) {
2617 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2618 << getOpenMPClauseName(OMPC_linear)
2619 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2620 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2621 diag::note_omp_explicit_dsa)
2622 << getOpenMPClauseName(OMPC_uniform);
2623 continue;
2624 }
2625 LinearArgs[CanonPVD] = E;
2626 if (E->isValueDependent() || E->isTypeDependent() ||
2627 E->isInstantiationDependent() ||
2628 E->containsUnexpandedParameterPack())
2629 continue;
2630 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2631 PVD->getOriginalType());
2632 continue;
2633 }
2634 }
2635 if (isa<CXXThisExpr>(E)) {
2636 if (UniformedLinearThis) {
2637 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2638 << getOpenMPClauseName(OMPC_linear)
2639 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2640 << E->getSourceRange();
2641 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2642 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2643 : OMPC_linear);
2644 continue;
2645 }
2646 UniformedLinearThis = E;
2647 if (E->isValueDependent() || E->isTypeDependent() ||
2648 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2649 continue;
2650 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2651 E->getType());
2652 continue;
2653 }
2654 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2655 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2656 }
2657 Expr *Step = nullptr;
2658 Expr *NewStep = nullptr;
2659 SmallVector<Expr *, 4> NewSteps;
2660 for (auto *E : Steps) {
2661 // Skip the same step expression, it was checked already.
2662 if (Step == E || !E) {
2663 NewSteps.push_back(E ? NewStep : nullptr);
2664 continue;
2665 }
2666 Step = E;
2667 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2668 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2669 auto *CanonPVD = PVD->getCanonicalDecl();
2670 if (UniformedArgs.count(CanonPVD) == 0) {
2671 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2672 << Step->getSourceRange();
2673 } else if (E->isValueDependent() || E->isTypeDependent() ||
2674 E->isInstantiationDependent() ||
2675 E->containsUnexpandedParameterPack() ||
2676 CanonPVD->getType()->hasIntegerRepresentation())
2677 NewSteps.push_back(Step);
2678 else {
2679 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2680 << Step->getSourceRange();
2681 }
2682 continue;
2683 }
2684 NewStep = Step;
2685 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2686 !Step->isInstantiationDependent() &&
2687 !Step->containsUnexpandedParameterPack()) {
2688 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2689 .get();
2690 if (NewStep)
2691 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2692 }
2693 NewSteps.push_back(NewStep);
2694 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002695 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2696 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002697 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002698 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2699 const_cast<Expr **>(Linears.data()), Linears.size(),
2700 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2701 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002702 ADecl->addAttr(NewAttr);
2703 return ConvertDeclToDeclGroup(ADecl);
2704}
2705
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002706StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2707 Stmt *AStmt,
2708 SourceLocation StartLoc,
2709 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002710 if (!AStmt)
2711 return StmtError();
2712
Alexey Bataev9959db52014-05-06 10:08:46 +00002713 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2714 // 1.2.2 OpenMP Language Terminology
2715 // Structured block - An executable statement with a single entry at the
2716 // top and a single exit at the bottom.
2717 // The point of exit cannot be a branch out of the structured block.
2718 // longjmp() and throw() must not violate the entry/exit criteria.
2719 CS->getCapturedDecl()->setNothrow();
2720
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002721 getCurFunction()->setHasBranchProtectedScope();
2722
Alexey Bataev25e5b442015-09-15 12:52:43 +00002723 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2724 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002725}
2726
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002727namespace {
2728/// \brief Helper class for checking canonical form of the OpenMP loops and
2729/// extracting iteration space of each loop in the loop nest, that will be used
2730/// for IR generation.
2731class OpenMPIterationSpaceChecker {
2732 /// \brief Reference to Sema.
2733 Sema &SemaRef;
2734 /// \brief A location for diagnostics (when there is no some better location).
2735 SourceLocation DefaultLoc;
2736 /// \brief A location for diagnostics (when increment is not compatible).
2737 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002738 /// \brief A source location for referring to loop init later.
2739 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002740 /// \brief A source location for referring to condition later.
2741 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002742 /// \brief A source location for referring to increment later.
2743 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002744 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002745 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002746 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002747 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002748 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002749 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002750 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002751 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002752 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002753 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002754 /// \brief This flag is true when condition is one of:
2755 /// Var < UB
2756 /// Var <= UB
2757 /// UB > Var
2758 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002759 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002760 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002761 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002762 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002763 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002764
2765public:
2766 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002767 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002768 /// \brief Check init-expr for canonical loop form and save loop counter
2769 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002770 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002771 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2772 /// for less/greater and for strict/non-strict comparison.
2773 bool CheckCond(Expr *S);
2774 /// \brief Check incr-expr for canonical loop form and return true if it
2775 /// does not conform, otherwise save loop step (#Step).
2776 bool CheckInc(Expr *S);
2777 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002778 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002779 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002780 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002781 /// \brief Source range of the loop init.
2782 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2783 /// \brief Source range of the loop condition.
2784 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2785 /// \brief Source range of the loop increment.
2786 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2787 /// \brief True if the step should be subtracted.
2788 bool ShouldSubtractStep() const { return SubtractStep; }
2789 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002790 Expr *
2791 BuildNumIterations(Scope *S, const bool LimitedType,
2792 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002793 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002794 Expr *BuildPreCond(Scope *S, Expr *Cond,
2795 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002796 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002797 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2798 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002799 /// \brief Build reference expression to the private counter be used for
2800 /// codegen.
2801 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002802 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002803 Expr *BuildCounterInit() const;
2804 /// \brief Build step of the counter be used for codegen.
2805 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002806 /// \brief Return true if any expression is dependent.
2807 bool Dependent() const;
2808
2809private:
2810 /// \brief Check the right-hand side of an assignment in the increment
2811 /// expression.
2812 bool CheckIncRHS(Expr *RHS);
2813 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002814 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002815 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002816 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002817 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002818 /// \brief Helper to set loop increment.
2819 bool SetStep(Expr *NewStep, bool Subtract);
2820};
2821
2822bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002823 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002824 assert(!LB && !UB && !Step);
2825 return false;
2826 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002827 return LCDecl->getType()->isDependentType() ||
2828 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2829 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002830}
2831
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002832static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002833 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2834 E = ExprTemp->getSubExpr();
2835
2836 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2837 E = MTE->GetTemporaryExpr();
2838
2839 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2840 E = Binder->getSubExpr();
2841
2842 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2843 E = ICE->getSubExprAsWritten();
2844 return E->IgnoreParens();
2845}
2846
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002847bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2848 Expr *NewLCRefExpr,
2849 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002850 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002851 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002852 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002853 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002854 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002855 LCDecl = getCanonicalDecl(NewLCDecl);
2856 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002857 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2858 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002859 if ((Ctor->isCopyOrMoveConstructor() ||
2860 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2861 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002862 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002863 LB = NewLB;
2864 return false;
2865}
2866
2867bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002868 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002869 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002870 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2871 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002872 if (!NewUB)
2873 return true;
2874 UB = NewUB;
2875 TestIsLessOp = LessOp;
2876 TestIsStrictOp = StrictOp;
2877 ConditionSrcRange = SR;
2878 ConditionLoc = SL;
2879 return false;
2880}
2881
2882bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2883 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002884 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002885 if (!NewStep)
2886 return true;
2887 if (!NewStep->isValueDependent()) {
2888 // Check that the step is integer expression.
2889 SourceLocation StepLoc = NewStep->getLocStart();
2890 ExprResult Val =
2891 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2892 if (Val.isInvalid())
2893 return true;
2894 NewStep = Val.get();
2895
2896 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2897 // If test-expr is of form var relational-op b and relational-op is < or
2898 // <= then incr-expr must cause var to increase on each iteration of the
2899 // loop. If test-expr is of form var relational-op b and relational-op is
2900 // > or >= then incr-expr must cause var to decrease on each iteration of
2901 // the loop.
2902 // If test-expr is of form b relational-op var and relational-op is < or
2903 // <= then incr-expr must cause var to decrease on each iteration of the
2904 // loop. If test-expr is of form b relational-op var and relational-op is
2905 // > or >= then incr-expr must cause var to increase on each iteration of
2906 // the loop.
2907 llvm::APSInt Result;
2908 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2909 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2910 bool IsConstNeg =
2911 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00002912 bool IsConstPos =
2913 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002914 bool IsConstZero = IsConstant && !Result.getBoolValue();
2915 if (UB && (IsConstZero ||
2916 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00002917 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002918 SemaRef.Diag(NewStep->getExprLoc(),
2919 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002920 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002921 SemaRef.Diag(ConditionLoc,
2922 diag::note_omp_loop_cond_requres_compatible_incr)
2923 << TestIsLessOp << ConditionSrcRange;
2924 return true;
2925 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002926 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00002927 NewStep =
2928 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2929 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00002930 Subtract = !Subtract;
2931 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002932 }
2933
2934 Step = NewStep;
2935 SubtractStep = Subtract;
2936 return false;
2937}
2938
Alexey Bataev9c821032015-04-30 04:23:23 +00002939bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002940 // Check init-expr for canonical loop form and save loop counter
2941 // variable - #Var and its initialization value - #LB.
2942 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2943 // var = lb
2944 // integer-type var = lb
2945 // random-access-iterator-type var = lb
2946 // pointer-type var = lb
2947 //
2948 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00002949 if (EmitDiags) {
2950 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2951 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002952 return true;
2953 }
Tim Shen4a05bb82016-06-21 20:29:17 +00002954 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2955 if (!ExprTemp->cleanupsHaveSideEffects())
2956 S = ExprTemp->getSubExpr();
2957
Alexander Musmana5f070a2014-10-01 06:03:56 +00002958 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002959 if (Expr *E = dyn_cast<Expr>(S))
2960 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00002961 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002962 if (BO->getOpcode() == BO_Assign) {
2963 auto *LHS = BO->getLHS()->IgnoreParens();
2964 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2965 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2966 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2967 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2968 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2969 }
2970 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2971 if (ME->isArrow() &&
2972 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2973 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2974 }
2975 }
David Majnemer9d168222016-08-05 17:44:54 +00002976 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002977 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00002978 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00002979 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002980 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00002981 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002982 SemaRef.Diag(S->getLocStart(),
2983 diag::ext_omp_loop_not_canonical_init)
2984 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002985 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002986 }
2987 }
2988 }
David Majnemer9d168222016-08-05 17:44:54 +00002989 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002990 if (CE->getOperator() == OO_Equal) {
2991 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00002992 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002993 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2994 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2995 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2996 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
2997 }
2998 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2999 if (ME->isArrow() &&
3000 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3001 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3002 }
3003 }
3004 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003005
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003006 if (Dependent() || SemaRef.CurContext->isDependentContext())
3007 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003008 if (EmitDiags) {
3009 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3010 << S->getSourceRange();
3011 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003012 return true;
3013}
3014
Alexey Bataev23b69422014-06-18 07:08:49 +00003015/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003016/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003017static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003018 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003019 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003020 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003021 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3022 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003023 if ((Ctor->isCopyOrMoveConstructor() ||
3024 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3025 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003026 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003027 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3028 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3029 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3030 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3031 return getCanonicalDecl(ME->getMemberDecl());
3032 return getCanonicalDecl(VD);
3033 }
3034 }
3035 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3036 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3037 return getCanonicalDecl(ME->getMemberDecl());
3038 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003039}
3040
3041bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3042 // Check test-expr for canonical form, save upper-bound UB, flags for
3043 // less/greater and for strict/non-strict comparison.
3044 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3045 // var relational-op b
3046 // b relational-op var
3047 //
3048 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003049 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003050 return true;
3051 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003052 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003053 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003054 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003055 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003056 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003057 return SetUB(BO->getRHS(),
3058 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3059 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3060 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003061 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003062 return SetUB(BO->getLHS(),
3063 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3064 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3065 BO->getSourceRange(), BO->getOperatorLoc());
3066 }
David Majnemer9d168222016-08-05 17:44:54 +00003067 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003068 if (CE->getNumArgs() == 2) {
3069 auto Op = CE->getOperator();
3070 switch (Op) {
3071 case OO_Greater:
3072 case OO_GreaterEqual:
3073 case OO_Less:
3074 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003075 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003076 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3077 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3078 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003079 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003080 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3081 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3082 CE->getOperatorLoc());
3083 break;
3084 default:
3085 break;
3086 }
3087 }
3088 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003089 if (Dependent() || SemaRef.CurContext->isDependentContext())
3090 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003091 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003092 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003093 return true;
3094}
3095
3096bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3097 // RHS of canonical loop form increment can be:
3098 // var + incr
3099 // incr + var
3100 // var - incr
3101 //
3102 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003103 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003104 if (BO->isAdditiveOp()) {
3105 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003106 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003107 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003108 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003109 return SetStep(BO->getLHS(), false);
3110 }
David Majnemer9d168222016-08-05 17:44:54 +00003111 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003112 bool IsAdd = CE->getOperator() == OO_Plus;
3113 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003114 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003115 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003116 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003117 return SetStep(CE->getArg(0), false);
3118 }
3119 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003120 if (Dependent() || SemaRef.CurContext->isDependentContext())
3121 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003122 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003123 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003124 return true;
3125}
3126
3127bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3128 // Check incr-expr for canonical loop form and return true if it
3129 // does not conform.
3130 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3131 // ++var
3132 // var++
3133 // --var
3134 // var--
3135 // var += incr
3136 // var -= incr
3137 // var = var + incr
3138 // var = incr + var
3139 // var = var - incr
3140 //
3141 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003142 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003143 return true;
3144 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003145 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3146 if (!ExprTemp->cleanupsHaveSideEffects())
3147 S = ExprTemp->getSubExpr();
3148
Alexander Musmana5f070a2014-10-01 06:03:56 +00003149 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003150 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003151 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003152 if (UO->isIncrementDecrementOp() &&
3153 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003154 return SetStep(SemaRef
3155 .ActOnIntegerConstant(UO->getLocStart(),
3156 (UO->isDecrementOp() ? -1 : 1))
3157 .get(),
3158 false);
3159 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003160 switch (BO->getOpcode()) {
3161 case BO_AddAssign:
3162 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003163 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003164 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3165 break;
3166 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003167 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003168 return CheckIncRHS(BO->getRHS());
3169 break;
3170 default:
3171 break;
3172 }
David Majnemer9d168222016-08-05 17:44:54 +00003173 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003174 switch (CE->getOperator()) {
3175 case OO_PlusPlus:
3176 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003177 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003178 return SetStep(SemaRef
3179 .ActOnIntegerConstant(
3180 CE->getLocStart(),
3181 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3182 .get(),
3183 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003184 break;
3185 case OO_PlusEqual:
3186 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003187 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003188 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3189 break;
3190 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003191 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003192 return CheckIncRHS(CE->getArg(1));
3193 break;
3194 default:
3195 break;
3196 }
3197 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003198 if (Dependent() || SemaRef.CurContext->isDependentContext())
3199 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003200 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003201 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003202 return true;
3203}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003204
Alexey Bataev5a3af132016-03-29 08:58:54 +00003205static ExprResult
3206tryBuildCapture(Sema &SemaRef, Expr *Capture,
3207 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003208 if (SemaRef.CurContext->isDependentContext())
3209 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003210 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3211 return SemaRef.PerformImplicitConversion(
3212 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3213 /*AllowExplicit=*/true);
3214 auto I = Captures.find(Capture);
3215 if (I != Captures.end())
3216 return buildCapture(SemaRef, Capture, I->second);
3217 DeclRefExpr *Ref = nullptr;
3218 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3219 Captures[Capture] = Ref;
3220 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003221}
3222
Alexander Musmana5f070a2014-10-01 06:03:56 +00003223/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003224Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3225 Scope *S, const bool LimitedType,
3226 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003227 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003228 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003229 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003230 SemaRef.getLangOpts().CPlusPlus) {
3231 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003232 auto *UBExpr = TestIsLessOp ? UB : LB;
3233 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003234 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3235 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003236 if (!Upper || !Lower)
3237 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003238
3239 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3240
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003241 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003242 // BuildBinOp already emitted error, this one is to point user to upper
3243 // and lower bound, and to tell what is passed to 'operator-'.
3244 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3245 << Upper->getSourceRange() << Lower->getSourceRange();
3246 return nullptr;
3247 }
3248 }
3249
3250 if (!Diff.isUsable())
3251 return nullptr;
3252
3253 // Upper - Lower [- 1]
3254 if (TestIsStrictOp)
3255 Diff = SemaRef.BuildBinOp(
3256 S, DefaultLoc, BO_Sub, Diff.get(),
3257 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3258 if (!Diff.isUsable())
3259 return nullptr;
3260
3261 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003262 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3263 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003264 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003265 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003266 if (!Diff.isUsable())
3267 return nullptr;
3268
3269 // Parentheses (for dumping/debugging purposes only).
3270 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3271 if (!Diff.isUsable())
3272 return nullptr;
3273
3274 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003275 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003276 if (!Diff.isUsable())
3277 return nullptr;
3278
Alexander Musman174b3ca2014-10-06 11:16:29 +00003279 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003280 QualType Type = Diff.get()->getType();
3281 auto &C = SemaRef.Context;
3282 bool UseVarType = VarType->hasIntegerRepresentation() &&
3283 C.getTypeSize(Type) > C.getTypeSize(VarType);
3284 if (!Type->isIntegerType() || UseVarType) {
3285 unsigned NewSize =
3286 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3287 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3288 : Type->hasSignedIntegerRepresentation();
3289 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003290 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3291 Diff = SemaRef.PerformImplicitConversion(
3292 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3293 if (!Diff.isUsable())
3294 return nullptr;
3295 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003296 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003297 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003298 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3299 if (NewSize != C.getTypeSize(Type)) {
3300 if (NewSize < C.getTypeSize(Type)) {
3301 assert(NewSize == 64 && "incorrect loop var size");
3302 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3303 << InitSrcRange << ConditionSrcRange;
3304 }
3305 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003306 NewSize, Type->hasSignedIntegerRepresentation() ||
3307 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003308 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3309 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3310 Sema::AA_Converting, true);
3311 if (!Diff.isUsable())
3312 return nullptr;
3313 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003314 }
3315 }
3316
Alexander Musmana5f070a2014-10-01 06:03:56 +00003317 return Diff.get();
3318}
3319
Alexey Bataev5a3af132016-03-29 08:58:54 +00003320Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3321 Scope *S, Expr *Cond,
3322 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003323 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3324 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3325 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003326
Alexey Bataev5a3af132016-03-29 08:58:54 +00003327 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3328 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3329 if (!NewLB.isUsable() || !NewUB.isUsable())
3330 return nullptr;
3331
Alexey Bataev62dbb972015-04-22 11:59:37 +00003332 auto CondExpr = SemaRef.BuildBinOp(
3333 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3334 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003335 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003336 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003337 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3338 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003339 CondExpr = SemaRef.PerformImplicitConversion(
3340 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3341 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003342 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003343 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3344 // Otherwise use original loop conditon and evaluate it in runtime.
3345 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3346}
3347
Alexander Musmana5f070a2014-10-01 06:03:56 +00003348/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003349DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003350 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003351 auto *VD = dyn_cast<VarDecl>(LCDecl);
3352 if (!VD) {
3353 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3354 auto *Ref = buildDeclRefExpr(
3355 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003356 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3357 // If the loop control decl is explicitly marked as private, do not mark it
3358 // as captured again.
3359 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3360 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003361 return Ref;
3362 }
3363 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003364 DefaultLoc);
3365}
3366
3367Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003368 if (LCDecl && !LCDecl->isInvalidDecl()) {
3369 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003370 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003371 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3372 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003373 if (PrivateVar->isInvalidDecl())
3374 return nullptr;
3375 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3376 }
3377 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003378}
3379
Samuel Antao4c8035b2016-12-12 18:00:20 +00003380/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003381Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3382
3383/// \brief Build step of the counter be used for codegen.
3384Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3385
3386/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003387struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003388 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003389 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003390 /// \brief This expression calculates the number of iterations in the loop.
3391 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003392 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003393 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003394 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003395 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003396 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003397 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003398 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003399 /// \brief This is step for the #CounterVar used to generate its update:
3400 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003401 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003402 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003403 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003404 /// \brief Source range of the loop init.
3405 SourceRange InitSrcRange;
3406 /// \brief Source range of the loop condition.
3407 SourceRange CondSrcRange;
3408 /// \brief Source range of the loop increment.
3409 SourceRange IncSrcRange;
3410};
3411
Alexey Bataev23b69422014-06-18 07:08:49 +00003412} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003413
Alexey Bataev9c821032015-04-30 04:23:23 +00003414void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3415 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3416 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003417 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3418 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003419 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3420 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003421 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3422 if (auto *D = ISC.GetLoopDecl()) {
3423 auto *VD = dyn_cast<VarDecl>(D);
3424 if (!VD) {
3425 if (auto *Private = IsOpenMPCapturedDecl(D))
3426 VD = Private;
3427 else {
3428 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3429 /*WithInit=*/false);
3430 VD = cast<VarDecl>(Ref->getDecl());
3431 }
3432 }
3433 DSAStack->addLoopControlVariable(D, VD);
3434 }
3435 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003436 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003437 }
3438}
3439
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003440/// \brief Called on a for stmt to check and extract its iteration space
3441/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003442static bool CheckOpenMPIterationSpace(
3443 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3444 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003445 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003446 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003447 LoopIterationSpace &ResultIterSpace,
3448 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003449 // OpenMP [2.6, Canonical Loop Form]
3450 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003451 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003452 if (!For) {
3453 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003454 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3455 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3456 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3457 if (NestedLoopCount > 1) {
3458 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3459 SemaRef.Diag(DSA.getConstructLoc(),
3460 diag::note_omp_collapse_ordered_expr)
3461 << 2 << CollapseLoopCountExpr->getSourceRange()
3462 << OrderedLoopCountExpr->getSourceRange();
3463 else if (CollapseLoopCountExpr)
3464 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3465 diag::note_omp_collapse_ordered_expr)
3466 << 0 << CollapseLoopCountExpr->getSourceRange();
3467 else
3468 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3469 diag::note_omp_collapse_ordered_expr)
3470 << 1 << OrderedLoopCountExpr->getSourceRange();
3471 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003472 return true;
3473 }
3474 assert(For->getBody());
3475
3476 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3477
3478 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003479 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003480 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003481 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003482
3483 bool HasErrors = false;
3484
3485 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003486 if (auto *LCDecl = ISC.GetLoopDecl()) {
3487 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003488
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003489 // OpenMP [2.6, Canonical Loop Form]
3490 // Var is one of the following:
3491 // A variable of signed or unsigned integer type.
3492 // For C++, a variable of a random access iterator type.
3493 // For C, a variable of a pointer type.
3494 auto VarType = LCDecl->getType().getNonReferenceType();
3495 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3496 !VarType->isPointerType() &&
3497 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3498 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3499 << SemaRef.getLangOpts().CPlusPlus;
3500 HasErrors = true;
3501 }
3502
3503 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3504 // a Construct
3505 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3506 // parallel for construct is (are) private.
3507 // The loop iteration variable in the associated for-loop of a simd
3508 // construct with just one associated for-loop is linear with a
3509 // constant-linear-step that is the increment of the associated for-loop.
3510 // Exclude loop var from the list of variables with implicitly defined data
3511 // sharing attributes.
3512 VarsWithImplicitDSA.erase(LCDecl);
3513
3514 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3515 // in a Construct, C/C++].
3516 // The loop iteration variable in the associated for-loop of a simd
3517 // construct with just one associated for-loop may be listed in a linear
3518 // clause with a constant-linear-step that is the increment of the
3519 // associated for-loop.
3520 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3521 // parallel for construct may be listed in a private or lastprivate clause.
3522 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3523 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3524 // declared in the loop and it is predetermined as a private.
3525 auto PredeterminedCKind =
3526 isOpenMPSimdDirective(DKind)
3527 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3528 : OMPC_private;
3529 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3530 DVar.CKind != PredeterminedCKind) ||
3531 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3532 isOpenMPDistributeDirective(DKind)) &&
3533 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3534 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3535 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3536 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3537 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3538 << getOpenMPClauseName(PredeterminedCKind);
3539 if (DVar.RefExpr == nullptr)
3540 DVar.CKind = PredeterminedCKind;
3541 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3542 HasErrors = true;
3543 } else if (LoopDeclRefExpr != nullptr) {
3544 // Make the loop iteration variable private (for worksharing constructs),
3545 // linear (for simd directives with the only one associated loop) or
3546 // lastprivate (for simd directives with several collapsed or ordered
3547 // loops).
3548 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003549 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3550 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003551 /*FromParent=*/false);
3552 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3553 }
3554
3555 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3556
3557 // Check test-expr.
3558 HasErrors |= ISC.CheckCond(For->getCond());
3559
3560 // Check incr-expr.
3561 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003562 }
3563
Alexander Musmana5f070a2014-10-01 06:03:56 +00003564 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003565 return HasErrors;
3566
Alexander Musmana5f070a2014-10-01 06:03:56 +00003567 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003568 ResultIterSpace.PreCond =
3569 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003570 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003571 DSA.getCurScope(),
3572 (isOpenMPWorksharingDirective(DKind) ||
3573 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3574 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003575 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003576 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003577 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3578 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3579 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3580 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3581 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3582 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3583
Alexey Bataev62dbb972015-04-22 11:59:37 +00003584 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3585 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003586 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003587 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003588 ResultIterSpace.CounterInit == nullptr ||
3589 ResultIterSpace.CounterStep == nullptr);
3590
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003591 return HasErrors;
3592}
3593
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003594/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003595static ExprResult
3596BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3597 ExprResult Start,
3598 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003599 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003600 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3601 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003602 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003603 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003604 VarRef.get()->getType())) {
3605 NewStart = SemaRef.PerformImplicitConversion(
3606 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3607 /*AllowExplicit=*/true);
3608 if (!NewStart.isUsable())
3609 return ExprError();
3610 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003611
3612 auto Init =
3613 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3614 return Init;
3615}
3616
Alexander Musmana5f070a2014-10-01 06:03:56 +00003617/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003618static ExprResult
3619BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3620 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3621 ExprResult Step, bool Subtract,
3622 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003623 // Add parentheses (for debugging purposes only).
3624 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3625 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3626 !Step.isUsable())
3627 return ExprError();
3628
Alexey Bataev5a3af132016-03-29 08:58:54 +00003629 ExprResult NewStep = Step;
3630 if (Captures)
3631 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003632 if (NewStep.isInvalid())
3633 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003634 ExprResult Update =
3635 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003636 if (!Update.isUsable())
3637 return ExprError();
3638
Alexey Bataevc0214e02016-02-16 12:13:49 +00003639 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3640 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003641 ExprResult NewStart = Start;
3642 if (Captures)
3643 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003644 if (NewStart.isInvalid())
3645 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003646
Alexey Bataevc0214e02016-02-16 12:13:49 +00003647 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3648 ExprResult SavedUpdate = Update;
3649 ExprResult UpdateVal;
3650 if (VarRef.get()->getType()->isOverloadableType() ||
3651 NewStart.get()->getType()->isOverloadableType() ||
3652 Update.get()->getType()->isOverloadableType()) {
3653 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3654 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3655 Update =
3656 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3657 if (Update.isUsable()) {
3658 UpdateVal =
3659 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3660 VarRef.get(), SavedUpdate.get());
3661 if (UpdateVal.isUsable()) {
3662 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3663 UpdateVal.get());
3664 }
3665 }
3666 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3667 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003668
Alexey Bataevc0214e02016-02-16 12:13:49 +00003669 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3670 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3671 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3672 NewStart.get(), SavedUpdate.get());
3673 if (!Update.isUsable())
3674 return ExprError();
3675
Alexey Bataev11481f52016-02-17 10:29:05 +00003676 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3677 VarRef.get()->getType())) {
3678 Update = SemaRef.PerformImplicitConversion(
3679 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3680 if (!Update.isUsable())
3681 return ExprError();
3682 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003683
3684 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3685 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003686 return Update;
3687}
3688
3689/// \brief Convert integer expression \a E to make it have at least \a Bits
3690/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003691static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003692 if (E == nullptr)
3693 return ExprError();
3694 auto &C = SemaRef.Context;
3695 QualType OldType = E->getType();
3696 unsigned HasBits = C.getTypeSize(OldType);
3697 if (HasBits >= Bits)
3698 return ExprResult(E);
3699 // OK to convert to signed, because new type has more bits than old.
3700 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3701 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3702 true);
3703}
3704
3705/// \brief Check if the given expression \a E is a constant integer that fits
3706/// into \a Bits bits.
3707static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3708 if (E == nullptr)
3709 return false;
3710 llvm::APSInt Result;
3711 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3712 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3713 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003714}
3715
Alexey Bataev5a3af132016-03-29 08:58:54 +00003716/// Build preinits statement for the given declarations.
3717static Stmt *buildPreInits(ASTContext &Context,
3718 SmallVectorImpl<Decl *> &PreInits) {
3719 if (!PreInits.empty()) {
3720 return new (Context) DeclStmt(
3721 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3722 SourceLocation(), SourceLocation());
3723 }
3724 return nullptr;
3725}
3726
3727/// Build preinits statement for the given declarations.
3728static Stmt *buildPreInits(ASTContext &Context,
3729 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3730 if (!Captures.empty()) {
3731 SmallVector<Decl *, 16> PreInits;
3732 for (auto &Pair : Captures)
3733 PreInits.push_back(Pair.second->getDecl());
3734 return buildPreInits(Context, PreInits);
3735 }
3736 return nullptr;
3737}
3738
3739/// Build postupdate expression for the given list of postupdates expressions.
3740static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3741 Expr *PostUpdate = nullptr;
3742 if (!PostUpdates.empty()) {
3743 for (auto *E : PostUpdates) {
3744 Expr *ConvE = S.BuildCStyleCastExpr(
3745 E->getExprLoc(),
3746 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3747 E->getExprLoc(), E)
3748 .get();
3749 PostUpdate = PostUpdate
3750 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3751 PostUpdate, ConvE)
3752 .get()
3753 : ConvE;
3754 }
3755 }
3756 return PostUpdate;
3757}
3758
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003759/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003760/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3761/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003762static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003763CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3764 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3765 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003766 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003767 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003768 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003769 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003770 // Found 'collapse' clause - calculate collapse number.
3771 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003772 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003773 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003774 }
3775 if (OrderedLoopCountExpr) {
3776 // Found 'ordered' clause - calculate collapse number.
3777 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003778 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3779 if (Result.getLimitedValue() < NestedLoopCount) {
3780 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3781 diag::err_omp_wrong_ordered_loop_count)
3782 << OrderedLoopCountExpr->getSourceRange();
3783 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3784 diag::note_collapse_loop_count)
3785 << CollapseLoopCountExpr->getSourceRange();
3786 }
3787 NestedLoopCount = Result.getLimitedValue();
3788 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003789 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003790 // This is helper routine for loop directives (e.g., 'for', 'simd',
3791 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003792 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003793 SmallVector<LoopIterationSpace, 4> IterSpaces;
3794 IterSpaces.resize(NestedLoopCount);
3795 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003796 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003797 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003798 NestedLoopCount, CollapseLoopCountExpr,
3799 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003800 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003801 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003802 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003803 // OpenMP [2.8.1, simd construct, Restrictions]
3804 // All loops associated with the construct must be perfectly nested; that
3805 // is, there must be no intervening code nor any OpenMP directive between
3806 // any two loops.
3807 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003808 }
3809
Alexander Musmana5f070a2014-10-01 06:03:56 +00003810 Built.clear(/* size */ NestedLoopCount);
3811
3812 if (SemaRef.CurContext->isDependentContext())
3813 return NestedLoopCount;
3814
3815 // An example of what is generated for the following code:
3816 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003817 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003818 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003819 // for (k = 0; k < NK; ++k)
3820 // for (j = J0; j < NJ; j+=2) {
3821 // <loop body>
3822 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003823 //
3824 // We generate the code below.
3825 // Note: the loop body may be outlined in CodeGen.
3826 // Note: some counters may be C++ classes, operator- is used to find number of
3827 // iterations and operator+= to calculate counter value.
3828 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3829 // or i64 is currently supported).
3830 //
3831 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3832 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3833 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3834 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3835 // // similar updates for vars in clauses (e.g. 'linear')
3836 // <loop body (using local i and j)>
3837 // }
3838 // i = NI; // assign final values of counters
3839 // j = NJ;
3840 //
3841
3842 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3843 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003844 // Precondition tests if there is at least one iteration (all conditions are
3845 // true).
3846 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003847 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003848 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003849 32 /* Bits */, SemaRef
3850 .PerformImplicitConversion(
3851 N0->IgnoreImpCasts(), N0->getType(),
3852 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003853 .get(),
3854 SemaRef);
3855 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003856 64 /* Bits */, SemaRef
3857 .PerformImplicitConversion(
3858 N0->IgnoreImpCasts(), N0->getType(),
3859 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003860 .get(),
3861 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003862
3863 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3864 return NestedLoopCount;
3865
3866 auto &C = SemaRef.Context;
3867 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3868
3869 Scope *CurScope = DSA.getCurScope();
3870 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003871 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003872 PreCond =
3873 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3874 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003875 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003876 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003877 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003878 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3879 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003880 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003881 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003882 SemaRef
3883 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3884 Sema::AA_Converting,
3885 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003886 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003887 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003888 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003889 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003890 SemaRef
3891 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3892 Sema::AA_Converting,
3893 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003894 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003895 }
3896
3897 // Choose either the 32-bit or 64-bit version.
3898 ExprResult LastIteration = LastIteration64;
3899 if (LastIteration32.isUsable() &&
3900 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3901 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3902 FitsInto(
3903 32 /* Bits */,
3904 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3905 LastIteration64.get(), SemaRef)))
3906 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00003907 QualType VType = LastIteration.get()->getType();
3908 QualType RealVType = VType;
3909 QualType StrideVType = VType;
3910 if (isOpenMPTaskLoopDirective(DKind)) {
3911 VType =
3912 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3913 StrideVType =
3914 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3915 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003916
3917 if (!LastIteration.isUsable())
3918 return 0;
3919
3920 // Save the number of iterations.
3921 ExprResult NumIterations = LastIteration;
3922 {
3923 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003924 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
3925 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003926 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3927 if (!LastIteration.isUsable())
3928 return 0;
3929 }
3930
3931 // Calculate the last iteration number beforehand instead of doing this on
3932 // each iteration. Do not do this if the number of iterations may be kfold-ed.
3933 llvm::APSInt Result;
3934 bool IsConstant =
3935 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3936 ExprResult CalcLastIteration;
3937 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003938 ExprResult SaveRef =
3939 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003940 LastIteration = SaveRef;
3941
3942 // Prepare SaveRef + 1.
3943 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003944 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00003945 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3946 if (!NumIterations.isUsable())
3947 return 0;
3948 }
3949
3950 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3951
David Majnemer9d168222016-08-05 17:44:54 +00003952 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00003953 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003954 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3955 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003956 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003957 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3958 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003959 SemaRef.AddInitializerToDecl(
3960 LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3961 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3962
3963 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00003964 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3965 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003966 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3967 /*DirectInit*/ false,
3968 /*TypeMayContainAuto*/ false);
3969
3970 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3971 // This will be used to implement clause 'lastprivate'.
3972 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00003973 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3974 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003975 SemaRef.AddInitializerToDecl(
3976 ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3977 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3978
3979 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00003980 VarDecl *STDecl =
3981 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3982 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00003983 SemaRef.AddInitializerToDecl(
3984 STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3985 /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3986
3987 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00003988 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00003989 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3990 UB.get(), LastIteration.get());
3991 ExprResult CondOp = SemaRef.ActOnConditionalOp(
3992 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3993 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3994 CondOp.get());
3995 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00003996
3997 // If we have a combined directive that combines 'distribute', 'for' or
3998 // 'simd' we need to be able to access the bounds of the schedule of the
3999 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4000 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4001 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4002 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4003
4004 // We expect to have at least 2 more parameters than the 'parallel'
4005 // directive does - the lower and upper bounds of the previous schedule.
4006 assert(CD->getNumParams() >= 4 &&
4007 "Unexpected number of parameters in loop combined directive");
4008
4009 // Set the proper type for the bounds given what we learned from the
4010 // enclosed loops.
4011 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4012 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4013
4014 // Previous lower and upper bounds are obtained from the region
4015 // parameters.
4016 PrevLB =
4017 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4018 PrevUB =
4019 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4020 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004021 }
4022
4023 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004024 ExprResult IV;
4025 ExprResult Init;
4026 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004027 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4028 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004029 Expr *RHS =
4030 (isOpenMPWorksharingDirective(DKind) ||
4031 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4032 ? LB.get()
4033 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004034 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4035 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004036 }
4037
Alexander Musmanc6388682014-12-15 07:07:06 +00004038 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004039 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004040 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004041 (isOpenMPWorksharingDirective(DKind) ||
4042 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004043 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4044 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4045 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004046
4047 // Loop increment (IV = IV + 1)
4048 SourceLocation IncLoc;
4049 ExprResult Inc =
4050 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4051 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4052 if (!Inc.isUsable())
4053 return 0;
4054 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004055 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4056 if (!Inc.isUsable())
4057 return 0;
4058
4059 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4060 // Used for directives with static scheduling.
4061 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004062 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4063 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004064 // LB + ST
4065 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4066 if (!NextLB.isUsable())
4067 return 0;
4068 // LB = LB + ST
4069 NextLB =
4070 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4071 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4072 if (!NextLB.isUsable())
4073 return 0;
4074 // UB + ST
4075 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4076 if (!NextUB.isUsable())
4077 return 0;
4078 // UB = UB + ST
4079 NextUB =
4080 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4081 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4082 if (!NextUB.isUsable())
4083 return 0;
4084 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004085
4086 // Build updates and final values of the loop counters.
4087 bool HasErrors = false;
4088 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004089 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004090 Built.Updates.resize(NestedLoopCount);
4091 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004092 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004093 {
4094 ExprResult Div;
4095 // Go from inner nested loop to outer.
4096 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4097 LoopIterationSpace &IS = IterSpaces[Cnt];
4098 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4099 // Build: Iter = (IV / Div) % IS.NumIters
4100 // where Div is product of previous iterations' IS.NumIters.
4101 ExprResult Iter;
4102 if (Div.isUsable()) {
4103 Iter =
4104 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4105 } else {
4106 Iter = IV;
4107 assert((Cnt == (int)NestedLoopCount - 1) &&
4108 "unusable div expected on first iteration only");
4109 }
4110
4111 if (Cnt != 0 && Iter.isUsable())
4112 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4113 IS.NumIterations);
4114 if (!Iter.isUsable()) {
4115 HasErrors = true;
4116 break;
4117 }
4118
Alexey Bataev39f915b82015-05-08 10:41:21 +00004119 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004120 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4121 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4122 IS.CounterVar->getExprLoc(),
4123 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004124 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004125 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004126 if (!Init.isUsable()) {
4127 HasErrors = true;
4128 break;
4129 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004130 ExprResult Update = BuildCounterUpdate(
4131 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4132 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004133 if (!Update.isUsable()) {
4134 HasErrors = true;
4135 break;
4136 }
4137
4138 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4139 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004140 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004141 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004142 if (!Final.isUsable()) {
4143 HasErrors = true;
4144 break;
4145 }
4146
4147 // Build Div for the next iteration: Div <- Div * IS.NumIters
4148 if (Cnt != 0) {
4149 if (Div.isUnset())
4150 Div = IS.NumIterations;
4151 else
4152 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4153 IS.NumIterations);
4154
4155 // Add parentheses (for debugging purposes only).
4156 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004157 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004158 if (!Div.isUsable()) {
4159 HasErrors = true;
4160 break;
4161 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004162 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004163 }
4164 if (!Update.isUsable() || !Final.isUsable()) {
4165 HasErrors = true;
4166 break;
4167 }
4168 // Save results
4169 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004170 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004171 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004172 Built.Updates[Cnt] = Update.get();
4173 Built.Finals[Cnt] = Final.get();
4174 }
4175 }
4176
4177 if (HasErrors)
4178 return 0;
4179
4180 // Save results
4181 Built.IterationVarRef = IV.get();
4182 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004183 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004184 Built.CalcLastIteration =
4185 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004186 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004187 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004188 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004189 Built.Init = Init.get();
4190 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004191 Built.LB = LB.get();
4192 Built.UB = UB.get();
4193 Built.IL = IL.get();
4194 Built.ST = ST.get();
4195 Built.EUB = EUB.get();
4196 Built.NLB = NextLB.get();
4197 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004198 Built.PrevLB = PrevLB.get();
4199 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004200
Alexey Bataev8b427062016-05-25 12:36:08 +00004201 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4202 // Fill data for doacross depend clauses.
4203 for (auto Pair : DSA.getDoacrossDependClauses()) {
4204 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4205 Pair.first->setCounterValue(CounterVal);
4206 else {
4207 if (NestedLoopCount != Pair.second.size() ||
4208 NestedLoopCount != LoopMultipliers.size() + 1) {
4209 // Erroneous case - clause has some problems.
4210 Pair.first->setCounterValue(CounterVal);
4211 continue;
4212 }
4213 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4214 auto I = Pair.second.rbegin();
4215 auto IS = IterSpaces.rbegin();
4216 auto ILM = LoopMultipliers.rbegin();
4217 Expr *UpCounterVal = CounterVal;
4218 Expr *Multiplier = nullptr;
4219 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4220 if (I->first) {
4221 assert(IS->CounterStep);
4222 Expr *NormalizedOffset =
4223 SemaRef
4224 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4225 I->first, IS->CounterStep)
4226 .get();
4227 if (Multiplier) {
4228 NormalizedOffset =
4229 SemaRef
4230 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4231 NormalizedOffset, Multiplier)
4232 .get();
4233 }
4234 assert(I->second == OO_Plus || I->second == OO_Minus);
4235 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004236 UpCounterVal = SemaRef
4237 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4238 UpCounterVal, NormalizedOffset)
4239 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004240 }
4241 Multiplier = *ILM;
4242 ++I;
4243 ++IS;
4244 ++ILM;
4245 }
4246 Pair.first->setCounterValue(UpCounterVal);
4247 }
4248 }
4249
Alexey Bataevabfc0692014-06-25 06:52:00 +00004250 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004251}
4252
Alexey Bataev10e775f2015-07-30 11:36:16 +00004253static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004254 auto CollapseClauses =
4255 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4256 if (CollapseClauses.begin() != CollapseClauses.end())
4257 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004258 return nullptr;
4259}
4260
Alexey Bataev10e775f2015-07-30 11:36:16 +00004261static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004262 auto OrderedClauses =
4263 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4264 if (OrderedClauses.begin() != OrderedClauses.end())
4265 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004266 return nullptr;
4267}
4268
Kelvin Lic5609492016-07-15 04:39:07 +00004269static bool checkSimdlenSafelenSpecified(Sema &S,
4270 const ArrayRef<OMPClause *> Clauses) {
4271 OMPSafelenClause *Safelen = nullptr;
4272 OMPSimdlenClause *Simdlen = nullptr;
4273
4274 for (auto *Clause : Clauses) {
4275 if (Clause->getClauseKind() == OMPC_safelen)
4276 Safelen = cast<OMPSafelenClause>(Clause);
4277 else if (Clause->getClauseKind() == OMPC_simdlen)
4278 Simdlen = cast<OMPSimdlenClause>(Clause);
4279 if (Safelen && Simdlen)
4280 break;
4281 }
4282
4283 if (Simdlen && Safelen) {
4284 llvm::APSInt SimdlenRes, SafelenRes;
4285 auto SimdlenLength = Simdlen->getSimdlen();
4286 auto SafelenLength = Safelen->getSafelen();
4287 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4288 SimdlenLength->isInstantiationDependent() ||
4289 SimdlenLength->containsUnexpandedParameterPack())
4290 return false;
4291 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4292 SafelenLength->isInstantiationDependent() ||
4293 SafelenLength->containsUnexpandedParameterPack())
4294 return false;
4295 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4296 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4297 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4298 // If both simdlen and safelen clauses are specified, the value of the
4299 // simdlen parameter must be less than or equal to the value of the safelen
4300 // parameter.
4301 if (SimdlenRes > SafelenRes) {
4302 S.Diag(SimdlenLength->getExprLoc(),
4303 diag::err_omp_wrong_simdlen_safelen_values)
4304 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4305 return true;
4306 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004307 }
4308 return false;
4309}
4310
Alexey Bataev4acb8592014-07-07 13:01:15 +00004311StmtResult Sema::ActOnOpenMPSimdDirective(
4312 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4313 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004314 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004315 if (!AStmt)
4316 return StmtError();
4317
4318 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004319 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004320 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4321 // define the nested loops number.
4322 unsigned NestedLoopCount = CheckOpenMPLoop(
4323 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4324 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004325 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004326 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004327
Alexander Musmana5f070a2014-10-01 06:03:56 +00004328 assert((CurContext->isDependentContext() || B.builtAll()) &&
4329 "omp simd loop exprs were not built");
4330
Alexander Musman3276a272015-03-21 10:12:56 +00004331 if (!CurContext->isDependentContext()) {
4332 // Finalize the clauses that need pre-built expressions for CodeGen.
4333 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004334 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004335 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004336 B.NumIterations, *this, CurScope,
4337 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004338 return StmtError();
4339 }
4340 }
4341
Kelvin Lic5609492016-07-15 04:39:07 +00004342 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004343 return StmtError();
4344
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004345 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004346 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4347 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004348}
4349
Alexey Bataev4acb8592014-07-07 13:01:15 +00004350StmtResult Sema::ActOnOpenMPForDirective(
4351 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4352 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004353 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004354 if (!AStmt)
4355 return StmtError();
4356
4357 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004358 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004359 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4360 // define the nested loops number.
4361 unsigned NestedLoopCount = CheckOpenMPLoop(
4362 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4363 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004364 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004365 return StmtError();
4366
Alexander Musmana5f070a2014-10-01 06:03:56 +00004367 assert((CurContext->isDependentContext() || B.builtAll()) &&
4368 "omp for loop exprs were not built");
4369
Alexey Bataev54acd402015-08-04 11:18:19 +00004370 if (!CurContext->isDependentContext()) {
4371 // Finalize the clauses that need pre-built expressions for CodeGen.
4372 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004373 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004374 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004375 B.NumIterations, *this, CurScope,
4376 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004377 return StmtError();
4378 }
4379 }
4380
Alexey Bataevf29276e2014-06-18 04:14:57 +00004381 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004382 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004383 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004384}
4385
Alexander Musmanf82886e2014-09-18 05:12:34 +00004386StmtResult Sema::ActOnOpenMPForSimdDirective(
4387 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4388 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004389 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004390 if (!AStmt)
4391 return StmtError();
4392
4393 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004394 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004395 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4396 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004397 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004398 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4399 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4400 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004401 if (NestedLoopCount == 0)
4402 return StmtError();
4403
Alexander Musmanc6388682014-12-15 07:07:06 +00004404 assert((CurContext->isDependentContext() || B.builtAll()) &&
4405 "omp for simd loop exprs were not built");
4406
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004407 if (!CurContext->isDependentContext()) {
4408 // Finalize the clauses that need pre-built expressions for CodeGen.
4409 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004410 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004411 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004412 B.NumIterations, *this, CurScope,
4413 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004414 return StmtError();
4415 }
4416 }
4417
Kelvin Lic5609492016-07-15 04:39:07 +00004418 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004419 return StmtError();
4420
Alexander Musmanf82886e2014-09-18 05:12:34 +00004421 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004422 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4423 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004424}
4425
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004426StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4427 Stmt *AStmt,
4428 SourceLocation StartLoc,
4429 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004430 if (!AStmt)
4431 return StmtError();
4432
4433 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004434 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004435 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004436 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004437 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004438 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004439 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004440 return StmtError();
4441 // All associated statements must be '#pragma omp section' except for
4442 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004443 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004444 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4445 if (SectionStmt)
4446 Diag(SectionStmt->getLocStart(),
4447 diag::err_omp_sections_substmt_not_section);
4448 return StmtError();
4449 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004450 cast<OMPSectionDirective>(SectionStmt)
4451 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004452 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004453 } else {
4454 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4455 return StmtError();
4456 }
4457
4458 getCurFunction()->setHasBranchProtectedScope();
4459
Alexey Bataev25e5b442015-09-15 12:52:43 +00004460 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4461 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004462}
4463
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004464StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4465 SourceLocation StartLoc,
4466 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004467 if (!AStmt)
4468 return StmtError();
4469
4470 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004471
4472 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004473 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004474
Alexey Bataev25e5b442015-09-15 12:52:43 +00004475 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4476 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004477}
4478
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004479StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4480 Stmt *AStmt,
4481 SourceLocation StartLoc,
4482 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004483 if (!AStmt)
4484 return StmtError();
4485
4486 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004487
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004488 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004489
Alexey Bataev3255bf32015-01-19 05:20:46 +00004490 // OpenMP [2.7.3, single Construct, Restrictions]
4491 // The copyprivate clause must not be used with the nowait clause.
4492 OMPClause *Nowait = nullptr;
4493 OMPClause *Copyprivate = nullptr;
4494 for (auto *Clause : Clauses) {
4495 if (Clause->getClauseKind() == OMPC_nowait)
4496 Nowait = Clause;
4497 else if (Clause->getClauseKind() == OMPC_copyprivate)
4498 Copyprivate = Clause;
4499 if (Copyprivate && Nowait) {
4500 Diag(Copyprivate->getLocStart(),
4501 diag::err_omp_single_copyprivate_with_nowait);
4502 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4503 return StmtError();
4504 }
4505 }
4506
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004507 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4508}
4509
Alexander Musman80c22892014-07-17 08:54:58 +00004510StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4511 SourceLocation StartLoc,
4512 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004513 if (!AStmt)
4514 return StmtError();
4515
4516 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004517
4518 getCurFunction()->setHasBranchProtectedScope();
4519
4520 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4521}
4522
Alexey Bataev28c75412015-12-15 08:19:24 +00004523StmtResult Sema::ActOnOpenMPCriticalDirective(
4524 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4525 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004526 if (!AStmt)
4527 return StmtError();
4528
4529 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004530
Alexey Bataev28c75412015-12-15 08:19:24 +00004531 bool ErrorFound = false;
4532 llvm::APSInt Hint;
4533 SourceLocation HintLoc;
4534 bool DependentHint = false;
4535 for (auto *C : Clauses) {
4536 if (C->getClauseKind() == OMPC_hint) {
4537 if (!DirName.getName()) {
4538 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4539 ErrorFound = true;
4540 }
4541 Expr *E = cast<OMPHintClause>(C)->getHint();
4542 if (E->isTypeDependent() || E->isValueDependent() ||
4543 E->isInstantiationDependent())
4544 DependentHint = true;
4545 else {
4546 Hint = E->EvaluateKnownConstInt(Context);
4547 HintLoc = C->getLocStart();
4548 }
4549 }
4550 }
4551 if (ErrorFound)
4552 return StmtError();
4553 auto Pair = DSAStack->getCriticalWithHint(DirName);
4554 if (Pair.first && DirName.getName() && !DependentHint) {
4555 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4556 Diag(StartLoc, diag::err_omp_critical_with_hint);
4557 if (HintLoc.isValid()) {
4558 Diag(HintLoc, diag::note_omp_critical_hint_here)
4559 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4560 } else
4561 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4562 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4563 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4564 << 1
4565 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4566 /*Radix=*/10, /*Signed=*/false);
4567 } else
4568 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4569 }
4570 }
4571
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004572 getCurFunction()->setHasBranchProtectedScope();
4573
Alexey Bataev28c75412015-12-15 08:19:24 +00004574 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4575 Clauses, AStmt);
4576 if (!Pair.first && DirName.getName() && !DependentHint)
4577 DSAStack->addCriticalWithHint(Dir, Hint);
4578 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004579}
4580
Alexey Bataev4acb8592014-07-07 13:01:15 +00004581StmtResult Sema::ActOnOpenMPParallelForDirective(
4582 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4583 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004584 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004585 if (!AStmt)
4586 return StmtError();
4587
Alexey Bataev4acb8592014-07-07 13:01:15 +00004588 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4589 // 1.2.2 OpenMP Language Terminology
4590 // Structured block - An executable statement with a single entry at the
4591 // top and a single exit at the bottom.
4592 // The point of exit cannot be a branch out of the structured block.
4593 // longjmp() and throw() must not violate the entry/exit criteria.
4594 CS->getCapturedDecl()->setNothrow();
4595
Alexander Musmanc6388682014-12-15 07:07:06 +00004596 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004597 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4598 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004599 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004600 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4601 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4602 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004603 if (NestedLoopCount == 0)
4604 return StmtError();
4605
Alexander Musmana5f070a2014-10-01 06:03:56 +00004606 assert((CurContext->isDependentContext() || B.builtAll()) &&
4607 "omp parallel for loop exprs were not built");
4608
Alexey Bataev54acd402015-08-04 11:18:19 +00004609 if (!CurContext->isDependentContext()) {
4610 // Finalize the clauses that need pre-built expressions for CodeGen.
4611 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004612 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004613 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004614 B.NumIterations, *this, CurScope,
4615 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004616 return StmtError();
4617 }
4618 }
4619
Alexey Bataev4acb8592014-07-07 13:01:15 +00004620 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004621 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004622 NestedLoopCount, Clauses, AStmt, B,
4623 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004624}
4625
Alexander Musmane4e893b2014-09-23 09:33:00 +00004626StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4627 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4628 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004629 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004630 if (!AStmt)
4631 return StmtError();
4632
Alexander Musmane4e893b2014-09-23 09:33:00 +00004633 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4634 // 1.2.2 OpenMP Language Terminology
4635 // Structured block - An executable statement with a single entry at the
4636 // top and a single exit at the bottom.
4637 // The point of exit cannot be a branch out of the structured block.
4638 // longjmp() and throw() must not violate the entry/exit criteria.
4639 CS->getCapturedDecl()->setNothrow();
4640
Alexander Musmanc6388682014-12-15 07:07:06 +00004641 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004642 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4643 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004644 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004645 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4646 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4647 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004648 if (NestedLoopCount == 0)
4649 return StmtError();
4650
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004651 if (!CurContext->isDependentContext()) {
4652 // Finalize the clauses that need pre-built expressions for CodeGen.
4653 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004654 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004655 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004656 B.NumIterations, *this, CurScope,
4657 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004658 return StmtError();
4659 }
4660 }
4661
Kelvin Lic5609492016-07-15 04:39:07 +00004662 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004663 return StmtError();
4664
Alexander Musmane4e893b2014-09-23 09:33:00 +00004665 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004666 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004667 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004668}
4669
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004670StmtResult
4671Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4672 Stmt *AStmt, SourceLocation StartLoc,
4673 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004674 if (!AStmt)
4675 return StmtError();
4676
4677 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004678 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004679 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004680 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004681 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004682 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004683 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004684 return StmtError();
4685 // All associated statements must be '#pragma omp section' except for
4686 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004687 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004688 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4689 if (SectionStmt)
4690 Diag(SectionStmt->getLocStart(),
4691 diag::err_omp_parallel_sections_substmt_not_section);
4692 return StmtError();
4693 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004694 cast<OMPSectionDirective>(SectionStmt)
4695 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004696 }
4697 } else {
4698 Diag(AStmt->getLocStart(),
4699 diag::err_omp_parallel_sections_not_compound_stmt);
4700 return StmtError();
4701 }
4702
4703 getCurFunction()->setHasBranchProtectedScope();
4704
Alexey Bataev25e5b442015-09-15 12:52:43 +00004705 return OMPParallelSectionsDirective::Create(
4706 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004707}
4708
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004709StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4710 Stmt *AStmt, SourceLocation StartLoc,
4711 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004712 if (!AStmt)
4713 return StmtError();
4714
David Majnemer9d168222016-08-05 17:44:54 +00004715 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004716 // 1.2.2 OpenMP Language Terminology
4717 // Structured block - An executable statement with a single entry at the
4718 // top and a single exit at the bottom.
4719 // The point of exit cannot be a branch out of the structured block.
4720 // longjmp() and throw() must not violate the entry/exit criteria.
4721 CS->getCapturedDecl()->setNothrow();
4722
4723 getCurFunction()->setHasBranchProtectedScope();
4724
Alexey Bataev25e5b442015-09-15 12:52:43 +00004725 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4726 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004727}
4728
Alexey Bataev68446b72014-07-18 07:47:19 +00004729StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4730 SourceLocation EndLoc) {
4731 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4732}
4733
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004734StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4735 SourceLocation EndLoc) {
4736 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4737}
4738
Alexey Bataev2df347a2014-07-18 10:17:07 +00004739StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4740 SourceLocation EndLoc) {
4741 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4742}
4743
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004744StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4745 SourceLocation StartLoc,
4746 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004747 if (!AStmt)
4748 return StmtError();
4749
4750 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004751
4752 getCurFunction()->setHasBranchProtectedScope();
4753
4754 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4755}
4756
Alexey Bataev6125da92014-07-21 11:26:11 +00004757StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4758 SourceLocation StartLoc,
4759 SourceLocation EndLoc) {
4760 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4761 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4762}
4763
Alexey Bataev346265e2015-09-25 10:37:12 +00004764StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4765 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004766 SourceLocation StartLoc,
4767 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004768 OMPClause *DependFound = nullptr;
4769 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004770 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004771 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004772 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004773 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004774 for (auto *C : Clauses) {
4775 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4776 DependFound = C;
4777 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4778 if (DependSourceClause) {
4779 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4780 << getOpenMPDirectiveName(OMPD_ordered)
4781 << getOpenMPClauseName(OMPC_depend) << 2;
4782 ErrorFound = true;
4783 } else
4784 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004785 if (DependSinkClause) {
4786 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4787 << 0;
4788 ErrorFound = true;
4789 }
4790 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4791 if (DependSourceClause) {
4792 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4793 << 1;
4794 ErrorFound = true;
4795 }
4796 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004797 }
4798 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004799 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004800 else if (C->getClauseKind() == OMPC_simd)
4801 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004802 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004803 if (!ErrorFound && !SC &&
4804 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004805 // OpenMP [2.8.1,simd Construct, Restrictions]
4806 // An ordered construct with the simd clause is the only OpenMP construct
4807 // that can appear in the simd region.
4808 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004809 ErrorFound = true;
4810 } else if (DependFound && (TC || SC)) {
4811 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4812 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4813 ErrorFound = true;
4814 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4815 Diag(DependFound->getLocStart(),
4816 diag::err_omp_ordered_directive_without_param);
4817 ErrorFound = true;
4818 } else if (TC || Clauses.empty()) {
4819 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4820 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4821 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4822 << (TC != nullptr);
4823 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4824 ErrorFound = true;
4825 }
4826 }
4827 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004828 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004829
4830 if (AStmt) {
4831 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4832
4833 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004834 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004835
4836 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004837}
4838
Alexey Bataev1d160b12015-03-13 12:27:31 +00004839namespace {
4840/// \brief Helper class for checking expression in 'omp atomic [update]'
4841/// construct.
4842class OpenMPAtomicUpdateChecker {
4843 /// \brief Error results for atomic update expressions.
4844 enum ExprAnalysisErrorCode {
4845 /// \brief A statement is not an expression statement.
4846 NotAnExpression,
4847 /// \brief Expression is not builtin binary or unary operation.
4848 NotABinaryOrUnaryExpression,
4849 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4850 NotAnUnaryIncDecExpression,
4851 /// \brief An expression is not of scalar type.
4852 NotAScalarType,
4853 /// \brief A binary operation is not an assignment operation.
4854 NotAnAssignmentOp,
4855 /// \brief RHS part of the binary operation is not a binary expression.
4856 NotABinaryExpression,
4857 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4858 /// expression.
4859 NotABinaryOperator,
4860 /// \brief RHS binary operation does not have reference to the updated LHS
4861 /// part.
4862 NotAnUpdateExpression,
4863 /// \brief No errors is found.
4864 NoError
4865 };
4866 /// \brief Reference to Sema.
4867 Sema &SemaRef;
4868 /// \brief A location for note diagnostics (when error is found).
4869 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004870 /// \brief 'x' lvalue part of the source atomic expression.
4871 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004872 /// \brief 'expr' rvalue part of the source atomic expression.
4873 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004874 /// \brief Helper expression of the form
4875 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4876 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4877 Expr *UpdateExpr;
4878 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4879 /// important for non-associative operations.
4880 bool IsXLHSInRHSPart;
4881 BinaryOperatorKind Op;
4882 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004883 /// \brief true if the source expression is a postfix unary operation, false
4884 /// if it is a prefix unary operation.
4885 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004886
4887public:
4888 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004889 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004890 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004891 /// \brief Check specified statement that it is suitable for 'atomic update'
4892 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004893 /// expression. If DiagId and NoteId == 0, then only check is performed
4894 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004895 /// \param DiagId Diagnostic which should be emitted if error is found.
4896 /// \param NoteId Diagnostic note for the main error message.
4897 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004898 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004899 /// \brief Return the 'x' lvalue part of the source atomic expression.
4900 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004901 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4902 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004903 /// \brief Return the update expression used in calculation of the updated
4904 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4905 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4906 Expr *getUpdateExpr() const { return UpdateExpr; }
4907 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4908 /// false otherwise.
4909 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4910
Alexey Bataevb78ca832015-04-01 03:33:17 +00004911 /// \brief true if the source expression is a postfix unary operation, false
4912 /// if it is a prefix unary operation.
4913 bool isPostfixUpdate() const { return IsPostfixUpdate; }
4914
Alexey Bataev1d160b12015-03-13 12:27:31 +00004915private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00004916 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4917 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004918};
4919} // namespace
4920
4921bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4922 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4923 ExprAnalysisErrorCode ErrorFound = NoError;
4924 SourceLocation ErrorLoc, NoteLoc;
4925 SourceRange ErrorRange, NoteRange;
4926 // Allowed constructs are:
4927 // x = x binop expr;
4928 // x = expr binop x;
4929 if (AtomicBinOp->getOpcode() == BO_Assign) {
4930 X = AtomicBinOp->getLHS();
4931 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4932 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4933 if (AtomicInnerBinOp->isMultiplicativeOp() ||
4934 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4935 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00004936 Op = AtomicInnerBinOp->getOpcode();
4937 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00004938 auto *LHS = AtomicInnerBinOp->getLHS();
4939 auto *RHS = AtomicInnerBinOp->getRHS();
4940 llvm::FoldingSetNodeID XId, LHSId, RHSId;
4941 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4942 /*Canonical=*/true);
4943 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4944 /*Canonical=*/true);
4945 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4946 /*Canonical=*/true);
4947 if (XId == LHSId) {
4948 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004949 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004950 } else if (XId == RHSId) {
4951 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004952 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004953 } else {
4954 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4955 ErrorRange = AtomicInnerBinOp->getSourceRange();
4956 NoteLoc = X->getExprLoc();
4957 NoteRange = X->getSourceRange();
4958 ErrorFound = NotAnUpdateExpression;
4959 }
4960 } else {
4961 ErrorLoc = AtomicInnerBinOp->getExprLoc();
4962 ErrorRange = AtomicInnerBinOp->getSourceRange();
4963 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4964 NoteRange = SourceRange(NoteLoc, NoteLoc);
4965 ErrorFound = NotABinaryOperator;
4966 }
4967 } else {
4968 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4969 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4970 ErrorFound = NotABinaryExpression;
4971 }
4972 } else {
4973 ErrorLoc = AtomicBinOp->getExprLoc();
4974 ErrorRange = AtomicBinOp->getSourceRange();
4975 NoteLoc = AtomicBinOp->getOperatorLoc();
4976 NoteRange = SourceRange(NoteLoc, NoteLoc);
4977 ErrorFound = NotAnAssignmentOp;
4978 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00004979 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00004980 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4981 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4982 return true;
4983 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00004984 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00004985 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004986}
4987
4988bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4989 unsigned NoteId) {
4990 ExprAnalysisErrorCode ErrorFound = NoError;
4991 SourceLocation ErrorLoc, NoteLoc;
4992 SourceRange ErrorRange, NoteRange;
4993 // Allowed constructs are:
4994 // x++;
4995 // x--;
4996 // ++x;
4997 // --x;
4998 // x binop= expr;
4999 // x = x binop expr;
5000 // x = expr binop x;
5001 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5002 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5003 if (AtomicBody->getType()->isScalarType() ||
5004 AtomicBody->isInstantiationDependent()) {
5005 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5006 AtomicBody->IgnoreParenImpCasts())) {
5007 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005008 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005009 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005010 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005011 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005012 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005013 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005014 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5015 AtomicBody->IgnoreParenImpCasts())) {
5016 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005017 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005018 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005019 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5020 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005021 // Check for Unary Operation
5022 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005023 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005024 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5025 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005026 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005027 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5028 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005029 } else {
5030 ErrorFound = NotAnUnaryIncDecExpression;
5031 ErrorLoc = AtomicUnaryOp->getExprLoc();
5032 ErrorRange = AtomicUnaryOp->getSourceRange();
5033 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5034 NoteRange = SourceRange(NoteLoc, NoteLoc);
5035 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005036 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005037 ErrorFound = NotABinaryOrUnaryExpression;
5038 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5039 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5040 }
5041 } else {
5042 ErrorFound = NotAScalarType;
5043 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5044 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5045 }
5046 } else {
5047 ErrorFound = NotAnExpression;
5048 NoteLoc = ErrorLoc = S->getLocStart();
5049 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5050 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005051 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005052 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5053 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5054 return true;
5055 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005056 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005057 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005058 // Build an update expression of form 'OpaqueValueExpr(x) binop
5059 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5060 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5061 auto *OVEX = new (SemaRef.getASTContext())
5062 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5063 auto *OVEExpr = new (SemaRef.getASTContext())
5064 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5065 auto Update =
5066 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5067 IsXLHSInRHSPart ? OVEExpr : OVEX);
5068 if (Update.isInvalid())
5069 return true;
5070 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5071 Sema::AA_Casting);
5072 if (Update.isInvalid())
5073 return true;
5074 UpdateExpr = Update.get();
5075 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005076 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005077}
5078
Alexey Bataev0162e452014-07-22 10:10:35 +00005079StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5080 Stmt *AStmt,
5081 SourceLocation StartLoc,
5082 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005083 if (!AStmt)
5084 return StmtError();
5085
David Majnemer9d168222016-08-05 17:44:54 +00005086 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005087 // 1.2.2 OpenMP Language Terminology
5088 // Structured block - An executable statement with a single entry at the
5089 // top and a single exit at the bottom.
5090 // The point of exit cannot be a branch out of the structured block.
5091 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005092 OpenMPClauseKind AtomicKind = OMPC_unknown;
5093 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005094 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005095 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005096 C->getClauseKind() == OMPC_update ||
5097 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005098 if (AtomicKind != OMPC_unknown) {
5099 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5100 << SourceRange(C->getLocStart(), C->getLocEnd());
5101 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5102 << getOpenMPClauseName(AtomicKind);
5103 } else {
5104 AtomicKind = C->getClauseKind();
5105 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005106 }
5107 }
5108 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005109
Alexey Bataev459dec02014-07-24 06:46:57 +00005110 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005111 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5112 Body = EWC->getSubExpr();
5113
Alexey Bataev62cec442014-11-18 10:14:22 +00005114 Expr *X = nullptr;
5115 Expr *V = nullptr;
5116 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005117 Expr *UE = nullptr;
5118 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005119 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005120 // OpenMP [2.12.6, atomic Construct]
5121 // In the next expressions:
5122 // * x and v (as applicable) are both l-value expressions with scalar type.
5123 // * During the execution of an atomic region, multiple syntactic
5124 // occurrences of x must designate the same storage location.
5125 // * Neither of v and expr (as applicable) may access the storage location
5126 // designated by x.
5127 // * Neither of x and expr (as applicable) may access the storage location
5128 // designated by v.
5129 // * expr is an expression with scalar type.
5130 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5131 // * binop, binop=, ++, and -- are not overloaded operators.
5132 // * The expression x binop expr must be numerically equivalent to x binop
5133 // (expr). This requirement is satisfied if the operators in expr have
5134 // precedence greater than binop, or by using parentheses around expr or
5135 // subexpressions of expr.
5136 // * The expression expr binop x must be numerically equivalent to (expr)
5137 // binop x. This requirement is satisfied if the operators in expr have
5138 // precedence equal to or greater than binop, or by using parentheses around
5139 // expr or subexpressions of expr.
5140 // * For forms that allow multiple occurrences of x, the number of times
5141 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005142 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005143 enum {
5144 NotAnExpression,
5145 NotAnAssignmentOp,
5146 NotAScalarType,
5147 NotAnLValue,
5148 NoError
5149 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005150 SourceLocation ErrorLoc, NoteLoc;
5151 SourceRange ErrorRange, NoteRange;
5152 // If clause is read:
5153 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005154 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5155 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005156 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5157 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5158 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5159 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5160 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5161 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5162 if (!X->isLValue() || !V->isLValue()) {
5163 auto NotLValueExpr = X->isLValue() ? V : X;
5164 ErrorFound = NotAnLValue;
5165 ErrorLoc = AtomicBinOp->getExprLoc();
5166 ErrorRange = AtomicBinOp->getSourceRange();
5167 NoteLoc = NotLValueExpr->getExprLoc();
5168 NoteRange = NotLValueExpr->getSourceRange();
5169 }
5170 } else if (!X->isInstantiationDependent() ||
5171 !V->isInstantiationDependent()) {
5172 auto NotScalarExpr =
5173 (X->isInstantiationDependent() || X->getType()->isScalarType())
5174 ? V
5175 : X;
5176 ErrorFound = NotAScalarType;
5177 ErrorLoc = AtomicBinOp->getExprLoc();
5178 ErrorRange = AtomicBinOp->getSourceRange();
5179 NoteLoc = NotScalarExpr->getExprLoc();
5180 NoteRange = NotScalarExpr->getSourceRange();
5181 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005182 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005183 ErrorFound = NotAnAssignmentOp;
5184 ErrorLoc = AtomicBody->getExprLoc();
5185 ErrorRange = AtomicBody->getSourceRange();
5186 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5187 : AtomicBody->getExprLoc();
5188 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5189 : AtomicBody->getSourceRange();
5190 }
5191 } else {
5192 ErrorFound = NotAnExpression;
5193 NoteLoc = ErrorLoc = Body->getLocStart();
5194 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005195 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005196 if (ErrorFound != NoError) {
5197 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5198 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005199 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5200 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005201 return StmtError();
5202 } else if (CurContext->isDependentContext())
5203 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005204 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005205 enum {
5206 NotAnExpression,
5207 NotAnAssignmentOp,
5208 NotAScalarType,
5209 NotAnLValue,
5210 NoError
5211 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005212 SourceLocation ErrorLoc, NoteLoc;
5213 SourceRange ErrorRange, NoteRange;
5214 // If clause is write:
5215 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005216 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5217 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005218 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5219 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005220 X = AtomicBinOp->getLHS();
5221 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005222 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5223 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5224 if (!X->isLValue()) {
5225 ErrorFound = NotAnLValue;
5226 ErrorLoc = AtomicBinOp->getExprLoc();
5227 ErrorRange = AtomicBinOp->getSourceRange();
5228 NoteLoc = X->getExprLoc();
5229 NoteRange = X->getSourceRange();
5230 }
5231 } else if (!X->isInstantiationDependent() ||
5232 !E->isInstantiationDependent()) {
5233 auto NotScalarExpr =
5234 (X->isInstantiationDependent() || X->getType()->isScalarType())
5235 ? E
5236 : X;
5237 ErrorFound = NotAScalarType;
5238 ErrorLoc = AtomicBinOp->getExprLoc();
5239 ErrorRange = AtomicBinOp->getSourceRange();
5240 NoteLoc = NotScalarExpr->getExprLoc();
5241 NoteRange = NotScalarExpr->getSourceRange();
5242 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005243 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005244 ErrorFound = NotAnAssignmentOp;
5245 ErrorLoc = AtomicBody->getExprLoc();
5246 ErrorRange = AtomicBody->getSourceRange();
5247 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5248 : AtomicBody->getExprLoc();
5249 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5250 : AtomicBody->getSourceRange();
5251 }
5252 } else {
5253 ErrorFound = NotAnExpression;
5254 NoteLoc = ErrorLoc = Body->getLocStart();
5255 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005256 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005257 if (ErrorFound != NoError) {
5258 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5259 << ErrorRange;
5260 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5261 << NoteRange;
5262 return StmtError();
5263 } else if (CurContext->isDependentContext())
5264 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005265 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005266 // If clause is update:
5267 // x++;
5268 // x--;
5269 // ++x;
5270 // --x;
5271 // x binop= expr;
5272 // x = x binop expr;
5273 // x = expr binop x;
5274 OpenMPAtomicUpdateChecker Checker(*this);
5275 if (Checker.checkStatement(
5276 Body, (AtomicKind == OMPC_update)
5277 ? diag::err_omp_atomic_update_not_expression_statement
5278 : diag::err_omp_atomic_not_expression_statement,
5279 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005280 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005281 if (!CurContext->isDependentContext()) {
5282 E = Checker.getExpr();
5283 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005284 UE = Checker.getUpdateExpr();
5285 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005286 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005287 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005288 enum {
5289 NotAnAssignmentOp,
5290 NotACompoundStatement,
5291 NotTwoSubstatements,
5292 NotASpecificExpression,
5293 NoError
5294 } ErrorFound = NoError;
5295 SourceLocation ErrorLoc, NoteLoc;
5296 SourceRange ErrorRange, NoteRange;
5297 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5298 // If clause is a capture:
5299 // v = x++;
5300 // v = x--;
5301 // v = ++x;
5302 // v = --x;
5303 // v = x binop= expr;
5304 // v = x = x binop expr;
5305 // v = x = expr binop x;
5306 auto *AtomicBinOp =
5307 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5308 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5309 V = AtomicBinOp->getLHS();
5310 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5311 OpenMPAtomicUpdateChecker Checker(*this);
5312 if (Checker.checkStatement(
5313 Body, diag::err_omp_atomic_capture_not_expression_statement,
5314 diag::note_omp_atomic_update))
5315 return StmtError();
5316 E = Checker.getExpr();
5317 X = Checker.getX();
5318 UE = Checker.getUpdateExpr();
5319 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5320 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005321 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005322 ErrorLoc = AtomicBody->getExprLoc();
5323 ErrorRange = AtomicBody->getSourceRange();
5324 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5325 : AtomicBody->getExprLoc();
5326 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5327 : AtomicBody->getSourceRange();
5328 ErrorFound = NotAnAssignmentOp;
5329 }
5330 if (ErrorFound != NoError) {
5331 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5332 << ErrorRange;
5333 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5334 return StmtError();
5335 } else if (CurContext->isDependentContext()) {
5336 UE = V = E = X = nullptr;
5337 }
5338 } else {
5339 // If clause is a capture:
5340 // { v = x; x = expr; }
5341 // { v = x; x++; }
5342 // { v = x; x--; }
5343 // { v = x; ++x; }
5344 // { v = x; --x; }
5345 // { v = x; x binop= expr; }
5346 // { v = x; x = x binop expr; }
5347 // { v = x; x = expr binop x; }
5348 // { x++; v = x; }
5349 // { x--; v = x; }
5350 // { ++x; v = x; }
5351 // { --x; v = x; }
5352 // { x binop= expr; v = x; }
5353 // { x = x binop expr; v = x; }
5354 // { x = expr binop x; v = x; }
5355 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5356 // Check that this is { expr1; expr2; }
5357 if (CS->size() == 2) {
5358 auto *First = CS->body_front();
5359 auto *Second = CS->body_back();
5360 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5361 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5362 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5363 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5364 // Need to find what subexpression is 'v' and what is 'x'.
5365 OpenMPAtomicUpdateChecker Checker(*this);
5366 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5367 BinaryOperator *BinOp = nullptr;
5368 if (IsUpdateExprFound) {
5369 BinOp = dyn_cast<BinaryOperator>(First);
5370 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5371 }
5372 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5373 // { v = x; x++; }
5374 // { v = x; x--; }
5375 // { v = x; ++x; }
5376 // { v = x; --x; }
5377 // { v = x; x binop= expr; }
5378 // { v = x; x = x binop expr; }
5379 // { v = x; x = expr binop x; }
5380 // Check that the first expression has form v = x.
5381 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5382 llvm::FoldingSetNodeID XId, PossibleXId;
5383 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5384 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5385 IsUpdateExprFound = XId == PossibleXId;
5386 if (IsUpdateExprFound) {
5387 V = BinOp->getLHS();
5388 X = Checker.getX();
5389 E = Checker.getExpr();
5390 UE = Checker.getUpdateExpr();
5391 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005392 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005393 }
5394 }
5395 if (!IsUpdateExprFound) {
5396 IsUpdateExprFound = !Checker.checkStatement(First);
5397 BinOp = nullptr;
5398 if (IsUpdateExprFound) {
5399 BinOp = dyn_cast<BinaryOperator>(Second);
5400 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5401 }
5402 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5403 // { x++; v = x; }
5404 // { x--; v = x; }
5405 // { ++x; v = x; }
5406 // { --x; v = x; }
5407 // { x binop= expr; v = x; }
5408 // { x = x binop expr; v = x; }
5409 // { x = expr binop x; v = x; }
5410 // Check that the second expression has form v = x.
5411 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5412 llvm::FoldingSetNodeID XId, PossibleXId;
5413 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5414 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5415 IsUpdateExprFound = XId == PossibleXId;
5416 if (IsUpdateExprFound) {
5417 V = BinOp->getLHS();
5418 X = Checker.getX();
5419 E = Checker.getExpr();
5420 UE = Checker.getUpdateExpr();
5421 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005422 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005423 }
5424 }
5425 }
5426 if (!IsUpdateExprFound) {
5427 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005428 auto *FirstExpr = dyn_cast<Expr>(First);
5429 auto *SecondExpr = dyn_cast<Expr>(Second);
5430 if (!FirstExpr || !SecondExpr ||
5431 !(FirstExpr->isInstantiationDependent() ||
5432 SecondExpr->isInstantiationDependent())) {
5433 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5434 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005435 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005436 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5437 : First->getLocStart();
5438 NoteRange = ErrorRange = FirstBinOp
5439 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005440 : SourceRange(ErrorLoc, ErrorLoc);
5441 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005442 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5443 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5444 ErrorFound = NotAnAssignmentOp;
5445 NoteLoc = ErrorLoc = SecondBinOp
5446 ? SecondBinOp->getOperatorLoc()
5447 : Second->getLocStart();
5448 NoteRange = ErrorRange =
5449 SecondBinOp ? SecondBinOp->getSourceRange()
5450 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005451 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005452 auto *PossibleXRHSInFirst =
5453 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5454 auto *PossibleXLHSInSecond =
5455 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5456 llvm::FoldingSetNodeID X1Id, X2Id;
5457 PossibleXRHSInFirst->Profile(X1Id, Context,
5458 /*Canonical=*/true);
5459 PossibleXLHSInSecond->Profile(X2Id, Context,
5460 /*Canonical=*/true);
5461 IsUpdateExprFound = X1Id == X2Id;
5462 if (IsUpdateExprFound) {
5463 V = FirstBinOp->getLHS();
5464 X = SecondBinOp->getLHS();
5465 E = SecondBinOp->getRHS();
5466 UE = nullptr;
5467 IsXLHSInRHSPart = false;
5468 IsPostfixUpdate = true;
5469 } else {
5470 ErrorFound = NotASpecificExpression;
5471 ErrorLoc = FirstBinOp->getExprLoc();
5472 ErrorRange = FirstBinOp->getSourceRange();
5473 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5474 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5475 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005476 }
5477 }
5478 }
5479 }
5480 } else {
5481 NoteLoc = ErrorLoc = Body->getLocStart();
5482 NoteRange = ErrorRange =
5483 SourceRange(Body->getLocStart(), Body->getLocStart());
5484 ErrorFound = NotTwoSubstatements;
5485 }
5486 } else {
5487 NoteLoc = ErrorLoc = Body->getLocStart();
5488 NoteRange = ErrorRange =
5489 SourceRange(Body->getLocStart(), Body->getLocStart());
5490 ErrorFound = NotACompoundStatement;
5491 }
5492 if (ErrorFound != NoError) {
5493 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5494 << ErrorRange;
5495 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5496 return StmtError();
5497 } else if (CurContext->isDependentContext()) {
5498 UE = V = E = X = nullptr;
5499 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005500 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005501 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005502
5503 getCurFunction()->setHasBranchProtectedScope();
5504
Alexey Bataev62cec442014-11-18 10:14:22 +00005505 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005506 X, V, E, UE, IsXLHSInRHSPart,
5507 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005508}
5509
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005510StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5511 Stmt *AStmt,
5512 SourceLocation StartLoc,
5513 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005514 if (!AStmt)
5515 return StmtError();
5516
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005517 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5518 // 1.2.2 OpenMP Language Terminology
5519 // Structured block - An executable statement with a single entry at the
5520 // top and a single exit at the bottom.
5521 // The point of exit cannot be a branch out of the structured block.
5522 // longjmp() and throw() must not violate the entry/exit criteria.
5523 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005524
Alexey Bataev13314bf2014-10-09 04:18:56 +00005525 // OpenMP [2.16, Nesting of Regions]
5526 // If specified, a teams construct must be contained within a target
5527 // construct. That target construct must contain no statements or directives
5528 // outside of the teams construct.
5529 if (DSAStack->hasInnerTeamsRegion()) {
5530 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5531 bool OMPTeamsFound = true;
5532 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5533 auto I = CS->body_begin();
5534 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005535 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005536 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5537 OMPTeamsFound = false;
5538 break;
5539 }
5540 ++I;
5541 }
5542 assert(I != CS->body_end() && "Not found statement");
5543 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005544 } else {
5545 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5546 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005547 }
5548 if (!OMPTeamsFound) {
5549 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5550 Diag(DSAStack->getInnerTeamsRegionLoc(),
5551 diag::note_omp_nested_teams_construct_here);
5552 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5553 << isa<OMPExecutableDirective>(S);
5554 return StmtError();
5555 }
5556 }
5557
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005558 getCurFunction()->setHasBranchProtectedScope();
5559
5560 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5561}
5562
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005563StmtResult
5564Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5565 Stmt *AStmt, SourceLocation StartLoc,
5566 SourceLocation EndLoc) {
5567 if (!AStmt)
5568 return StmtError();
5569
5570 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5571 // 1.2.2 OpenMP Language Terminology
5572 // Structured block - An executable statement with a single entry at the
5573 // top and a single exit at the bottom.
5574 // The point of exit cannot be a branch out of the structured block.
5575 // longjmp() and throw() must not violate the entry/exit criteria.
5576 CS->getCapturedDecl()->setNothrow();
5577
5578 getCurFunction()->setHasBranchProtectedScope();
5579
5580 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5581 AStmt);
5582}
5583
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005584StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5585 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5586 SourceLocation EndLoc,
5587 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5588 if (!AStmt)
5589 return StmtError();
5590
5591 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5592 // 1.2.2 OpenMP Language Terminology
5593 // Structured block - An executable statement with a single entry at the
5594 // top and a single exit at the bottom.
5595 // The point of exit cannot be a branch out of the structured block.
5596 // longjmp() and throw() must not violate the entry/exit criteria.
5597 CS->getCapturedDecl()->setNothrow();
5598
5599 OMPLoopDirective::HelperExprs B;
5600 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5601 // define the nested loops number.
5602 unsigned NestedLoopCount =
5603 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5604 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5605 VarsWithImplicitDSA, B);
5606 if (NestedLoopCount == 0)
5607 return StmtError();
5608
5609 assert((CurContext->isDependentContext() || B.builtAll()) &&
5610 "omp target parallel for loop exprs were not built");
5611
5612 if (!CurContext->isDependentContext()) {
5613 // Finalize the clauses that need pre-built expressions for CodeGen.
5614 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005615 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005616 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005617 B.NumIterations, *this, CurScope,
5618 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005619 return StmtError();
5620 }
5621 }
5622
5623 getCurFunction()->setHasBranchProtectedScope();
5624 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5625 NestedLoopCount, Clauses, AStmt,
5626 B, DSAStack->isCancelRegion());
5627}
5628
Samuel Antaodf67fc42016-01-19 19:15:56 +00005629/// \brief Check for existence of a map clause in the list of clauses.
5630static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5631 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5632 I != E; ++I) {
5633 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5634 return true;
5635 }
5636 }
5637
5638 return false;
5639}
5640
Michael Wong65f367f2015-07-21 13:44:28 +00005641StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5642 Stmt *AStmt,
5643 SourceLocation StartLoc,
5644 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005645 if (!AStmt)
5646 return StmtError();
5647
5648 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5649
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005650 // OpenMP [2.10.1, Restrictions, p. 97]
5651 // At least one map clause must appear on the directive.
5652 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005653 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5654 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005655 return StmtError();
5656 }
5657
Michael Wong65f367f2015-07-21 13:44:28 +00005658 getCurFunction()->setHasBranchProtectedScope();
5659
5660 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5661 AStmt);
5662}
5663
Samuel Antaodf67fc42016-01-19 19:15:56 +00005664StmtResult
5665Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5666 SourceLocation StartLoc,
5667 SourceLocation EndLoc) {
5668 // OpenMP [2.10.2, Restrictions, p. 99]
5669 // At least one map clause must appear on the directive.
5670 if (!HasMapClause(Clauses)) {
5671 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5672 << getOpenMPDirectiveName(OMPD_target_enter_data);
5673 return StmtError();
5674 }
5675
5676 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5677 Clauses);
5678}
5679
Samuel Antao72590762016-01-19 20:04:50 +00005680StmtResult
5681Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5682 SourceLocation StartLoc,
5683 SourceLocation EndLoc) {
5684 // OpenMP [2.10.3, Restrictions, p. 102]
5685 // At least one map clause must appear on the directive.
5686 if (!HasMapClause(Clauses)) {
5687 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5688 << getOpenMPDirectiveName(OMPD_target_exit_data);
5689 return StmtError();
5690 }
5691
5692 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5693}
5694
Samuel Antao686c70c2016-05-26 17:30:50 +00005695StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5696 SourceLocation StartLoc,
5697 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005698 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005699 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005700 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005701 seenMotionClause = true;
5702 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005703 if (!seenMotionClause) {
5704 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5705 return StmtError();
5706 }
5707 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5708}
5709
Alexey Bataev13314bf2014-10-09 04:18:56 +00005710StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5711 Stmt *AStmt, SourceLocation StartLoc,
5712 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005713 if (!AStmt)
5714 return StmtError();
5715
Alexey Bataev13314bf2014-10-09 04:18:56 +00005716 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5717 // 1.2.2 OpenMP Language Terminology
5718 // Structured block - An executable statement with a single entry at the
5719 // top and a single exit at the bottom.
5720 // The point of exit cannot be a branch out of the structured block.
5721 // longjmp() and throw() must not violate the entry/exit criteria.
5722 CS->getCapturedDecl()->setNothrow();
5723
5724 getCurFunction()->setHasBranchProtectedScope();
5725
5726 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5727}
5728
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005729StmtResult
5730Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5731 SourceLocation EndLoc,
5732 OpenMPDirectiveKind CancelRegion) {
5733 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5734 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5735 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5736 << getOpenMPDirectiveName(CancelRegion);
5737 return StmtError();
5738 }
5739 if (DSAStack->isParentNowaitRegion()) {
5740 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5741 return StmtError();
5742 }
5743 if (DSAStack->isParentOrderedRegion()) {
5744 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5745 return StmtError();
5746 }
5747 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5748 CancelRegion);
5749}
5750
Alexey Bataev87933c72015-09-18 08:07:34 +00005751StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5752 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005753 SourceLocation EndLoc,
5754 OpenMPDirectiveKind CancelRegion) {
5755 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5756 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5757 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5758 << getOpenMPDirectiveName(CancelRegion);
5759 return StmtError();
5760 }
5761 if (DSAStack->isParentNowaitRegion()) {
5762 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5763 return StmtError();
5764 }
5765 if (DSAStack->isParentOrderedRegion()) {
5766 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5767 return StmtError();
5768 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005769 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005770 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5771 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005772}
5773
Alexey Bataev382967a2015-12-08 12:06:20 +00005774static bool checkGrainsizeNumTasksClauses(Sema &S,
5775 ArrayRef<OMPClause *> Clauses) {
5776 OMPClause *PrevClause = nullptr;
5777 bool ErrorFound = false;
5778 for (auto *C : Clauses) {
5779 if (C->getClauseKind() == OMPC_grainsize ||
5780 C->getClauseKind() == OMPC_num_tasks) {
5781 if (!PrevClause)
5782 PrevClause = C;
5783 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5784 S.Diag(C->getLocStart(),
5785 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5786 << getOpenMPClauseName(C->getClauseKind())
5787 << getOpenMPClauseName(PrevClause->getClauseKind());
5788 S.Diag(PrevClause->getLocStart(),
5789 diag::note_omp_previous_grainsize_num_tasks)
5790 << getOpenMPClauseName(PrevClause->getClauseKind());
5791 ErrorFound = true;
5792 }
5793 }
5794 }
5795 return ErrorFound;
5796}
5797
Alexey Bataev49f6e782015-12-01 04:18:41 +00005798StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5799 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5800 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005801 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005802 if (!AStmt)
5803 return StmtError();
5804
5805 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5806 OMPLoopDirective::HelperExprs B;
5807 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5808 // define the nested loops number.
5809 unsigned NestedLoopCount =
5810 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005811 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005812 VarsWithImplicitDSA, B);
5813 if (NestedLoopCount == 0)
5814 return StmtError();
5815
5816 assert((CurContext->isDependentContext() || B.builtAll()) &&
5817 "omp for loop exprs were not built");
5818
Alexey Bataev382967a2015-12-08 12:06:20 +00005819 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5820 // The grainsize clause and num_tasks clause are mutually exclusive and may
5821 // not appear on the same taskloop directive.
5822 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5823 return StmtError();
5824
Alexey Bataev49f6e782015-12-01 04:18:41 +00005825 getCurFunction()->setHasBranchProtectedScope();
5826 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5827 NestedLoopCount, Clauses, AStmt, B);
5828}
5829
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005830StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5831 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5832 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005833 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005834 if (!AStmt)
5835 return StmtError();
5836
5837 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5838 OMPLoopDirective::HelperExprs B;
5839 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5840 // define the nested loops number.
5841 unsigned NestedLoopCount =
5842 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5843 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5844 VarsWithImplicitDSA, B);
5845 if (NestedLoopCount == 0)
5846 return StmtError();
5847
5848 assert((CurContext->isDependentContext() || B.builtAll()) &&
5849 "omp for loop exprs were not built");
5850
Alexey Bataev5a3af132016-03-29 08:58:54 +00005851 if (!CurContext->isDependentContext()) {
5852 // Finalize the clauses that need pre-built expressions for CodeGen.
5853 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005854 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005855 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005856 B.NumIterations, *this, CurScope,
5857 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005858 return StmtError();
5859 }
5860 }
5861
Alexey Bataev382967a2015-12-08 12:06:20 +00005862 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5863 // The grainsize clause and num_tasks clause are mutually exclusive and may
5864 // not appear on the same taskloop directive.
5865 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5866 return StmtError();
5867
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005868 getCurFunction()->setHasBranchProtectedScope();
5869 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5870 NestedLoopCount, Clauses, AStmt, B);
5871}
5872
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005873StmtResult Sema::ActOnOpenMPDistributeDirective(
5874 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5875 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005876 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005877 if (!AStmt)
5878 return StmtError();
5879
5880 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5881 OMPLoopDirective::HelperExprs B;
5882 // In presence of clause 'collapse' with number of loops, it will
5883 // define the nested loops number.
5884 unsigned NestedLoopCount =
5885 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5886 nullptr /*ordered not a clause on distribute*/, AStmt,
5887 *this, *DSAStack, VarsWithImplicitDSA, B);
5888 if (NestedLoopCount == 0)
5889 return StmtError();
5890
5891 assert((CurContext->isDependentContext() || B.builtAll()) &&
5892 "omp for loop exprs were not built");
5893
5894 getCurFunction()->setHasBranchProtectedScope();
5895 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5896 NestedLoopCount, Clauses, AStmt, B);
5897}
5898
Carlo Bertolli9925f152016-06-27 14:55:37 +00005899StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5900 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5901 SourceLocation EndLoc,
5902 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5903 if (!AStmt)
5904 return StmtError();
5905
5906 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5907 // 1.2.2 OpenMP Language Terminology
5908 // Structured block - An executable statement with a single entry at the
5909 // top and a single exit at the bottom.
5910 // The point of exit cannot be a branch out of the structured block.
5911 // longjmp() and throw() must not violate the entry/exit criteria.
5912 CS->getCapturedDecl()->setNothrow();
5913
5914 OMPLoopDirective::HelperExprs B;
5915 // In presence of clause 'collapse' with number of loops, it will
5916 // define the nested loops number.
5917 unsigned NestedLoopCount = CheckOpenMPLoop(
5918 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5919 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5920 VarsWithImplicitDSA, B);
5921 if (NestedLoopCount == 0)
5922 return StmtError();
5923
5924 assert((CurContext->isDependentContext() || B.builtAll()) &&
5925 "omp for loop exprs were not built");
5926
5927 getCurFunction()->setHasBranchProtectedScope();
5928 return OMPDistributeParallelForDirective::Create(
5929 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5930}
5931
Kelvin Li4a39add2016-07-05 05:00:15 +00005932StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5933 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5934 SourceLocation EndLoc,
5935 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5936 if (!AStmt)
5937 return StmtError();
5938
5939 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5940 // 1.2.2 OpenMP Language Terminology
5941 // Structured block - An executable statement with a single entry at the
5942 // top and a single exit at the bottom.
5943 // The point of exit cannot be a branch out of the structured block.
5944 // longjmp() and throw() must not violate the entry/exit criteria.
5945 CS->getCapturedDecl()->setNothrow();
5946
5947 OMPLoopDirective::HelperExprs B;
5948 // In presence of clause 'collapse' with number of loops, it will
5949 // define the nested loops number.
5950 unsigned NestedLoopCount = CheckOpenMPLoop(
5951 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5952 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5953 VarsWithImplicitDSA, B);
5954 if (NestedLoopCount == 0)
5955 return StmtError();
5956
5957 assert((CurContext->isDependentContext() || B.builtAll()) &&
5958 "omp for loop exprs were not built");
5959
Kelvin Lic5609492016-07-15 04:39:07 +00005960 if (checkSimdlenSafelenSpecified(*this, Clauses))
5961 return StmtError();
5962
Kelvin Li4a39add2016-07-05 05:00:15 +00005963 getCurFunction()->setHasBranchProtectedScope();
5964 return OMPDistributeParallelForSimdDirective::Create(
5965 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5966}
5967
Kelvin Li787f3fc2016-07-06 04:45:38 +00005968StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5969 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5970 SourceLocation EndLoc,
5971 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5972 if (!AStmt)
5973 return StmtError();
5974
5975 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5976 // 1.2.2 OpenMP Language Terminology
5977 // Structured block - An executable statement with a single entry at the
5978 // top and a single exit at the bottom.
5979 // The point of exit cannot be a branch out of the structured block.
5980 // longjmp() and throw() must not violate the entry/exit criteria.
5981 CS->getCapturedDecl()->setNothrow();
5982
5983 OMPLoopDirective::HelperExprs B;
5984 // In presence of clause 'collapse' with number of loops, it will
5985 // define the nested loops number.
5986 unsigned NestedLoopCount =
5987 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5988 nullptr /*ordered not a clause on distribute*/, AStmt,
5989 *this, *DSAStack, VarsWithImplicitDSA, B);
5990 if (NestedLoopCount == 0)
5991 return StmtError();
5992
5993 assert((CurContext->isDependentContext() || B.builtAll()) &&
5994 "omp for loop exprs were not built");
5995
Kelvin Lic5609492016-07-15 04:39:07 +00005996 if (checkSimdlenSafelenSpecified(*this, Clauses))
5997 return StmtError();
5998
Kelvin Li787f3fc2016-07-06 04:45:38 +00005999 getCurFunction()->setHasBranchProtectedScope();
6000 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6001 NestedLoopCount, Clauses, AStmt, B);
6002}
6003
Kelvin Lia579b912016-07-14 02:54:56 +00006004StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6005 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6006 SourceLocation EndLoc,
6007 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6008 if (!AStmt)
6009 return StmtError();
6010
6011 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6012 // 1.2.2 OpenMP Language Terminology
6013 // Structured block - An executable statement with a single entry at the
6014 // top and a single exit at the bottom.
6015 // The point of exit cannot be a branch out of the structured block.
6016 // longjmp() and throw() must not violate the entry/exit criteria.
6017 CS->getCapturedDecl()->setNothrow();
6018
6019 OMPLoopDirective::HelperExprs B;
6020 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6021 // define the nested loops number.
6022 unsigned NestedLoopCount = CheckOpenMPLoop(
6023 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6024 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6025 VarsWithImplicitDSA, B);
6026 if (NestedLoopCount == 0)
6027 return StmtError();
6028
6029 assert((CurContext->isDependentContext() || B.builtAll()) &&
6030 "omp target parallel for simd loop exprs were not built");
6031
6032 if (!CurContext->isDependentContext()) {
6033 // Finalize the clauses that need pre-built expressions for CodeGen.
6034 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006035 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006036 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6037 B.NumIterations, *this, CurScope,
6038 DSAStack))
6039 return StmtError();
6040 }
6041 }
Kelvin Lic5609492016-07-15 04:39:07 +00006042 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006043 return StmtError();
6044
6045 getCurFunction()->setHasBranchProtectedScope();
6046 return OMPTargetParallelForSimdDirective::Create(
6047 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6048}
6049
Kelvin Li986330c2016-07-20 22:57:10 +00006050StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6051 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6052 SourceLocation EndLoc,
6053 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6054 if (!AStmt)
6055 return StmtError();
6056
6057 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6058 // 1.2.2 OpenMP Language Terminology
6059 // Structured block - An executable statement with a single entry at the
6060 // top and a single exit at the bottom.
6061 // The point of exit cannot be a branch out of the structured block.
6062 // longjmp() and throw() must not violate the entry/exit criteria.
6063 CS->getCapturedDecl()->setNothrow();
6064
6065 OMPLoopDirective::HelperExprs B;
6066 // In presence of clause 'collapse' with number of loops, it will define the
6067 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006068 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006069 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6070 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6071 VarsWithImplicitDSA, B);
6072 if (NestedLoopCount == 0)
6073 return StmtError();
6074
6075 assert((CurContext->isDependentContext() || B.builtAll()) &&
6076 "omp target simd loop exprs were not built");
6077
6078 if (!CurContext->isDependentContext()) {
6079 // Finalize the clauses that need pre-built expressions for CodeGen.
6080 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006081 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006082 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6083 B.NumIterations, *this, CurScope,
6084 DSAStack))
6085 return StmtError();
6086 }
6087 }
6088
6089 if (checkSimdlenSafelenSpecified(*this, Clauses))
6090 return StmtError();
6091
6092 getCurFunction()->setHasBranchProtectedScope();
6093 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6094 NestedLoopCount, Clauses, AStmt, B);
6095}
6096
Kelvin Li02532872016-08-05 14:37:37 +00006097StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6098 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6099 SourceLocation EndLoc,
6100 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6101 if (!AStmt)
6102 return StmtError();
6103
6104 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6105 // 1.2.2 OpenMP Language Terminology
6106 // Structured block - An executable statement with a single entry at the
6107 // top and a single exit at the bottom.
6108 // The point of exit cannot be a branch out of the structured block.
6109 // longjmp() and throw() must not violate the entry/exit criteria.
6110 CS->getCapturedDecl()->setNothrow();
6111
6112 OMPLoopDirective::HelperExprs B;
6113 // In presence of clause 'collapse' with number of loops, it will
6114 // define the nested loops number.
6115 unsigned NestedLoopCount =
6116 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6117 nullptr /*ordered not a clause on distribute*/, AStmt,
6118 *this, *DSAStack, VarsWithImplicitDSA, B);
6119 if (NestedLoopCount == 0)
6120 return StmtError();
6121
6122 assert((CurContext->isDependentContext() || B.builtAll()) &&
6123 "omp teams distribute loop exprs were not built");
6124
6125 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006126 return OMPTeamsDistributeDirective::Create(
6127 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006128}
6129
Kelvin Li4e325f72016-10-25 12:50:55 +00006130StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6131 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6132 SourceLocation EndLoc,
6133 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6134 if (!AStmt)
6135 return StmtError();
6136
6137 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6138 // 1.2.2 OpenMP Language Terminology
6139 // Structured block - An executable statement with a single entry at the
6140 // top and a single exit at the bottom.
6141 // The point of exit cannot be a branch out of the structured block.
6142 // longjmp() and throw() must not violate the entry/exit criteria.
6143 CS->getCapturedDecl()->setNothrow();
6144
6145 OMPLoopDirective::HelperExprs B;
6146 // In presence of clause 'collapse' with number of loops, it will
6147 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006148 unsigned NestedLoopCount = CheckOpenMPLoop(
6149 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6150 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6151 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006152
6153 if (NestedLoopCount == 0)
6154 return StmtError();
6155
6156 assert((CurContext->isDependentContext() || B.builtAll()) &&
6157 "omp teams distribute simd loop exprs were not built");
6158
6159 if (!CurContext->isDependentContext()) {
6160 // Finalize the clauses that need pre-built expressions for CodeGen.
6161 for (auto C : Clauses) {
6162 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6163 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6164 B.NumIterations, *this, CurScope,
6165 DSAStack))
6166 return StmtError();
6167 }
6168 }
6169
6170 if (checkSimdlenSafelenSpecified(*this, Clauses))
6171 return StmtError();
6172
6173 getCurFunction()->setHasBranchProtectedScope();
6174 return OMPTeamsDistributeSimdDirective::Create(
6175 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6176}
6177
Kelvin Li579e41c2016-11-30 23:51:03 +00006178StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6179 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6180 SourceLocation EndLoc,
6181 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6182 if (!AStmt)
6183 return StmtError();
6184
6185 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6186 // 1.2.2 OpenMP Language Terminology
6187 // Structured block - An executable statement with a single entry at the
6188 // top and a single exit at the bottom.
6189 // The point of exit cannot be a branch out of the structured block.
6190 // longjmp() and throw() must not violate the entry/exit criteria.
6191 CS->getCapturedDecl()->setNothrow();
6192
6193 OMPLoopDirective::HelperExprs B;
6194 // In presence of clause 'collapse' with number of loops, it will
6195 // define the nested loops number.
6196 auto NestedLoopCount = CheckOpenMPLoop(
6197 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6198 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6199 VarsWithImplicitDSA, B);
6200
6201 if (NestedLoopCount == 0)
6202 return StmtError();
6203
6204 assert((CurContext->isDependentContext() || B.builtAll()) &&
6205 "omp for loop exprs were not built");
6206
6207 if (!CurContext->isDependentContext()) {
6208 // Finalize the clauses that need pre-built expressions for CodeGen.
6209 for (auto C : Clauses) {
6210 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6211 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6212 B.NumIterations, *this, CurScope,
6213 DSAStack))
6214 return StmtError();
6215 }
6216 }
6217
6218 if (checkSimdlenSafelenSpecified(*this, Clauses))
6219 return StmtError();
6220
6221 getCurFunction()->setHasBranchProtectedScope();
6222 return OMPTeamsDistributeParallelForSimdDirective::Create(
6223 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6224}
6225
Kelvin Li7ade93f2016-12-09 03:24:30 +00006226StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6227 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6228 SourceLocation EndLoc,
6229 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6230 if (!AStmt)
6231 return StmtError();
6232
6233 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6234 // 1.2.2 OpenMP Language Terminology
6235 // Structured block - An executable statement with a single entry at the
6236 // top and a single exit at the bottom.
6237 // The point of exit cannot be a branch out of the structured block.
6238 // longjmp() and throw() must not violate the entry/exit criteria.
6239 CS->getCapturedDecl()->setNothrow();
6240
6241 OMPLoopDirective::HelperExprs B;
6242 // In presence of clause 'collapse' with number of loops, it will
6243 // define the nested loops number.
6244 unsigned NestedLoopCount = CheckOpenMPLoop(
6245 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6246 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6247 VarsWithImplicitDSA, B);
6248
6249 if (NestedLoopCount == 0)
6250 return StmtError();
6251
6252 assert((CurContext->isDependentContext() || B.builtAll()) &&
6253 "omp for loop exprs were not built");
6254
6255 if (!CurContext->isDependentContext()) {
6256 // Finalize the clauses that need pre-built expressions for CodeGen.
6257 for (auto C : Clauses) {
6258 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6259 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6260 B.NumIterations, *this, CurScope,
6261 DSAStack))
6262 return StmtError();
6263 }
6264 }
6265
6266 getCurFunction()->setHasBranchProtectedScope();
6267 return OMPTeamsDistributeParallelForDirective::Create(
6268 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6269}
6270
Kelvin Libf594a52016-12-17 05:48:59 +00006271StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6272 Stmt *AStmt,
6273 SourceLocation StartLoc,
6274 SourceLocation EndLoc) {
6275 if (!AStmt)
6276 return StmtError();
6277
6278 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6279 // 1.2.2 OpenMP Language Terminology
6280 // Structured block - An executable statement with a single entry at the
6281 // top and a single exit at the bottom.
6282 // The point of exit cannot be a branch out of the structured block.
6283 // longjmp() and throw() must not violate the entry/exit criteria.
6284 CS->getCapturedDecl()->setNothrow();
6285
6286 getCurFunction()->setHasBranchProtectedScope();
6287
6288 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6289 AStmt);
6290}
6291
Kelvin Li83c451e2016-12-25 04:52:54 +00006292StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6293 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6294 SourceLocation EndLoc,
6295 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6296 if (!AStmt)
6297 return StmtError();
6298
6299 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6300 // 1.2.2 OpenMP Language Terminology
6301 // Structured block - An executable statement with a single entry at the
6302 // top and a single exit at the bottom.
6303 // The point of exit cannot be a branch out of the structured block.
6304 // longjmp() and throw() must not violate the entry/exit criteria.
6305 CS->getCapturedDecl()->setNothrow();
6306
6307 OMPLoopDirective::HelperExprs B;
6308 // In presence of clause 'collapse' with number of loops, it will
6309 // define the nested loops number.
6310 auto NestedLoopCount = CheckOpenMPLoop(
6311 OMPD_target_teams_distribute,
6312 getCollapseNumberExpr(Clauses),
6313 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6314 VarsWithImplicitDSA, B);
6315 if (NestedLoopCount == 0)
6316 return StmtError();
6317
6318 assert((CurContext->isDependentContext() || B.builtAll()) &&
6319 "omp target teams distribute loop exprs were not built");
6320
6321 getCurFunction()->setHasBranchProtectedScope();
6322 return OMPTargetTeamsDistributeDirective::Create(
6323 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6324}
6325
Alexey Bataeved09d242014-05-28 05:53:51 +00006326OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006327 SourceLocation StartLoc,
6328 SourceLocation LParenLoc,
6329 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006330 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006331 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006332 case OMPC_final:
6333 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6334 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006335 case OMPC_num_threads:
6336 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6337 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006338 case OMPC_safelen:
6339 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6340 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006341 case OMPC_simdlen:
6342 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6343 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006344 case OMPC_collapse:
6345 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6346 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006347 case OMPC_ordered:
6348 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6349 break;
Michael Wonge710d542015-08-07 16:16:36 +00006350 case OMPC_device:
6351 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6352 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006353 case OMPC_num_teams:
6354 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6355 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006356 case OMPC_thread_limit:
6357 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6358 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006359 case OMPC_priority:
6360 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6361 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006362 case OMPC_grainsize:
6363 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6364 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006365 case OMPC_num_tasks:
6366 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6367 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006368 case OMPC_hint:
6369 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6370 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006371 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006372 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006373 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006374 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006375 case OMPC_private:
6376 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006377 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006378 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006379 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006380 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006381 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006382 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006383 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006384 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006385 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006386 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006387 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006388 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006389 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006390 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006391 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006392 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006393 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006394 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006395 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006396 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006397 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006398 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006399 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006400 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006401 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006402 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006403 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006404 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006405 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006406 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006407 llvm_unreachable("Clause is not allowed.");
6408 }
6409 return Res;
6410}
6411
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006412OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6413 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006414 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006415 SourceLocation NameModifierLoc,
6416 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006417 SourceLocation EndLoc) {
6418 Expr *ValExpr = Condition;
6419 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6420 !Condition->isInstantiationDependent() &&
6421 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006422 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006423 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006424 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006425
Richard Smith03a4aa32016-06-23 19:02:52 +00006426 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006427 }
6428
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006429 return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6430 NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006431}
6432
Alexey Bataev3778b602014-07-17 07:32:53 +00006433OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6434 SourceLocation StartLoc,
6435 SourceLocation LParenLoc,
6436 SourceLocation EndLoc) {
6437 Expr *ValExpr = Condition;
6438 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6439 !Condition->isInstantiationDependent() &&
6440 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006441 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006442 if (Val.isInvalid())
6443 return nullptr;
6444
Richard Smith03a4aa32016-06-23 19:02:52 +00006445 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006446 }
6447
6448 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6449}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006450ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6451 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006452 if (!Op)
6453 return ExprError();
6454
6455 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6456 public:
6457 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006458 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006459 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6460 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006461 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6462 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006463 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6464 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006465 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6466 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006467 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6468 QualType T,
6469 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006470 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6471 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006472 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6473 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006474 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006475 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006476 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006477 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6478 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006479 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6480 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006481 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6482 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006483 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006484 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006485 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006486 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6487 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006488 llvm_unreachable("conversion functions are permitted");
6489 }
6490 } ConvertDiagnoser;
6491 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6492}
6493
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006494static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006495 OpenMPClauseKind CKind,
6496 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006497 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6498 !ValExpr->isInstantiationDependent()) {
6499 SourceLocation Loc = ValExpr->getExprLoc();
6500 ExprResult Value =
6501 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6502 if (Value.isInvalid())
6503 return false;
6504
6505 ValExpr = Value.get();
6506 // The expression must evaluate to a non-negative integer value.
6507 llvm::APSInt Result;
6508 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006509 Result.isSigned() &&
6510 !((!StrictlyPositive && Result.isNonNegative()) ||
6511 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006512 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006513 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6514 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006515 return false;
6516 }
6517 }
6518 return true;
6519}
6520
Alexey Bataev568a8332014-03-06 06:15:19 +00006521OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6522 SourceLocation StartLoc,
6523 SourceLocation LParenLoc,
6524 SourceLocation EndLoc) {
6525 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006526
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006527 // OpenMP [2.5, Restrictions]
6528 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006529 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6530 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006531 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006532
Alexey Bataeved09d242014-05-28 05:53:51 +00006533 return new (Context)
6534 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006535}
6536
Alexey Bataev62c87d22014-03-21 04:51:18 +00006537ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006538 OpenMPClauseKind CKind,
6539 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006540 if (!E)
6541 return ExprError();
6542 if (E->isValueDependent() || E->isTypeDependent() ||
6543 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006544 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006545 llvm::APSInt Result;
6546 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6547 if (ICE.isInvalid())
6548 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006549 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6550 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006551 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006552 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6553 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006554 return ExprError();
6555 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006556 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6557 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6558 << E->getSourceRange();
6559 return ExprError();
6560 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006561 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6562 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006563 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006564 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006565 return ICE;
6566}
6567
6568OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6569 SourceLocation LParenLoc,
6570 SourceLocation EndLoc) {
6571 // OpenMP [2.8.1, simd construct, Description]
6572 // The parameter of the safelen clause must be a constant
6573 // positive integer expression.
6574 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6575 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006576 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006577 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006578 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006579}
6580
Alexey Bataev66b15b52015-08-21 11:14:16 +00006581OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6582 SourceLocation LParenLoc,
6583 SourceLocation EndLoc) {
6584 // OpenMP [2.8.1, simd construct, Description]
6585 // The parameter of the simdlen clause must be a constant
6586 // positive integer expression.
6587 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6588 if (Simdlen.isInvalid())
6589 return nullptr;
6590 return new (Context)
6591 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6592}
6593
Alexander Musman64d33f12014-06-04 07:53:32 +00006594OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6595 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006596 SourceLocation LParenLoc,
6597 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006598 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006599 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006600 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006601 // The parameter of the collapse clause must be a constant
6602 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006603 ExprResult NumForLoopsResult =
6604 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6605 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006606 return nullptr;
6607 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006608 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006609}
6610
Alexey Bataev10e775f2015-07-30 11:36:16 +00006611OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6612 SourceLocation EndLoc,
6613 SourceLocation LParenLoc,
6614 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006615 // OpenMP [2.7.1, loop construct, Description]
6616 // OpenMP [2.8.1, simd construct, Description]
6617 // OpenMP [2.9.6, distribute construct, Description]
6618 // The parameter of the ordered clause must be a constant
6619 // positive integer expression if any.
6620 if (NumForLoops && LParenLoc.isValid()) {
6621 ExprResult NumForLoopsResult =
6622 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6623 if (NumForLoopsResult.isInvalid())
6624 return nullptr;
6625 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006626 } else
6627 NumForLoops = nullptr;
6628 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006629 return new (Context)
6630 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6631}
6632
Alexey Bataeved09d242014-05-28 05:53:51 +00006633OMPClause *Sema::ActOnOpenMPSimpleClause(
6634 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6635 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006636 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006637 switch (Kind) {
6638 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006639 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00006640 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6641 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006642 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006643 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00006644 Res = ActOnOpenMPProcBindClause(
6645 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6646 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006647 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006648 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00006649 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00006650 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00006651 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006652 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00006653 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006654 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006655 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00006656 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006657 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006658 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006659 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006660 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006661 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006662 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006663 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006664 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006665 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006666 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006667 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006668 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006669 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006670 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006671 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006672 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006673 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006674 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006675 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006676 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006677 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006678 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006679 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006680 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006681 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006682 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006683 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006684 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006685 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006686 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006687 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006688 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006689 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006690 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006691 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006692 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006693 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006694 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006695 llvm_unreachable("Clause is not allowed.");
6696 }
6697 return Res;
6698}
6699
Alexey Bataev6402bca2015-12-28 07:25:51 +00006700static std::string
6701getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6702 ArrayRef<unsigned> Exclude = llvm::None) {
6703 std::string Values;
6704 unsigned Bound = Last >= 2 ? Last - 2 : 0;
6705 unsigned Skipped = Exclude.size();
6706 auto S = Exclude.begin(), E = Exclude.end();
6707 for (unsigned i = First; i < Last; ++i) {
6708 if (std::find(S, E, i) != E) {
6709 --Skipped;
6710 continue;
6711 }
6712 Values += "'";
6713 Values += getOpenMPSimpleClauseTypeName(K, i);
6714 Values += "'";
6715 if (i == Bound - Skipped)
6716 Values += " or ";
6717 else if (i != Bound + 1 - Skipped)
6718 Values += ", ";
6719 }
6720 return Values;
6721}
6722
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006723OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6724 SourceLocation KindKwLoc,
6725 SourceLocation StartLoc,
6726 SourceLocation LParenLoc,
6727 SourceLocation EndLoc) {
6728 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00006729 static_assert(OMPC_DEFAULT_unknown > 0,
6730 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006731 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006732 << getListOfPossibleValues(OMPC_default, /*First=*/0,
6733 /*Last=*/OMPC_DEFAULT_unknown)
6734 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006735 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006736 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00006737 switch (Kind) {
6738 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006739 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006740 break;
6741 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006742 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00006743 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006744 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006745 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00006746 break;
6747 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006748 return new (Context)
6749 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006750}
6751
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006752OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6753 SourceLocation KindKwLoc,
6754 SourceLocation StartLoc,
6755 SourceLocation LParenLoc,
6756 SourceLocation EndLoc) {
6757 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006758 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00006759 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6760 /*Last=*/OMPC_PROC_BIND_unknown)
6761 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006762 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006763 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006764 return new (Context)
6765 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006766}
6767
Alexey Bataev56dafe82014-06-20 07:16:17 +00006768OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006769 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006770 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006771 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006772 SourceLocation EndLoc) {
6773 OMPClause *Res = nullptr;
6774 switch (Kind) {
6775 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006776 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6777 assert(Argument.size() == NumberOfElements &&
6778 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006779 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006780 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6781 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6782 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6783 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6784 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006785 break;
6786 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00006787 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6788 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6789 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6790 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006791 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00006792 case OMPC_dist_schedule:
6793 Res = ActOnOpenMPDistScheduleClause(
6794 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6795 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6796 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006797 case OMPC_defaultmap:
6798 enum { Modifier, DefaultmapKind };
6799 Res = ActOnOpenMPDefaultmapClause(
6800 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6801 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00006802 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6803 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006804 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00006805 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006806 case OMPC_num_threads:
6807 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00006808 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006809 case OMPC_collapse:
6810 case OMPC_default:
6811 case OMPC_proc_bind:
6812 case OMPC_private:
6813 case OMPC_firstprivate:
6814 case OMPC_lastprivate:
6815 case OMPC_shared:
6816 case OMPC_reduction:
6817 case OMPC_linear:
6818 case OMPC_aligned:
6819 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006820 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006821 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00006822 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006823 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006824 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006825 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006826 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006827 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006828 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006829 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006830 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006831 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006832 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00006833 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00006834 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006835 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006836 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00006837 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006838 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00006839 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006840 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00006841 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00006842 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00006843 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006844 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006845 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006846 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006847 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006848 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006849 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006850 llvm_unreachable("Clause is not allowed.");
6851 }
6852 return Res;
6853}
6854
Alexey Bataev6402bca2015-12-28 07:25:51 +00006855static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6856 OpenMPScheduleClauseModifier M2,
6857 SourceLocation M1Loc, SourceLocation M2Loc) {
6858 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6859 SmallVector<unsigned, 2> Excluded;
6860 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6861 Excluded.push_back(M2);
6862 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6863 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6864 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6865 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6866 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6867 << getListOfPossibleValues(OMPC_schedule,
6868 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6869 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6870 Excluded)
6871 << getOpenMPClauseName(OMPC_schedule);
6872 return true;
6873 }
6874 return false;
6875}
6876
Alexey Bataev56dafe82014-06-20 07:16:17 +00006877OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00006878 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00006879 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00006880 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6881 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6882 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6883 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6884 return nullptr;
6885 // OpenMP, 2.7.1, Loop Construct, Restrictions
6886 // Either the monotonic modifier or the nonmonotonic modifier can be specified
6887 // but not both.
6888 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6889 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6890 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6891 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6892 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6893 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6894 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6895 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6896 return nullptr;
6897 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006898 if (Kind == OMPC_SCHEDULE_unknown) {
6899 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00006900 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6901 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6902 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6903 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6904 Exclude);
6905 } else {
6906 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6907 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006908 }
6909 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6910 << Values << getOpenMPClauseName(OMPC_schedule);
6911 return nullptr;
6912 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00006913 // OpenMP, 2.7.1, Loop Construct, Restrictions
6914 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6915 // schedule(guided).
6916 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6917 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6918 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6919 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6920 diag::err_omp_schedule_nonmonotonic_static);
6921 return nullptr;
6922 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00006923 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00006924 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00006925 if (ChunkSize) {
6926 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6927 !ChunkSize->isInstantiationDependent() &&
6928 !ChunkSize->containsUnexpandedParameterPack()) {
6929 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6930 ExprResult Val =
6931 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6932 if (Val.isInvalid())
6933 return nullptr;
6934
6935 ValExpr = Val.get();
6936
6937 // OpenMP [2.7.1, Restrictions]
6938 // chunk_size must be a loop invariant integer expression with a positive
6939 // value.
6940 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00006941 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6942 if (Result.isSigned() && !Result.isStrictlyPositive()) {
6943 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006944 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00006945 return nullptr;
6946 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00006947 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
6948 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006949 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6950 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6951 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006952 }
6953 }
6954 }
6955
Alexey Bataev6402bca2015-12-28 07:25:51 +00006956 return new (Context)
6957 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00006958 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00006959}
6960
Alexey Bataev142e1fc2014-06-20 09:44:06 +00006961OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6962 SourceLocation StartLoc,
6963 SourceLocation EndLoc) {
6964 OMPClause *Res = nullptr;
6965 switch (Kind) {
6966 case OMPC_ordered:
6967 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6968 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00006969 case OMPC_nowait:
6970 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6971 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006972 case OMPC_untied:
6973 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6974 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006975 case OMPC_mergeable:
6976 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6977 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006978 case OMPC_read:
6979 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6980 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00006981 case OMPC_write:
6982 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6983 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006984 case OMPC_update:
6985 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6986 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00006987 case OMPC_capture:
6988 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6989 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006990 case OMPC_seq_cst:
6991 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6992 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00006993 case OMPC_threads:
6994 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6995 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006996 case OMPC_simd:
6997 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6998 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00006999 case OMPC_nogroup:
7000 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7001 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007002 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007003 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007004 case OMPC_num_threads:
7005 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007006 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007007 case OMPC_collapse:
7008 case OMPC_schedule:
7009 case OMPC_private:
7010 case OMPC_firstprivate:
7011 case OMPC_lastprivate:
7012 case OMPC_shared:
7013 case OMPC_reduction:
7014 case OMPC_linear:
7015 case OMPC_aligned:
7016 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007017 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007018 case OMPC_default:
7019 case OMPC_proc_bind:
7020 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007021 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007022 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007023 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007024 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007025 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007026 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007027 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007028 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007029 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007030 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007031 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007032 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007033 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007034 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007035 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007036 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007037 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007038 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007039 llvm_unreachable("Clause is not allowed.");
7040 }
7041 return Res;
7042}
7043
Alexey Bataev236070f2014-06-20 11:19:47 +00007044OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7045 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007046 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007047 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7048}
7049
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007050OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7051 SourceLocation EndLoc) {
7052 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7053}
7054
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007055OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7056 SourceLocation EndLoc) {
7057 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7058}
7059
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007060OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7061 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007062 return new (Context) OMPReadClause(StartLoc, EndLoc);
7063}
7064
Alexey Bataevdea47612014-07-23 07:46:59 +00007065OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7066 SourceLocation EndLoc) {
7067 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7068}
7069
Alexey Bataev67a4f222014-07-23 10:25:33 +00007070OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7071 SourceLocation EndLoc) {
7072 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7073}
7074
Alexey Bataev459dec02014-07-24 06:46:57 +00007075OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7076 SourceLocation EndLoc) {
7077 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7078}
7079
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007080OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7081 SourceLocation EndLoc) {
7082 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7083}
7084
Alexey Bataev346265e2015-09-25 10:37:12 +00007085OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7086 SourceLocation EndLoc) {
7087 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7088}
7089
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007090OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7091 SourceLocation EndLoc) {
7092 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7093}
7094
Alexey Bataevb825de12015-12-07 10:51:44 +00007095OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7096 SourceLocation EndLoc) {
7097 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7098}
7099
Alexey Bataevc5e02582014-06-16 07:08:35 +00007100OMPClause *Sema::ActOnOpenMPVarListClause(
7101 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7102 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7103 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007104 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007105 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7106 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7107 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007108 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007109 switch (Kind) {
7110 case OMPC_private:
7111 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7112 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007113 case OMPC_firstprivate:
7114 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7115 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007116 case OMPC_lastprivate:
7117 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7118 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007119 case OMPC_shared:
7120 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7121 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007122 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007123 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7124 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007125 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007126 case OMPC_linear:
7127 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007128 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007129 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007130 case OMPC_aligned:
7131 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7132 ColonLoc, EndLoc);
7133 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007134 case OMPC_copyin:
7135 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7136 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007137 case OMPC_copyprivate:
7138 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7139 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007140 case OMPC_flush:
7141 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7142 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007143 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007144 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007145 StartLoc, LParenLoc, EndLoc);
7146 break;
7147 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007148 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7149 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7150 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007151 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007152 case OMPC_to:
7153 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7154 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007155 case OMPC_from:
7156 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7157 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007158 case OMPC_use_device_ptr:
7159 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7160 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007161 case OMPC_is_device_ptr:
7162 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7163 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007164 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007165 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007166 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007167 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007168 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007169 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007170 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007171 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007172 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007173 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007174 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007175 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007176 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007177 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007178 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007179 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007180 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007181 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007182 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007183 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007184 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007185 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007186 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007187 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007188 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007189 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007190 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007191 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007192 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007193 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007194 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007195 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007196 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007197 llvm_unreachable("Clause is not allowed.");
7198 }
7199 return Res;
7200}
7201
Alexey Bataev90c228f2016-02-08 09:29:13 +00007202ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007203 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007204 ExprResult Res = BuildDeclRefExpr(
7205 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7206 if (!Res.isUsable())
7207 return ExprError();
7208 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7209 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7210 if (!Res.isUsable())
7211 return ExprError();
7212 }
7213 if (VK != VK_LValue && Res.get()->isGLValue()) {
7214 Res = DefaultLvalueConversion(Res.get());
7215 if (!Res.isUsable())
7216 return ExprError();
7217 }
7218 return Res;
7219}
7220
Alexey Bataev60da77e2016-02-29 05:54:20 +00007221static std::pair<ValueDecl *, bool>
7222getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7223 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007224 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7225 RefExpr->containsUnexpandedParameterPack())
7226 return std::make_pair(nullptr, true);
7227
Alexey Bataevd985eda2016-02-10 11:29:16 +00007228 // OpenMP [3.1, C/C++]
7229 // A list item is a variable name.
7230 // OpenMP [2.9.3.3, Restrictions, p.1]
7231 // A variable that is part of another variable (as an array or
7232 // structure element) cannot appear in a private clause.
7233 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007234 enum {
7235 NoArrayExpr = -1,
7236 ArraySubscript = 0,
7237 OMPArraySection = 1
7238 } IsArrayExpr = NoArrayExpr;
7239 if (AllowArraySection) {
7240 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7241 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7242 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7243 Base = TempASE->getBase()->IgnoreParenImpCasts();
7244 RefExpr = Base;
7245 IsArrayExpr = ArraySubscript;
7246 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7247 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7248 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7249 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7250 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7251 Base = TempASE->getBase()->IgnoreParenImpCasts();
7252 RefExpr = Base;
7253 IsArrayExpr = OMPArraySection;
7254 }
7255 }
7256 ELoc = RefExpr->getExprLoc();
7257 ERange = RefExpr->getSourceRange();
7258 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007259 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7260 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7261 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7262 (S.getCurrentThisType().isNull() || !ME ||
7263 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7264 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007265 if (IsArrayExpr != NoArrayExpr)
7266 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7267 << ERange;
7268 else {
7269 S.Diag(ELoc,
7270 AllowArraySection
7271 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7272 : diag::err_omp_expected_var_name_member_expr)
7273 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7274 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007275 return std::make_pair(nullptr, false);
7276 }
7277 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7278}
7279
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007280OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7281 SourceLocation StartLoc,
7282 SourceLocation LParenLoc,
7283 SourceLocation EndLoc) {
7284 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007285 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007286 for (auto &RefExpr : VarList) {
7287 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007288 SourceLocation ELoc;
7289 SourceRange ERange;
7290 Expr *SimpleRefExpr = RefExpr;
7291 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007292 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007293 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007294 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007295 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007296 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007297 ValueDecl *D = Res.first;
7298 if (!D)
7299 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007300
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007301 QualType Type = D->getType();
7302 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007303
7304 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7305 // A variable that appears in a private clause must not have an incomplete
7306 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007307 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007308 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007309 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007310
Alexey Bataev758e55e2013-09-06 18:03:48 +00007311 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7312 // in a Construct]
7313 // Variables with the predetermined data-sharing attributes may not be
7314 // listed in data-sharing attributes clauses, except for the cases
7315 // listed below. For these exceptions only, listing a predetermined
7316 // variable in a data-sharing attribute clause is allowed and overrides
7317 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007318 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007319 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007320 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7321 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007322 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007323 continue;
7324 }
7325
Kelvin Libf594a52016-12-17 05:48:59 +00007326 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007327 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007328 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007329 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007330 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7331 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007332 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007333 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007334 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007335 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007336 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007337 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007338 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007339 continue;
7340 }
7341
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007342 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7343 // A list item cannot appear in both a map clause and a data-sharing
7344 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007345 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Li83c451e2016-12-25 04:52:54 +00007346 CurrDir == OMPD_target_teams ||
7347 CurrDir == OMPD_target_teams_distribute) {
Samuel Antao6890b092016-07-28 14:25:09 +00007348 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007349 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007350 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007351 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7352 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7353 ConflictKind = WhereFoundClauseKind;
7354 return true;
7355 })) {
7356 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007357 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007358 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007359 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007360 ReportOriginalDSA(*this, DSAStack, D, DVar);
7361 continue;
7362 }
7363 }
7364
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007365 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7366 // A variable of class type (or array thereof) that appears in a private
7367 // clause requires an accessible, unambiguous default constructor for the
7368 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007369 // Generate helper private variable and initialize it with the default
7370 // value. The address of the original variable is replaced by the address of
7371 // the new private variable in CodeGen. This new variable is not added to
7372 // IdResolver, so the code in the OpenMP region uses original variable for
7373 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007374 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007375 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7376 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007377 ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007378 if (VDPrivate->isInvalidDecl())
7379 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007380 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007381 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007382
Alexey Bataev90c228f2016-02-08 09:29:13 +00007383 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007384 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007385 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007386 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007387 Vars.push_back((VD || CurContext->isDependentContext())
7388 ? RefExpr->IgnoreParens()
7389 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007390 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007391 }
7392
Alexey Bataeved09d242014-05-28 05:53:51 +00007393 if (Vars.empty())
7394 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007395
Alexey Bataev03b340a2014-10-21 03:16:40 +00007396 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7397 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007398}
7399
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007400namespace {
7401class DiagsUninitializedSeveretyRAII {
7402private:
7403 DiagnosticsEngine &Diags;
7404 SourceLocation SavedLoc;
7405 bool IsIgnored;
7406
7407public:
7408 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7409 bool IsIgnored)
7410 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7411 if (!IsIgnored) {
7412 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7413 /*Map*/ diag::Severity::Ignored, Loc);
7414 }
7415 }
7416 ~DiagsUninitializedSeveretyRAII() {
7417 if (!IsIgnored)
7418 Diags.popMappings(SavedLoc);
7419 }
7420};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007421}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007422
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007423OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7424 SourceLocation StartLoc,
7425 SourceLocation LParenLoc,
7426 SourceLocation EndLoc) {
7427 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007428 SmallVector<Expr *, 8> PrivateCopies;
7429 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007430 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007431 bool IsImplicitClause =
7432 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7433 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7434
Alexey Bataeved09d242014-05-28 05:53:51 +00007435 for (auto &RefExpr : VarList) {
7436 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007437 SourceLocation ELoc;
7438 SourceRange ERange;
7439 Expr *SimpleRefExpr = RefExpr;
7440 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007441 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007442 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007443 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007444 PrivateCopies.push_back(nullptr);
7445 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007446 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007447 ValueDecl *D = Res.first;
7448 if (!D)
7449 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007450
Alexey Bataev60da77e2016-02-29 05:54:20 +00007451 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007452 QualType Type = D->getType();
7453 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007454
7455 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7456 // A variable that appears in a private clause must not have an incomplete
7457 // type or a reference type.
7458 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007459 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007460 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007461 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007462
7463 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7464 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007465 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007466 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007467 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007468
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007469 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007470 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007471 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007472 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007473 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007474 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007475 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7476 // A list item that specifies a given variable may not appear in more
7477 // than one clause on the same directive, except that a variable may be
7478 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007479 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007480 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007481 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007482 << getOpenMPClauseName(DVar.CKind)
7483 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007484 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007485 continue;
7486 }
7487
7488 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7489 // in a Construct]
7490 // Variables with the predetermined data-sharing attributes may not be
7491 // listed in data-sharing attributes clauses, except for the cases
7492 // listed below. For these exceptions only, listing a predetermined
7493 // variable in a data-sharing attribute clause is allowed and overrides
7494 // the variable's predetermined data-sharing attributes.
7495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7496 // in a Construct, C/C++, p.2]
7497 // Variables with const-qualified type having no mutable member may be
7498 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007499 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007500 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7501 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007502 << getOpenMPClauseName(DVar.CKind)
7503 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007504 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007505 continue;
7506 }
7507
Alexey Bataevf29276e2014-06-18 04:14:57 +00007508 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007509 // OpenMP [2.9.3.4, Restrictions, p.2]
7510 // A list item that is private within a parallel region must not appear
7511 // in a firstprivate clause on a worksharing construct if any of the
7512 // worksharing regions arising from the worksharing construct ever bind
7513 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007514 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007515 !isOpenMPParallelDirective(CurrDir) &&
7516 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007517 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007518 if (DVar.CKind != OMPC_shared &&
7519 (isOpenMPParallelDirective(DVar.DKind) ||
7520 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007521 Diag(ELoc, diag::err_omp_required_access)
7522 << getOpenMPClauseName(OMPC_firstprivate)
7523 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007524 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007525 continue;
7526 }
7527 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007528 // OpenMP [2.9.3.4, Restrictions, p.3]
7529 // A list item that appears in a reduction clause of a parallel construct
7530 // must not appear in a firstprivate clause on a worksharing or task
7531 // construct if any of the worksharing or task regions arising from the
7532 // worksharing or task construct ever bind to any of the parallel regions
7533 // arising from the parallel construct.
7534 // OpenMP [2.9.3.4, Restrictions, p.4]
7535 // A list item that appears in a reduction clause in worksharing
7536 // construct must not appear in a firstprivate clause in a task construct
7537 // encountered during execution of any of the worksharing regions arising
7538 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007539 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007540 DVar = DSAStack->hasInnermostDSA(
7541 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7542 [](OpenMPDirectiveKind K) -> bool {
7543 return isOpenMPParallelDirective(K) ||
7544 isOpenMPWorksharingDirective(K);
7545 },
7546 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007547 if (DVar.CKind == OMPC_reduction &&
7548 (isOpenMPParallelDirective(DVar.DKind) ||
7549 isOpenMPWorksharingDirective(DVar.DKind))) {
7550 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7551 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007552 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007553 continue;
7554 }
7555 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007556
7557 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7558 // A list item that is private within a teams region must not appear in a
7559 // firstprivate clause on a distribute construct if any of the distribute
7560 // regions arising from the distribute construct ever bind to any of the
7561 // teams regions arising from the teams construct.
7562 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7563 // A list item that appears in a reduction clause of a teams construct
7564 // must not appear in a firstprivate clause on a distribute construct if
7565 // any of the distribute regions arising from the distribute construct
7566 // ever bind to any of the teams regions arising from the teams construct.
7567 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7568 // A list item may appear in a firstprivate or lastprivate clause but not
7569 // both.
7570 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007571 DVar = DSAStack->hasInnermostDSA(
7572 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7573 [](OpenMPDirectiveKind K) -> bool {
7574 return isOpenMPTeamsDirective(K);
7575 },
7576 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007577 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7578 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007579 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007580 continue;
7581 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007582 DVar = DSAStack->hasInnermostDSA(
7583 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7584 [](OpenMPDirectiveKind K) -> bool {
7585 return isOpenMPTeamsDirective(K);
7586 },
7587 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007588 if (DVar.CKind == OMPC_reduction &&
7589 isOpenMPTeamsDirective(DVar.DKind)) {
7590 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007591 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007592 continue;
7593 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007594 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007595 if (DVar.CKind == OMPC_lastprivate) {
7596 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007597 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007598 continue;
7599 }
7600 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007601 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7602 // A list item cannot appear in both a map clause and a data-sharing
7603 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007604 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Li83c451e2016-12-25 04:52:54 +00007605 CurrDir == OMPD_target_teams ||
7606 CurrDir == OMPD_target_teams_distribute) {
Samuel Antao6890b092016-07-28 14:25:09 +00007607 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007608 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007609 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007610 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7611 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7612 ConflictKind = WhereFoundClauseKind;
7613 return true;
7614 })) {
7615 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007616 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007617 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007618 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7619 ReportOriginalDSA(*this, DSAStack, D, DVar);
7620 continue;
7621 }
7622 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007623 }
7624
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007625 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007626 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007627 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007628 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7629 << getOpenMPClauseName(OMPC_firstprivate) << Type
7630 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7631 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007632 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007633 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007634 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007635 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00007636 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007637 continue;
7638 }
7639
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007640 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007641 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7642 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007643 // Generate helper private variable and initialize it with the value of the
7644 // original variable. The address of the original variable is replaced by
7645 // the address of the new private variable in the CodeGen. This new variable
7646 // is not added to IdResolver, so the code in the OpenMP region uses
7647 // original variable for proper diagnostics and variable capturing.
7648 Expr *VDInitRefExpr = nullptr;
7649 // For arrays generate initializer for single element and replace it by the
7650 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007651 if (Type->isArrayType()) {
7652 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00007653 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007654 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007655 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007656 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007657 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007658 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00007659 InitializedEntity Entity =
7660 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007661 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7662
7663 InitializationSequence InitSeq(*this, Entity, Kind, Init);
7664 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7665 if (Result.isInvalid())
7666 VDPrivate->setInvalidDecl();
7667 else
7668 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00007669 // Remove temp variable declaration.
7670 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007671 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007672 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7673 ".firstprivate.temp");
7674 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7675 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00007676 AddInitializerToDecl(VDPrivate,
7677 DefaultLvalueConversion(VDInitRefExpr).get(),
7678 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007679 }
7680 if (VDPrivate->isInvalidDecl()) {
7681 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007682 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007683 diag::note_omp_task_predetermined_firstprivate_here);
7684 }
7685 continue;
7686 }
7687 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007688 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00007689 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7690 RefExpr->getExprLoc());
7691 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007692 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007693 if (TopDVar.CKind == OMPC_lastprivate)
7694 Ref = TopDVar.PrivateCopy;
7695 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007696 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00007697 if (!IsOpenMPCapturedDecl(D))
7698 ExprCaptures.push_back(Ref->getDecl());
7699 }
Alexey Bataev417089f2016-02-17 13:19:37 +00007700 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007701 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007702 Vars.push_back((VD || CurContext->isDependentContext())
7703 ? RefExpr->IgnoreParens()
7704 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007705 PrivateCopies.push_back(VDPrivateRefExpr);
7706 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007707 }
7708
Alexey Bataeved09d242014-05-28 05:53:51 +00007709 if (Vars.empty())
7710 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007711
7712 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007713 Vars, PrivateCopies, Inits,
7714 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007715}
7716
Alexander Musman1bb328c2014-06-04 13:06:39 +00007717OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7718 SourceLocation StartLoc,
7719 SourceLocation LParenLoc,
7720 SourceLocation EndLoc) {
7721 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00007722 SmallVector<Expr *, 8> SrcExprs;
7723 SmallVector<Expr *, 8> DstExprs;
7724 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00007725 SmallVector<Decl *, 4> ExprCaptures;
7726 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007727 for (auto &RefExpr : VarList) {
7728 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007729 SourceLocation ELoc;
7730 SourceRange ERange;
7731 Expr *SimpleRefExpr = RefExpr;
7732 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007733 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00007734 // It will be analyzed later.
7735 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00007736 SrcExprs.push_back(nullptr);
7737 DstExprs.push_back(nullptr);
7738 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007739 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007740 ValueDecl *D = Res.first;
7741 if (!D)
7742 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007743
Alexey Bataev74caaf22016-02-20 04:09:36 +00007744 QualType Type = D->getType();
7745 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007746
7747 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7748 // A variable that appears in a lastprivate clause must not have an
7749 // incomplete type or a reference type.
7750 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00007751 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00007752 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007753 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00007754
7755 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7756 // in a Construct]
7757 // Variables with the predetermined data-sharing attributes may not be
7758 // listed in data-sharing attributes clauses, except for the cases
7759 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007760 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007761 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7762 DVar.CKind != OMPC_firstprivate &&
7763 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7764 Diag(ELoc, diag::err_omp_wrong_dsa)
7765 << getOpenMPClauseName(DVar.CKind)
7766 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007767 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00007768 continue;
7769 }
7770
Alexey Bataevf29276e2014-06-18 04:14:57 +00007771 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7772 // OpenMP [2.14.3.5, Restrictions, p.2]
7773 // A list item that is private within a parallel region, or that appears in
7774 // the reduction clause of a parallel construct, must not appear in a
7775 // lastprivate clause on a worksharing construct if any of the corresponding
7776 // worksharing regions ever binds to any of the corresponding parallel
7777 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007778 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00007779 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007780 !isOpenMPParallelDirective(CurrDir) &&
7781 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00007782 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007783 if (DVar.CKind != OMPC_shared) {
7784 Diag(ELoc, diag::err_omp_required_access)
7785 << getOpenMPClauseName(OMPC_lastprivate)
7786 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00007787 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007788 continue;
7789 }
7790 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00007791
7792 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7793 // A list item may appear in a firstprivate or lastprivate clause but not
7794 // both.
7795 if (CurrDir == OMPD_distribute) {
7796 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7797 if (DVar.CKind == OMPC_firstprivate) {
7798 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7799 ReportOriginalDSA(*this, DSAStack, D, DVar);
7800 continue;
7801 }
7802 }
7803
Alexander Musman1bb328c2014-06-04 13:06:39 +00007804 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00007805 // A variable of class type (or array thereof) that appears in a
7806 // lastprivate clause requires an accessible, unambiguous default
7807 // constructor for the class type, unless the list item is also specified
7808 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00007809 // A variable of class type (or array thereof) that appears in a
7810 // lastprivate clause requires an accessible, unambiguous copy assignment
7811 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00007812 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007813 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00007814 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007815 D->hasAttrs() ? &D->getAttrs() : nullptr);
7816 auto *PseudoSrcExpr =
7817 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007818 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007819 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00007820 D->hasAttrs() ? &D->getAttrs() : nullptr);
7821 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00007822 // For arrays generate assignment operation for single element and replace
7823 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00007824 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00007825 PseudoDstExpr, PseudoSrcExpr);
7826 if (AssignmentOp.isInvalid())
7827 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00007828 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00007829 /*DiscardedValue=*/true);
7830 if (AssignmentOp.isInvalid())
7831 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007832
Alexey Bataev74caaf22016-02-20 04:09:36 +00007833 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007834 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007835 if (TopDVar.CKind == OMPC_firstprivate)
7836 Ref = TopDVar.PrivateCopy;
7837 else {
Alexey Bataev61205072016-03-02 04:57:40 +00007838 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007839 if (!IsOpenMPCapturedDecl(D))
7840 ExprCaptures.push_back(Ref->getDecl());
7841 }
7842 if (TopDVar.CKind == OMPC_firstprivate ||
7843 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00007844 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00007845 ExprResult RefRes = DefaultLvalueConversion(Ref);
7846 if (!RefRes.isUsable())
7847 continue;
7848 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00007849 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7850 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007851 if (!PostUpdateRes.isUsable())
7852 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00007853 ExprPostUpdates.push_back(
7854 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00007855 }
7856 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007857 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007858 Vars.push_back((VD || CurContext->isDependentContext())
7859 ? RefExpr->IgnoreParens()
7860 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00007861 SrcExprs.push_back(PseudoSrcExpr);
7862 DstExprs.push_back(PseudoDstExpr);
7863 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00007864 }
7865
7866 if (Vars.empty())
7867 return nullptr;
7868
7869 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00007870 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00007871 buildPreInits(Context, ExprCaptures),
7872 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00007873}
7874
Alexey Bataev758e55e2013-09-06 18:03:48 +00007875OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7876 SourceLocation StartLoc,
7877 SourceLocation LParenLoc,
7878 SourceLocation EndLoc) {
7879 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00007880 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007881 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007882 SourceLocation ELoc;
7883 SourceRange ERange;
7884 Expr *SimpleRefExpr = RefExpr;
7885 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007886 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00007887 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007888 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007889 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007890 ValueDecl *D = Res.first;
7891 if (!D)
7892 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007893
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007894 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007895 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7896 // in a Construct]
7897 // Variables with the predetermined data-sharing attributes may not be
7898 // listed in data-sharing attributes clauses, except for the cases
7899 // listed below. For these exceptions only, listing a predetermined
7900 // variable in a data-sharing attribute clause is allowed and overrides
7901 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007902 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00007903 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7904 DVar.RefExpr) {
7905 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7906 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007907 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007908 continue;
7909 }
7910
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007911 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007912 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007913 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00007914 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007915 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7916 ? RefExpr->IgnoreParens()
7917 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007918 }
7919
Alexey Bataeved09d242014-05-28 05:53:51 +00007920 if (Vars.empty())
7921 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007922
7923 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7924}
7925
Alexey Bataevc5e02582014-06-16 07:08:35 +00007926namespace {
7927class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7928 DSAStackTy *Stack;
7929
7930public:
7931 bool VisitDeclRefExpr(DeclRefExpr *E) {
7932 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007933 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007934 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7935 return false;
7936 if (DVar.CKind != OMPC_unknown)
7937 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007938 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7939 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7940 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007941 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00007942 return true;
7943 return false;
7944 }
7945 return false;
7946 }
7947 bool VisitStmt(Stmt *S) {
7948 for (auto Child : S->children()) {
7949 if (Child && Visit(Child))
7950 return true;
7951 }
7952 return false;
7953 }
Alexey Bataev23b69422014-06-18 07:08:49 +00007954 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00007955};
Alexey Bataev23b69422014-06-18 07:08:49 +00007956} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00007957
Alexey Bataev60da77e2016-02-29 05:54:20 +00007958namespace {
7959// Transform MemberExpression for specified FieldDecl of current class to
7960// DeclRefExpr to specified OMPCapturedExprDecl.
7961class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
7962 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
7963 ValueDecl *Field;
7964 DeclRefExpr *CapturedExpr;
7965
7966public:
7967 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
7968 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
7969
7970 ExprResult TransformMemberExpr(MemberExpr *E) {
7971 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
7972 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00007973 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00007974 return CapturedExpr;
7975 }
7976 return BaseTransform::TransformMemberExpr(E);
7977 }
7978 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
7979};
7980} // namespace
7981
Alexey Bataeva839ddd2016-03-17 10:19:46 +00007982template <typename T>
7983static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
7984 const llvm::function_ref<T(ValueDecl *)> &Gen) {
7985 for (auto &Set : Lookups) {
7986 for (auto *D : Set) {
7987 if (auto Res = Gen(cast<ValueDecl>(D)))
7988 return Res;
7989 }
7990 }
7991 return T();
7992}
7993
7994static ExprResult
7995buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
7996 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
7997 const DeclarationNameInfo &ReductionId, QualType Ty,
7998 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
7999 if (ReductionIdScopeSpec.isInvalid())
8000 return ExprError();
8001 SmallVector<UnresolvedSet<8>, 4> Lookups;
8002 if (S) {
8003 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8004 Lookup.suppressDiagnostics();
8005 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8006 auto *D = Lookup.getRepresentativeDecl();
8007 do {
8008 S = S->getParent();
8009 } while (S && !S->isDeclScope(D));
8010 if (S)
8011 S = S->getParent();
8012 Lookups.push_back(UnresolvedSet<8>());
8013 Lookups.back().append(Lookup.begin(), Lookup.end());
8014 Lookup.clear();
8015 }
8016 } else if (auto *ULE =
8017 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8018 Lookups.push_back(UnresolvedSet<8>());
8019 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008020 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008021 if (D == PrevD)
8022 Lookups.push_back(UnresolvedSet<8>());
8023 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8024 Lookups.back().addDecl(DRD);
8025 PrevD = D;
8026 }
8027 }
8028 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8029 Ty->containsUnexpandedParameterPack() ||
8030 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8031 return !D->isInvalidDecl() &&
8032 (D->getType()->isDependentType() ||
8033 D->getType()->isInstantiationDependentType() ||
8034 D->getType()->containsUnexpandedParameterPack());
8035 })) {
8036 UnresolvedSet<8> ResSet;
8037 for (auto &Set : Lookups) {
8038 ResSet.append(Set.begin(), Set.end());
8039 // The last item marks the end of all declarations at the specified scope.
8040 ResSet.addDecl(Set[Set.size() - 1]);
8041 }
8042 return UnresolvedLookupExpr::Create(
8043 SemaRef.Context, /*NamingClass=*/nullptr,
8044 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8045 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8046 }
8047 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8048 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8049 if (!D->isInvalidDecl() &&
8050 SemaRef.Context.hasSameType(D->getType(), Ty))
8051 return D;
8052 return nullptr;
8053 }))
8054 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8055 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8056 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8057 if (!D->isInvalidDecl() &&
8058 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8059 !Ty.isMoreQualifiedThan(D->getType()))
8060 return D;
8061 return nullptr;
8062 })) {
8063 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8064 /*DetectVirtual=*/false);
8065 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8066 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8067 VD->getType().getUnqualifiedType()))) {
8068 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8069 /*DiagID=*/0) !=
8070 Sema::AR_inaccessible) {
8071 SemaRef.BuildBasePathArray(Paths, BasePath);
8072 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8073 }
8074 }
8075 }
8076 }
8077 if (ReductionIdScopeSpec.isSet()) {
8078 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8079 return ExprError();
8080 }
8081 return ExprEmpty();
8082}
8083
Alexey Bataevc5e02582014-06-16 07:08:35 +00008084OMPClause *Sema::ActOnOpenMPReductionClause(
8085 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8086 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008087 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8088 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008089 auto DN = ReductionId.getName();
8090 auto OOK = DN.getCXXOverloadedOperator();
8091 BinaryOperatorKind BOK = BO_Comma;
8092
8093 // OpenMP [2.14.3.6, reduction clause]
8094 // C
8095 // reduction-identifier is either an identifier or one of the following
8096 // operators: +, -, *, &, |, ^, && and ||
8097 // C++
8098 // reduction-identifier is either an id-expression or one of the following
8099 // operators: +, -, *, &, |, ^, && and ||
8100 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8101 switch (OOK) {
8102 case OO_Plus:
8103 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008104 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008105 break;
8106 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008107 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008108 break;
8109 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008110 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008111 break;
8112 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008113 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008114 break;
8115 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008116 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008117 break;
8118 case OO_AmpAmp:
8119 BOK = BO_LAnd;
8120 break;
8121 case OO_PipePipe:
8122 BOK = BO_LOr;
8123 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008124 case OO_New:
8125 case OO_Delete:
8126 case OO_Array_New:
8127 case OO_Array_Delete:
8128 case OO_Slash:
8129 case OO_Percent:
8130 case OO_Tilde:
8131 case OO_Exclaim:
8132 case OO_Equal:
8133 case OO_Less:
8134 case OO_Greater:
8135 case OO_LessEqual:
8136 case OO_GreaterEqual:
8137 case OO_PlusEqual:
8138 case OO_MinusEqual:
8139 case OO_StarEqual:
8140 case OO_SlashEqual:
8141 case OO_PercentEqual:
8142 case OO_CaretEqual:
8143 case OO_AmpEqual:
8144 case OO_PipeEqual:
8145 case OO_LessLess:
8146 case OO_GreaterGreater:
8147 case OO_LessLessEqual:
8148 case OO_GreaterGreaterEqual:
8149 case OO_EqualEqual:
8150 case OO_ExclaimEqual:
8151 case OO_PlusPlus:
8152 case OO_MinusMinus:
8153 case OO_Comma:
8154 case OO_ArrowStar:
8155 case OO_Arrow:
8156 case OO_Call:
8157 case OO_Subscript:
8158 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008159 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008160 case NUM_OVERLOADED_OPERATORS:
8161 llvm_unreachable("Unexpected reduction identifier");
8162 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008163 if (auto II = DN.getAsIdentifierInfo()) {
8164 if (II->isStr("max"))
8165 BOK = BO_GT;
8166 else if (II->isStr("min"))
8167 BOK = BO_LT;
8168 }
8169 break;
8170 }
8171 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008172 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008173 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008174 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008175
8176 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008177 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008178 SmallVector<Expr *, 8> LHSs;
8179 SmallVector<Expr *, 8> RHSs;
8180 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008181 SmallVector<Decl *, 4> ExprCaptures;
8182 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008183 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8184 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008185 for (auto RefExpr : VarList) {
8186 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008187 // OpenMP [2.1, C/C++]
8188 // A list item is a variable or array section, subject to the restrictions
8189 // specified in Section 2.4 on page 42 and in each of the sections
8190 // describing clauses and directives for which a list appears.
8191 // OpenMP [2.14.3.3, Restrictions, p.1]
8192 // A variable that is part of another variable (as an array or
8193 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008194 if (!FirstIter && IR != ER)
8195 ++IR;
8196 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008197 SourceLocation ELoc;
8198 SourceRange ERange;
8199 Expr *SimpleRefExpr = RefExpr;
8200 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8201 /*AllowArraySection=*/true);
8202 if (Res.second) {
8203 // It will be analyzed later.
8204 Vars.push_back(RefExpr);
8205 Privates.push_back(nullptr);
8206 LHSs.push_back(nullptr);
8207 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008208 // Try to find 'declare reduction' corresponding construct before using
8209 // builtin/overloaded operators.
8210 QualType Type = Context.DependentTy;
8211 CXXCastPath BasePath;
8212 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8213 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8214 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8215 if (CurContext->isDependentContext() &&
8216 (DeclareReductionRef.isUnset() ||
8217 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8218 ReductionOps.push_back(DeclareReductionRef.get());
8219 else
8220 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008221 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008222 ValueDecl *D = Res.first;
8223 if (!D)
8224 continue;
8225
Alexey Bataeva1764212015-09-30 09:22:36 +00008226 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008227 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8228 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8229 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008230 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008231 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008232 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8233 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8234 Type = ATy->getElementType();
8235 else
8236 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008237 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008238 } else
8239 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8240 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008241
Alexey Bataevc5e02582014-06-16 07:08:35 +00008242 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8243 // A variable that appears in a private clause must not have an incomplete
8244 // type or a reference type.
8245 if (RequireCompleteType(ELoc, Type,
8246 diag::err_omp_reduction_incomplete_type))
8247 continue;
8248 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008249 // A list item that appears in a reduction clause must not be
8250 // const-qualified.
8251 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008252 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008253 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008254 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008255 bool IsDecl = !VD ||
8256 VD->isThisDeclarationADefinition(Context) ==
8257 VarDecl::DeclarationOnly;
8258 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008259 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008260 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008261 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008262 continue;
8263 }
8264 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8265 // If a list-item is a reference type then it must bind to the same object
8266 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008267 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008268 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008269 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008270 DSARefChecker Check(DSAStack);
8271 if (Check.Visit(VDDef->getInit())) {
8272 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8273 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8274 continue;
8275 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008276 }
8277 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008278
Alexey Bataevc5e02582014-06-16 07:08:35 +00008279 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8280 // in a Construct]
8281 // Variables with the predetermined data-sharing attributes may not be
8282 // listed in data-sharing attributes clauses, except for the cases
8283 // listed below. For these exceptions only, listing a predetermined
8284 // variable in a data-sharing attribute clause is allowed and overrides
8285 // the variable's predetermined data-sharing attributes.
8286 // OpenMP [2.14.3.6, Restrictions, p.3]
8287 // Any number of reduction clauses can be specified on the directive,
8288 // but a list item can appear only once in the reduction clauses for that
8289 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008290 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008291 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008292 if (DVar.CKind == OMPC_reduction) {
8293 Diag(ELoc, diag::err_omp_once_referenced)
8294 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008295 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008296 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008297 } else if (DVar.CKind != OMPC_unknown) {
8298 Diag(ELoc, diag::err_omp_wrong_dsa)
8299 << getOpenMPClauseName(DVar.CKind)
8300 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008301 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008302 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008303 }
8304
8305 // OpenMP [2.14.3.6, Restrictions, p.1]
8306 // A list item that appears in a reduction clause of a worksharing
8307 // construct must be shared in the parallel regions to which any of the
8308 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008309 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8310 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008311 !isOpenMPParallelDirective(CurrDir) &&
8312 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008313 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008314 if (DVar.CKind != OMPC_shared) {
8315 Diag(ELoc, diag::err_omp_required_access)
8316 << getOpenMPClauseName(OMPC_reduction)
8317 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008318 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008319 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008320 }
8321 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008322
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008323 // Try to find 'declare reduction' corresponding construct before using
8324 // builtin/overloaded operators.
8325 CXXCastPath BasePath;
8326 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8327 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8328 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8329 if (DeclareReductionRef.isInvalid())
8330 continue;
8331 if (CurContext->isDependentContext() &&
8332 (DeclareReductionRef.isUnset() ||
8333 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8334 Vars.push_back(RefExpr);
8335 Privates.push_back(nullptr);
8336 LHSs.push_back(nullptr);
8337 RHSs.push_back(nullptr);
8338 ReductionOps.push_back(DeclareReductionRef.get());
8339 continue;
8340 }
8341 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8342 // Not allowed reduction identifier is found.
8343 Diag(ReductionId.getLocStart(),
8344 diag::err_omp_unknown_reduction_identifier)
8345 << Type << ReductionIdRange;
8346 continue;
8347 }
8348
8349 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8350 // The type of a list item that appears in a reduction clause must be valid
8351 // for the reduction-identifier. For a max or min reduction in C, the type
8352 // of the list item must be an allowed arithmetic data type: char, int,
8353 // float, double, or _Bool, possibly modified with long, short, signed, or
8354 // unsigned. For a max or min reduction in C++, the type of the list item
8355 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8356 // double, or bool, possibly modified with long, short, signed, or unsigned.
8357 if (DeclareReductionRef.isUnset()) {
8358 if ((BOK == BO_GT || BOK == BO_LT) &&
8359 !(Type->isScalarType() ||
8360 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8361 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8362 << getLangOpts().CPlusPlus;
8363 if (!ASE && !OASE) {
8364 bool IsDecl = !VD ||
8365 VD->isThisDeclarationADefinition(Context) ==
8366 VarDecl::DeclarationOnly;
8367 Diag(D->getLocation(),
8368 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8369 << D;
8370 }
8371 continue;
8372 }
8373 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8374 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8375 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8376 if (!ASE && !OASE) {
8377 bool IsDecl = !VD ||
8378 VD->isThisDeclarationADefinition(Context) ==
8379 VarDecl::DeclarationOnly;
8380 Diag(D->getLocation(),
8381 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8382 << D;
8383 }
8384 continue;
8385 }
8386 }
8387
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008388 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008389 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008390 D->hasAttrs() ? &D->getAttrs() : nullptr);
8391 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8392 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008393 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008394 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008395 (!ASE &&
8396 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008397 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008398 // Create pseudo array type for private copy. The size for this array will
8399 // be generated during codegen.
8400 // For array subscripts or single variables Private Ty is the same as Type
8401 // (type of the variable or single array element).
8402 PrivateTy = Context.getVariableArrayType(
8403 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8404 Context.getSizeType(), VK_RValue),
8405 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008406 } else if (!ASE && !OASE &&
8407 Context.getAsArrayType(D->getType().getNonReferenceType()))
8408 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008409 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008410 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8411 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008412 // Add initializer for private variable.
8413 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008414 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8415 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8416 if (DeclareReductionRef.isUsable()) {
8417 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8418 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8419 if (DRD->getInitializer()) {
8420 Init = DRDRef;
8421 RHSVD->setInit(DRDRef);
8422 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008423 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008424 } else {
8425 switch (BOK) {
8426 case BO_Add:
8427 case BO_Xor:
8428 case BO_Or:
8429 case BO_LOr:
8430 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8431 if (Type->isScalarType() || Type->isAnyComplexType())
8432 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8433 break;
8434 case BO_Mul:
8435 case BO_LAnd:
8436 if (Type->isScalarType() || Type->isAnyComplexType()) {
8437 // '*' and '&&' reduction ops - initializer is '1'.
8438 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008439 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008440 break;
8441 case BO_And: {
8442 // '&' reduction op - initializer is '~0'.
8443 QualType OrigType = Type;
8444 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8445 Type = ComplexTy->getElementType();
8446 if (Type->isRealFloatingType()) {
8447 llvm::APFloat InitValue =
8448 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8449 /*isIEEE=*/true);
8450 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8451 Type, ELoc);
8452 } else if (Type->isScalarType()) {
8453 auto Size = Context.getTypeSize(Type);
8454 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8455 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8456 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8457 }
8458 if (Init && OrigType->isAnyComplexType()) {
8459 // Init = 0xFFFF + 0xFFFFi;
8460 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8461 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8462 }
8463 Type = OrigType;
8464 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008465 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008466 case BO_LT:
8467 case BO_GT: {
8468 // 'min' reduction op - initializer is 'Largest representable number in
8469 // the reduction list item type'.
8470 // 'max' reduction op - initializer is 'Least representable number in
8471 // the reduction list item type'.
8472 if (Type->isIntegerType() || Type->isPointerType()) {
8473 bool IsSigned = Type->hasSignedIntegerRepresentation();
8474 auto Size = Context.getTypeSize(Type);
8475 QualType IntTy =
8476 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8477 llvm::APInt InitValue =
8478 (BOK != BO_LT)
8479 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8480 : llvm::APInt::getMinValue(Size)
8481 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8482 : llvm::APInt::getMaxValue(Size);
8483 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8484 if (Type->isPointerType()) {
8485 // Cast to pointer type.
8486 auto CastExpr = BuildCStyleCastExpr(
8487 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8488 SourceLocation(), Init);
8489 if (CastExpr.isInvalid())
8490 continue;
8491 Init = CastExpr.get();
8492 }
8493 } else if (Type->isRealFloatingType()) {
8494 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8495 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8496 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8497 Type, ELoc);
8498 }
8499 break;
8500 }
8501 case BO_PtrMemD:
8502 case BO_PtrMemI:
8503 case BO_MulAssign:
8504 case BO_Div:
8505 case BO_Rem:
8506 case BO_Sub:
8507 case BO_Shl:
8508 case BO_Shr:
8509 case BO_LE:
8510 case BO_GE:
8511 case BO_EQ:
8512 case BO_NE:
8513 case BO_AndAssign:
8514 case BO_XorAssign:
8515 case BO_OrAssign:
8516 case BO_Assign:
8517 case BO_AddAssign:
8518 case BO_SubAssign:
8519 case BO_DivAssign:
8520 case BO_RemAssign:
8521 case BO_ShlAssign:
8522 case BO_ShrAssign:
8523 case BO_Comma:
8524 llvm_unreachable("Unexpected reduction operation");
8525 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008526 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008527 if (Init && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008528 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8529 /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008530 } else if (!Init)
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008531 ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008532 if (RHSVD->isInvalidDecl())
8533 continue;
8534 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008535 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8536 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008537 bool IsDecl =
8538 !VD ||
8539 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8540 Diag(D->getLocation(),
8541 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8542 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008543 continue;
8544 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008545 // Store initializer for single element in private copy. Will be used during
8546 // codegen.
8547 PrivateVD->setInit(RHSVD->getInit());
8548 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008549 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008550 ExprResult ReductionOp;
8551 if (DeclareReductionRef.isUsable()) {
8552 QualType RedTy = DeclareReductionRef.get()->getType();
8553 QualType PtrRedTy = Context.getPointerType(RedTy);
8554 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8555 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8556 if (!BasePath.empty()) {
8557 LHS = DefaultLvalueConversion(LHS.get());
8558 RHS = DefaultLvalueConversion(RHS.get());
8559 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8560 CK_UncheckedDerivedToBase, LHS.get(),
8561 &BasePath, LHS.get()->getValueKind());
8562 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8563 CK_UncheckedDerivedToBase, RHS.get(),
8564 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008565 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008566 FunctionProtoType::ExtProtoInfo EPI;
8567 QualType Params[] = {PtrRedTy, PtrRedTy};
8568 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8569 auto *OVE = new (Context) OpaqueValueExpr(
8570 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8571 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8572 Expr *Args[] = {LHS.get(), RHS.get()};
8573 ReductionOp = new (Context)
8574 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8575 } else {
8576 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8577 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8578 if (ReductionOp.isUsable()) {
8579 if (BOK != BO_LT && BOK != BO_GT) {
8580 ReductionOp =
8581 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8582 BO_Assign, LHSDRE, ReductionOp.get());
8583 } else {
8584 auto *ConditionalOp = new (Context) ConditionalOperator(
8585 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8586 RHSDRE, Type, VK_LValue, OK_Ordinary);
8587 ReductionOp =
8588 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8589 BO_Assign, LHSDRE, ConditionalOp);
8590 }
8591 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8592 }
8593 if (ReductionOp.isInvalid())
8594 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008595 }
8596
Alexey Bataev60da77e2016-02-29 05:54:20 +00008597 DeclRefExpr *Ref = nullptr;
8598 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008599 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008600 if (ASE || OASE) {
8601 TransformExprToCaptures RebuildToCapture(*this, D);
8602 VarsExpr =
8603 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8604 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008605 } else {
8606 VarsExpr = Ref =
8607 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008608 }
8609 if (!IsOpenMPCapturedDecl(D)) {
8610 ExprCaptures.push_back(Ref->getDecl());
8611 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8612 ExprResult RefRes = DefaultLvalueConversion(Ref);
8613 if (!RefRes.isUsable())
8614 continue;
8615 ExprResult PostUpdateRes =
8616 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8617 SimpleRefExpr, RefRes.get());
8618 if (!PostUpdateRes.isUsable())
8619 continue;
8620 ExprPostUpdates.push_back(
8621 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008622 }
8623 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008624 }
8625 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8626 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008627 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008628 LHSs.push_back(LHSDRE);
8629 RHSs.push_back(RHSDRE);
8630 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008631 }
8632
8633 if (Vars.empty())
8634 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00008635
Alexey Bataevc5e02582014-06-16 07:08:35 +00008636 return OMPReductionClause::Create(
8637 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008638 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008639 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8640 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00008641}
8642
Alexey Bataevecba70f2016-04-12 11:02:11 +00008643bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8644 SourceLocation LinLoc) {
8645 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8646 LinKind == OMPC_LINEAR_unknown) {
8647 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8648 return true;
8649 }
8650 return false;
8651}
8652
8653bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8654 OpenMPLinearClauseKind LinKind,
8655 QualType Type) {
8656 auto *VD = dyn_cast_or_null<VarDecl>(D);
8657 // A variable must not have an incomplete type or a reference type.
8658 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8659 return true;
8660 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8661 !Type->isReferenceType()) {
8662 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8663 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8664 return true;
8665 }
8666 Type = Type.getNonReferenceType();
8667
8668 // A list item must not be const-qualified.
8669 if (Type.isConstant(Context)) {
8670 Diag(ELoc, diag::err_omp_const_variable)
8671 << getOpenMPClauseName(OMPC_linear);
8672 if (D) {
8673 bool IsDecl =
8674 !VD ||
8675 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8676 Diag(D->getLocation(),
8677 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8678 << D;
8679 }
8680 return true;
8681 }
8682
8683 // A list item must be of integral or pointer type.
8684 Type = Type.getUnqualifiedType().getCanonicalType();
8685 const auto *Ty = Type.getTypePtrOrNull();
8686 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8687 !Ty->isPointerType())) {
8688 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8689 if (D) {
8690 bool IsDecl =
8691 !VD ||
8692 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8693 Diag(D->getLocation(),
8694 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8695 << D;
8696 }
8697 return true;
8698 }
8699 return false;
8700}
8701
Alexey Bataev182227b2015-08-20 10:54:39 +00008702OMPClause *Sema::ActOnOpenMPLinearClause(
8703 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8704 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8705 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008706 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008707 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00008708 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008709 SmallVector<Decl *, 4> ExprCaptures;
8710 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008711 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00008712 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00008713 for (auto &RefExpr : VarList) {
8714 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008715 SourceLocation ELoc;
8716 SourceRange ERange;
8717 Expr *SimpleRefExpr = RefExpr;
8718 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8719 /*AllowArraySection=*/false);
8720 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00008721 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008722 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008723 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00008724 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00008725 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008726 ValueDecl *D = Res.first;
8727 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00008728 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00008729
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008730 QualType Type = D->getType();
8731 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00008732
8733 // OpenMP [2.14.3.7, linear clause]
8734 // A list-item cannot appear in more than one linear clause.
8735 // A list-item that appears in a linear clause cannot appear in any
8736 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008737 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00008738 if (DVar.RefExpr) {
8739 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8740 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008741 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00008742 continue;
8743 }
8744
Alexey Bataevecba70f2016-04-12 11:02:11 +00008745 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00008746 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00008747 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00008748
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008749 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008750 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8751 D->hasAttrs() ? &D->getAttrs() : nullptr);
8752 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008753 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008754 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008755 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008756 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008757 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00008758 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8759 if (!IsOpenMPCapturedDecl(D)) {
8760 ExprCaptures.push_back(Ref->getDecl());
8761 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8762 ExprResult RefRes = DefaultLvalueConversion(Ref);
8763 if (!RefRes.isUsable())
8764 continue;
8765 ExprResult PostUpdateRes =
8766 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8767 SimpleRefExpr, RefRes.get());
8768 if (!PostUpdateRes.isUsable())
8769 continue;
8770 ExprPostUpdates.push_back(
8771 IgnoredValueConversions(PostUpdateRes.get()).get());
8772 }
8773 }
8774 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008775 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008776 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008777 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008778 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008779 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008780 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8781 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8782
8783 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008784 Vars.push_back((VD || CurContext->isDependentContext())
8785 ? RefExpr->IgnoreParens()
8786 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008787 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00008788 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00008789 }
8790
8791 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008792 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008793
8794 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00008795 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00008796 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8797 !Step->isInstantiationDependent() &&
8798 !Step->containsUnexpandedParameterPack()) {
8799 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008800 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00008801 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008802 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008803 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00008804
Alexander Musman3276a272015-03-21 10:12:56 +00008805 // Build var to save the step value.
8806 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008807 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00008808 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00008809 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00008810 ExprResult CalcStep =
8811 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008812 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00008813
Alexander Musman8dba6642014-04-22 13:09:42 +00008814 // Warn about zero linear step (it would be probably better specified as
8815 // making corresponding variables 'const').
8816 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00008817 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8818 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00008819 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8820 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00008821 if (!IsConstant && CalcStep.isUsable()) {
8822 // Calculate the step beforehand instead of doing this on each iteration.
8823 // (This is not used if the number of iterations may be kfold-ed).
8824 CalcStepExpr = CalcStep.get();
8825 }
Alexander Musman8dba6642014-04-22 13:09:42 +00008826 }
8827
Alexey Bataev182227b2015-08-20 10:54:39 +00008828 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8829 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008830 StepExpr, CalcStepExpr,
8831 buildPreInits(Context, ExprCaptures),
8832 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00008833}
8834
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008835static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8836 Expr *NumIterations, Sema &SemaRef,
8837 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00008838 // Walk the vars and build update/final expressions for the CodeGen.
8839 SmallVector<Expr *, 8> Updates;
8840 SmallVector<Expr *, 8> Finals;
8841 Expr *Step = Clause.getStep();
8842 Expr *CalcStep = Clause.getCalcStep();
8843 // OpenMP [2.14.3.7, linear clause]
8844 // If linear-step is not specified it is assumed to be 1.
8845 if (Step == nullptr)
8846 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008847 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00008848 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008849 }
Alexander Musman3276a272015-03-21 10:12:56 +00008850 bool HasErrors = false;
8851 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008852 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008853 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00008854 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008855 SourceLocation ELoc;
8856 SourceRange ERange;
8857 Expr *SimpleRefExpr = RefExpr;
8858 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8859 /*AllowArraySection=*/false);
8860 ValueDecl *D = Res.first;
8861 if (Res.second || !D) {
8862 Updates.push_back(nullptr);
8863 Finals.push_back(nullptr);
8864 HasErrors = true;
8865 continue;
8866 }
8867 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8868 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8869 ->getMemberDecl();
8870 }
8871 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00008872 Expr *InitExpr = *CurInit;
8873
8874 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00008875 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00008876 Expr *CapturedRef;
8877 if (LinKind == OMPC_LINEAR_uval)
8878 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8879 else
8880 CapturedRef =
8881 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8882 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8883 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008884
8885 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008886 ExprResult Update;
8887 if (!Info.first) {
8888 Update =
8889 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8890 InitExpr, IV, Step, /* Subtract */ false);
8891 } else
8892 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008893 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8894 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00008895
8896 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008897 ExprResult Final;
8898 if (!Info.first) {
8899 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8900 InitExpr, NumIterations, Step,
8901 /* Subtract */ false);
8902 } else
8903 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008904 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8905 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008906
Alexander Musman3276a272015-03-21 10:12:56 +00008907 if (!Update.isUsable() || !Final.isUsable()) {
8908 Updates.push_back(nullptr);
8909 Finals.push_back(nullptr);
8910 HasErrors = true;
8911 } else {
8912 Updates.push_back(Update.get());
8913 Finals.push_back(Final.get());
8914 }
Richard Trieucc3949d2016-02-18 22:34:54 +00008915 ++CurInit;
8916 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00008917 }
8918 Clause.setUpdates(Updates);
8919 Clause.setFinals(Finals);
8920 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00008921}
8922
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008923OMPClause *Sema::ActOnOpenMPAlignedClause(
8924 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8925 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8926
8927 SmallVector<Expr *, 8> Vars;
8928 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00008929 assert(RefExpr && "NULL expr in OpenMP linear clause.");
8930 SourceLocation ELoc;
8931 SourceRange ERange;
8932 Expr *SimpleRefExpr = RefExpr;
8933 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8934 /*AllowArraySection=*/false);
8935 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008936 // It will be analyzed later.
8937 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008938 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00008939 ValueDecl *D = Res.first;
8940 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008941 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008942
Alexey Bataev1efd1662016-03-29 10:59:56 +00008943 QualType QType = D->getType();
8944 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008945
8946 // OpenMP [2.8.1, simd construct, Restrictions]
8947 // The type of list items appearing in the aligned clause must be
8948 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008949 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008950 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00008951 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008952 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008953 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008954 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00008955 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008956 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00008957 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008958 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00008959 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008960 continue;
8961 }
8962
8963 // OpenMP [2.8.1, simd construct, Restrictions]
8964 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00008965 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00008966 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008967 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
8968 << getOpenMPClauseName(OMPC_aligned);
8969 continue;
8970 }
8971
Alexey Bataev1efd1662016-03-29 10:59:56 +00008972 DeclRefExpr *Ref = nullptr;
8973 if (!VD && IsOpenMPCapturedDecl(D))
8974 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8975 Vars.push_back(DefaultFunctionArrayConversion(
8976 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
8977 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008978 }
8979
8980 // OpenMP [2.8.1, simd construct, Description]
8981 // The parameter of the aligned clause, alignment, must be a constant
8982 // positive integer expression.
8983 // If no optional parameter is specified, implementation-defined default
8984 // alignments for SIMD instructions on the target platforms are assumed.
8985 if (Alignment != nullptr) {
8986 ExprResult AlignResult =
8987 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
8988 if (AlignResult.isInvalid())
8989 return nullptr;
8990 Alignment = AlignResult.get();
8991 }
8992 if (Vars.empty())
8993 return nullptr;
8994
8995 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
8996 EndLoc, Vars, Alignment);
8997}
8998
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008999OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9000 SourceLocation StartLoc,
9001 SourceLocation LParenLoc,
9002 SourceLocation EndLoc) {
9003 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009004 SmallVector<Expr *, 8> SrcExprs;
9005 SmallVector<Expr *, 8> DstExprs;
9006 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009007 for (auto &RefExpr : VarList) {
9008 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9009 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009010 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009011 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009012 SrcExprs.push_back(nullptr);
9013 DstExprs.push_back(nullptr);
9014 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009015 continue;
9016 }
9017
Alexey Bataeved09d242014-05-28 05:53:51 +00009018 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009019 // OpenMP [2.1, C/C++]
9020 // A list item is a variable name.
9021 // OpenMP [2.14.4.1, Restrictions, p.1]
9022 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009023 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009024 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009025 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9026 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009027 continue;
9028 }
9029
9030 Decl *D = DE->getDecl();
9031 VarDecl *VD = cast<VarDecl>(D);
9032
9033 QualType Type = VD->getType();
9034 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9035 // It will be analyzed later.
9036 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009037 SrcExprs.push_back(nullptr);
9038 DstExprs.push_back(nullptr);
9039 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009040 continue;
9041 }
9042
9043 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9044 // A list item that appears in a copyin clause must be threadprivate.
9045 if (!DSAStack->isThreadPrivate(VD)) {
9046 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009047 << getOpenMPClauseName(OMPC_copyin)
9048 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009049 continue;
9050 }
9051
9052 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9053 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009054 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009055 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009056 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009057 auto *SrcVD =
9058 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9059 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009060 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009061 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9062 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009063 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9064 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009065 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009066 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009067 // For arrays generate assignment operation for single element and replace
9068 // it by the original array element in CodeGen.
9069 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9070 PseudoDstExpr, PseudoSrcExpr);
9071 if (AssignmentOp.isInvalid())
9072 continue;
9073 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9074 /*DiscardedValue=*/true);
9075 if (AssignmentOp.isInvalid())
9076 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009077
9078 DSAStack->addDSA(VD, DE, OMPC_copyin);
9079 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009080 SrcExprs.push_back(PseudoSrcExpr);
9081 DstExprs.push_back(PseudoDstExpr);
9082 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009083 }
9084
Alexey Bataeved09d242014-05-28 05:53:51 +00009085 if (Vars.empty())
9086 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009087
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009088 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9089 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009090}
9091
Alexey Bataevbae9a792014-06-27 10:37:06 +00009092OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9093 SourceLocation StartLoc,
9094 SourceLocation LParenLoc,
9095 SourceLocation EndLoc) {
9096 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009097 SmallVector<Expr *, 8> SrcExprs;
9098 SmallVector<Expr *, 8> DstExprs;
9099 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009100 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009101 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9102 SourceLocation ELoc;
9103 SourceRange ERange;
9104 Expr *SimpleRefExpr = RefExpr;
9105 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9106 /*AllowArraySection=*/false);
9107 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009108 // It will be analyzed later.
9109 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009110 SrcExprs.push_back(nullptr);
9111 DstExprs.push_back(nullptr);
9112 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009113 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009114 ValueDecl *D = Res.first;
9115 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009116 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009117
Alexey Bataeve122da12016-03-17 10:50:17 +00009118 QualType Type = D->getType();
9119 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009120
9121 // OpenMP [2.14.4.2, Restrictions, p.2]
9122 // A list item that appears in a copyprivate clause may not appear in a
9123 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009124 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9125 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009126 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9127 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009128 Diag(ELoc, diag::err_omp_wrong_dsa)
9129 << getOpenMPClauseName(DVar.CKind)
9130 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009131 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009132 continue;
9133 }
9134
9135 // OpenMP [2.11.4.2, Restrictions, p.1]
9136 // All list items that appear in a copyprivate clause must be either
9137 // threadprivate or private in the enclosing context.
9138 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009139 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009140 if (DVar.CKind == OMPC_shared) {
9141 Diag(ELoc, diag::err_omp_required_access)
9142 << getOpenMPClauseName(OMPC_copyprivate)
9143 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009144 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009145 continue;
9146 }
9147 }
9148 }
9149
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009150 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009151 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009152 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009153 << getOpenMPClauseName(OMPC_copyprivate) << Type
9154 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009155 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009156 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009157 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009158 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009159 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009160 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009161 continue;
9162 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009163
Alexey Bataevbae9a792014-06-27 10:37:06 +00009164 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9165 // A variable of class type (or array thereof) that appears in a
9166 // copyin clause requires an accessible, unambiguous copy assignment
9167 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009168 Type = Context.getBaseElementType(Type.getNonReferenceType())
9169 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009170 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009171 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9172 D->hasAttrs() ? &D->getAttrs() : nullptr);
9173 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009174 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009175 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9176 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009177 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009178 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009179 PseudoDstExpr, PseudoSrcExpr);
9180 if (AssignmentOp.isInvalid())
9181 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009182 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009183 /*DiscardedValue=*/true);
9184 if (AssignmentOp.isInvalid())
9185 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009186
9187 // No need to mark vars as copyprivate, they are already threadprivate or
9188 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009189 assert(VD || IsOpenMPCapturedDecl(D));
9190 Vars.push_back(
9191 VD ? RefExpr->IgnoreParens()
9192 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009193 SrcExprs.push_back(PseudoSrcExpr);
9194 DstExprs.push_back(PseudoDstExpr);
9195 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009196 }
9197
9198 if (Vars.empty())
9199 return nullptr;
9200
Alexey Bataeva63048e2015-03-23 06:18:07 +00009201 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9202 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009203}
9204
Alexey Bataev6125da92014-07-21 11:26:11 +00009205OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9206 SourceLocation StartLoc,
9207 SourceLocation LParenLoc,
9208 SourceLocation EndLoc) {
9209 if (VarList.empty())
9210 return nullptr;
9211
9212 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9213}
Alexey Bataevdea47612014-07-23 07:46:59 +00009214
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009215OMPClause *
9216Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9217 SourceLocation DepLoc, SourceLocation ColonLoc,
9218 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9219 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009220 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009221 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009222 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009223 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009224 return nullptr;
9225 }
9226 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009227 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9228 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009229 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009230 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009231 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9232 /*Last=*/OMPC_DEPEND_unknown, Except)
9233 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009234 return nullptr;
9235 }
9236 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009237 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009238 llvm::APSInt DepCounter(/*BitWidth=*/32);
9239 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9240 if (DepKind == OMPC_DEPEND_sink) {
9241 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9242 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9243 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009244 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009245 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009246 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9247 DSAStack->getParentOrderedRegionParam()) {
9248 for (auto &RefExpr : VarList) {
9249 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009250 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009251 // It will be analyzed later.
9252 Vars.push_back(RefExpr);
9253 continue;
9254 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009255
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009256 SourceLocation ELoc = RefExpr->getExprLoc();
9257 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9258 if (DepKind == OMPC_DEPEND_sink) {
9259 if (DepCounter >= TotalDepCount) {
9260 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9261 continue;
9262 }
9263 ++DepCounter;
9264 // OpenMP [2.13.9, Summary]
9265 // depend(dependence-type : vec), where dependence-type is:
9266 // 'sink' and where vec is the iteration vector, which has the form:
9267 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9268 // where n is the value specified by the ordered clause in the loop
9269 // directive, xi denotes the loop iteration variable of the i-th nested
9270 // loop associated with the loop directive, and di is a constant
9271 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009272 if (CurContext->isDependentContext()) {
9273 // It will be analyzed later.
9274 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009275 continue;
9276 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009277 SimpleExpr = SimpleExpr->IgnoreImplicit();
9278 OverloadedOperatorKind OOK = OO_None;
9279 SourceLocation OOLoc;
9280 Expr *LHS = SimpleExpr;
9281 Expr *RHS = nullptr;
9282 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9283 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9284 OOLoc = BO->getOperatorLoc();
9285 LHS = BO->getLHS()->IgnoreParenImpCasts();
9286 RHS = BO->getRHS()->IgnoreParenImpCasts();
9287 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9288 OOK = OCE->getOperator();
9289 OOLoc = OCE->getOperatorLoc();
9290 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9291 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9292 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9293 OOK = MCE->getMethodDecl()
9294 ->getNameInfo()
9295 .getName()
9296 .getCXXOverloadedOperator();
9297 OOLoc = MCE->getCallee()->getExprLoc();
9298 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9299 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9300 }
9301 SourceLocation ELoc;
9302 SourceRange ERange;
9303 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9304 /*AllowArraySection=*/false);
9305 if (Res.second) {
9306 // It will be analyzed later.
9307 Vars.push_back(RefExpr);
9308 }
9309 ValueDecl *D = Res.first;
9310 if (!D)
9311 continue;
9312
9313 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9314 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9315 continue;
9316 }
9317 if (RHS) {
9318 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9319 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9320 if (RHSRes.isInvalid())
9321 continue;
9322 }
9323 if (!CurContext->isDependentContext() &&
9324 DSAStack->getParentOrderedRegionParam() &&
9325 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9326 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9327 << DSAStack->getParentLoopControlVariable(
9328 DepCounter.getZExtValue());
9329 continue;
9330 }
9331 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009332 } else {
9333 // OpenMP [2.11.1.1, Restrictions, p.3]
9334 // A variable that is part of another variable (such as a field of a
9335 // structure) but is not an array element or an array section cannot
9336 // appear in a depend clause.
9337 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9338 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9339 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9340 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9341 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009342 (ASE &&
9343 !ASE->getBase()
9344 ->getType()
9345 .getNonReferenceType()
9346 ->isPointerType() &&
9347 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009348 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9349 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009350 continue;
9351 }
9352 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009353 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9354 }
9355
9356 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9357 TotalDepCount > VarList.size() &&
9358 DSAStack->getParentOrderedRegionParam()) {
9359 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9360 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9361 }
9362 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9363 Vars.empty())
9364 return nullptr;
9365 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009366 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9367 DepKind, DepLoc, ColonLoc, Vars);
9368 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9369 DSAStack->addDoacrossDependClause(C, OpsOffs);
9370 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009371}
Michael Wonge710d542015-08-07 16:16:36 +00009372
9373OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9374 SourceLocation LParenLoc,
9375 SourceLocation EndLoc) {
9376 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009377
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009378 // OpenMP [2.9.1, Restrictions]
9379 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009380 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9381 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009382 return nullptr;
9383
Michael Wonge710d542015-08-07 16:16:36 +00009384 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9385}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009386
9387static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9388 DSAStackTy *Stack, CXXRecordDecl *RD) {
9389 if (!RD || RD->isInvalidDecl())
9390 return true;
9391
9392 auto QTy = SemaRef.Context.getRecordType(RD);
9393 if (RD->isDynamicClass()) {
9394 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9395 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9396 return false;
9397 }
9398 auto *DC = RD;
9399 bool IsCorrect = true;
9400 for (auto *I : DC->decls()) {
9401 if (I) {
9402 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9403 if (MD->isStatic()) {
9404 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9405 SemaRef.Diag(MD->getLocation(),
9406 diag::note_omp_static_member_in_target);
9407 IsCorrect = false;
9408 }
9409 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9410 if (VD->isStaticDataMember()) {
9411 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9412 SemaRef.Diag(VD->getLocation(),
9413 diag::note_omp_static_member_in_target);
9414 IsCorrect = false;
9415 }
9416 }
9417 }
9418 }
9419
9420 for (auto &I : RD->bases()) {
9421 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9422 I.getType()->getAsCXXRecordDecl()))
9423 IsCorrect = false;
9424 }
9425 return IsCorrect;
9426}
9427
9428static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9429 DSAStackTy *Stack, QualType QTy) {
9430 NamedDecl *ND;
9431 if (QTy->isIncompleteType(&ND)) {
9432 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9433 return false;
9434 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009435 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009436 return false;
9437 }
9438 return true;
9439}
9440
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009441/// \brief Return true if it can be proven that the provided array expression
9442/// (array section or array subscript) does NOT specify the whole size of the
9443/// array whose base type is \a BaseQTy.
9444static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9445 const Expr *E,
9446 QualType BaseQTy) {
9447 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9448
9449 // If this is an array subscript, it refers to the whole size if the size of
9450 // the dimension is constant and equals 1. Also, an array section assumes the
9451 // format of an array subscript if no colon is used.
9452 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9453 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9454 return ATy->getSize().getSExtValue() != 1;
9455 // Size can't be evaluated statically.
9456 return false;
9457 }
9458
9459 assert(OASE && "Expecting array section if not an array subscript.");
9460 auto *LowerBound = OASE->getLowerBound();
9461 auto *Length = OASE->getLength();
9462
9463 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009464 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009465 if (LowerBound) {
9466 llvm::APSInt ConstLowerBound;
9467 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9468 return false; // Can't get the integer value as a constant.
9469 if (ConstLowerBound.getSExtValue())
9470 return true;
9471 }
9472
9473 // If we don't have a length we covering the whole dimension.
9474 if (!Length)
9475 return false;
9476
9477 // If the base is a pointer, we don't have a way to get the size of the
9478 // pointee.
9479 if (BaseQTy->isPointerType())
9480 return false;
9481
9482 // We can only check if the length is the same as the size of the dimension
9483 // if we have a constant array.
9484 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9485 if (!CATy)
9486 return false;
9487
9488 llvm::APSInt ConstLength;
9489 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9490 return false; // Can't get the integer value as a constant.
9491
9492 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9493}
9494
9495// Return true if it can be proven that the provided array expression (array
9496// section or array subscript) does NOT specify a single element of the array
9497// whose base type is \a BaseQTy.
9498static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009499 const Expr *E,
9500 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009501 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9502
9503 // An array subscript always refer to a single element. Also, an array section
9504 // assumes the format of an array subscript if no colon is used.
9505 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9506 return false;
9507
9508 assert(OASE && "Expecting array section if not an array subscript.");
9509 auto *Length = OASE->getLength();
9510
9511 // If we don't have a length we have to check if the array has unitary size
9512 // for this dimension. Also, we should always expect a length if the base type
9513 // is pointer.
9514 if (!Length) {
9515 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9516 return ATy->getSize().getSExtValue() != 1;
9517 // We cannot assume anything.
9518 return false;
9519 }
9520
9521 // Check if the length evaluates to 1.
9522 llvm::APSInt ConstLength;
9523 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9524 return false; // Can't get the integer value as a constant.
9525
9526 return ConstLength.getSExtValue() != 1;
9527}
9528
Samuel Antao661c0902016-05-26 17:39:58 +00009529// Return the expression of the base of the mappable expression or null if it
9530// cannot be determined and do all the necessary checks to see if the expression
9531// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009532// components of the expression.
9533static Expr *CheckMapClauseExpressionBase(
9534 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009535 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9536 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009537 SourceLocation ELoc = E->getExprLoc();
9538 SourceRange ERange = E->getSourceRange();
9539
9540 // The base of elements of list in a map clause have to be either:
9541 // - a reference to variable or field.
9542 // - a member expression.
9543 // - an array expression.
9544 //
9545 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9546 // reference to 'r'.
9547 //
9548 // If we have:
9549 //
9550 // struct SS {
9551 // Bla S;
9552 // foo() {
9553 // #pragma omp target map (S.Arr[:12]);
9554 // }
9555 // }
9556 //
9557 // We want to retrieve the member expression 'this->S';
9558
9559 Expr *RelevantExpr = nullptr;
9560
Samuel Antao5de996e2016-01-22 20:21:36 +00009561 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9562 // If a list item is an array section, it must specify contiguous storage.
9563 //
9564 // For this restriction it is sufficient that we make sure only references
9565 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009566 // exist except in the rightmost expression (unless they cover the whole
9567 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009568 //
9569 // r.ArrS[3:5].Arr[6:7]
9570 //
9571 // r.ArrS[3:5].x
9572 //
9573 // but these would be valid:
9574 // r.ArrS[3].Arr[6:7]
9575 //
9576 // r.ArrS[3].x
9577
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009578 bool AllowUnitySizeArraySection = true;
9579 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009580
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009581 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009582 E = E->IgnoreParenImpCasts();
9583
9584 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9585 if (!isa<VarDecl>(CurE->getDecl()))
9586 break;
9587
9588 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009589
9590 // If we got a reference to a declaration, we should not expect any array
9591 // section before that.
9592 AllowUnitySizeArraySection = false;
9593 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009594
9595 // Record the component.
9596 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9597 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009598 continue;
9599 }
9600
9601 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9602 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9603
9604 if (isa<CXXThisExpr>(BaseE))
9605 // We found a base expression: this->Val.
9606 RelevantExpr = CurE;
9607 else
9608 E = BaseE;
9609
9610 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9611 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9612 << CurE->getSourceRange();
9613 break;
9614 }
9615
9616 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9617
9618 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9619 // A bit-field cannot appear in a map clause.
9620 //
9621 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009622 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9623 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009624 break;
9625 }
9626
9627 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9628 // If the type of a list item is a reference to a type T then the type
9629 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009630 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009631
9632 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9633 // A list item cannot be a variable that is a member of a structure with
9634 // a union type.
9635 //
9636 if (auto *RT = CurType->getAs<RecordType>())
9637 if (RT->isUnionType()) {
9638 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9639 << CurE->getSourceRange();
9640 break;
9641 }
9642
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009643 // If we got a member expression, we should not expect any array section
9644 // before that:
9645 //
9646 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9647 // If a list item is an element of a structure, only the rightmost symbol
9648 // of the variable reference can be an array section.
9649 //
9650 AllowUnitySizeArraySection = false;
9651 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009652
9653 // Record the component.
9654 CurComponents.push_back(
9655 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +00009656 continue;
9657 }
9658
9659 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9660 E = CurE->getBase()->IgnoreParenImpCasts();
9661
9662 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9663 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9664 << 0 << CurE->getSourceRange();
9665 break;
9666 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009667
9668 // If we got an array subscript that express the whole dimension we
9669 // can have any array expressions before. If it only expressing part of
9670 // the dimension, we can only have unitary-size array expressions.
9671 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9672 E->getType()))
9673 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009674
9675 // Record the component - we don't have any declaration associated.
9676 CurComponents.push_back(
9677 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009678 continue;
9679 }
9680
9681 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009682 E = CurE->getBase()->IgnoreParenImpCasts();
9683
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009684 auto CurType =
9685 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9686
Samuel Antao5de996e2016-01-22 20:21:36 +00009687 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9688 // If the type of a list item is a reference to a type T then the type
9689 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +00009690 if (CurType->isReferenceType())
9691 CurType = CurType->getPointeeType();
9692
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009693 bool IsPointer = CurType->isAnyPointerType();
9694
9695 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009696 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9697 << 0 << CurE->getSourceRange();
9698 break;
9699 }
9700
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009701 bool NotWhole =
9702 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9703 bool NotUnity =
9704 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9705
Samuel Antaodab51bb2016-07-18 23:22:11 +00009706 if (AllowWholeSizeArraySection) {
9707 // Any array section is currently allowed. Allowing a whole size array
9708 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009709 //
9710 // If this array section refers to the whole dimension we can still
9711 // accept other array sections before this one, except if the base is a
9712 // pointer. Otherwise, only unitary sections are accepted.
9713 if (NotWhole || IsPointer)
9714 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +00009715 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009716 // A unity or whole array section is not allowed and that is not
9717 // compatible with the properties of the current array section.
9718 SemaRef.Diag(
9719 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9720 << CurE->getSourceRange();
9721 break;
9722 }
Samuel Antao90927002016-04-26 14:54:23 +00009723
9724 // Record the component - we don't have any declaration associated.
9725 CurComponents.push_back(
9726 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +00009727 continue;
9728 }
9729
9730 // If nothing else worked, this is not a valid map clause expression.
9731 SemaRef.Diag(ELoc,
9732 diag::err_omp_expected_named_var_member_or_array_expression)
9733 << ERange;
9734 break;
9735 }
9736
9737 return RelevantExpr;
9738}
9739
9740// Return true if expression E associated with value VD has conflicts with other
9741// map information.
Samuel Antao90927002016-04-26 14:54:23 +00009742static bool CheckMapConflicts(
9743 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9744 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +00009745 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9746 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009747 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +00009748 SourceLocation ELoc = E->getExprLoc();
9749 SourceRange ERange = E->getSourceRange();
9750
9751 // In order to easily check the conflicts we need to match each component of
9752 // the expression under test with the components of the expressions that are
9753 // already in the stack.
9754
Samuel Antao5de996e2016-01-22 20:21:36 +00009755 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009756 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009757 "Map clause expression with unexpected base!");
9758
9759 // Variables to help detecting enclosing problems in data environment nests.
9760 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +00009761 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +00009762
Samuel Antao90927002016-04-26 14:54:23 +00009763 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9764 VD, CurrentRegionOnly,
9765 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00009766 StackComponents,
9767 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +00009768
Samuel Antao5de996e2016-01-22 20:21:36 +00009769 assert(!StackComponents.empty() &&
9770 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +00009771 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +00009772 "Map clause expression with unexpected base!");
9773
Samuel Antao90927002016-04-26 14:54:23 +00009774 // The whole expression in the stack.
9775 auto *RE = StackComponents.front().getAssociatedExpression();
9776
Samuel Antao5de996e2016-01-22 20:21:36 +00009777 // Expressions must start from the same base. Here we detect at which
9778 // point both expressions diverge from each other and see if we can
9779 // detect if the memory referred to both expressions is contiguous and
9780 // do not overlap.
9781 auto CI = CurComponents.rbegin();
9782 auto CE = CurComponents.rend();
9783 auto SI = StackComponents.rbegin();
9784 auto SE = StackComponents.rend();
9785 for (; CI != CE && SI != SE; ++CI, ++SI) {
9786
9787 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9788 // At most one list item can be an array item derived from a given
9789 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +00009790 if (CurrentRegionOnly &&
9791 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9792 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9793 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9794 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9795 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +00009796 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +00009797 << CI->getAssociatedExpression()->getSourceRange();
9798 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9799 diag::note_used_here)
9800 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +00009801 return true;
9802 }
9803
9804 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +00009805 if (CI->getAssociatedExpression()->getStmtClass() !=
9806 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +00009807 break;
9808
9809 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +00009810 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +00009811 break;
9812 }
Kelvin Li9f645ae2016-07-18 22:49:16 +00009813 // Check if the extra components of the expressions in the enclosing
9814 // data environment are redundant for the current base declaration.
9815 // If they are, the maps completely overlap, which is legal.
9816 for (; SI != SE; ++SI) {
9817 QualType Type;
9818 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +00009819 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009820 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +00009821 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9822 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +00009823 auto *E = OASE->getBase()->IgnoreParenImpCasts();
9824 Type =
9825 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9826 }
9827 if (Type.isNull() || Type->isAnyPointerType() ||
9828 CheckArrayExpressionDoesNotReferToWholeSize(
9829 SemaRef, SI->getAssociatedExpression(), Type))
9830 break;
9831 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009832
9833 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9834 // List items of map clauses in the same construct must not share
9835 // original storage.
9836 //
9837 // If the expressions are exactly the same or one is a subset of the
9838 // other, it means they are sharing storage.
9839 if (CI == CE && SI == SE) {
9840 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +00009841 if (CKind == OMPC_map)
9842 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9843 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009844 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009845 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9846 << ERange;
9847 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009848 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9849 << RE->getSourceRange();
9850 return true;
9851 } else {
9852 // If we find the same expression in the enclosing data environment,
9853 // that is legal.
9854 IsEnclosedByDataEnvironmentExpr = true;
9855 return false;
9856 }
9857 }
9858
Samuel Antao90927002016-04-26 14:54:23 +00009859 QualType DerivedType =
9860 std::prev(CI)->getAssociatedDeclaration()->getType();
9861 SourceLocation DerivedLoc =
9862 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +00009863
9864 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9865 // If the type of a list item is a reference to a type T then the type
9866 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +00009867 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +00009868
9869 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9870 // A variable for which the type is pointer and an array section
9871 // derived from that variable must not appear as list items of map
9872 // clauses of the same construct.
9873 //
9874 // Also, cover one of the cases in:
9875 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9876 // If any part of the original storage of a list item has corresponding
9877 // storage in the device data environment, all of the original storage
9878 // must have corresponding storage in the device data environment.
9879 //
9880 if (DerivedType->isAnyPointerType()) {
9881 if (CI == CE || SI == SE) {
9882 SemaRef.Diag(
9883 DerivedLoc,
9884 diag::err_omp_pointer_mapped_along_with_derived_section)
9885 << DerivedLoc;
9886 } else {
9887 assert(CI != CE && SI != SE);
9888 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9889 << DerivedLoc;
9890 }
9891 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9892 << RE->getSourceRange();
9893 return true;
9894 }
9895
9896 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9897 // List items of map clauses in the same construct must not share
9898 // original storage.
9899 //
9900 // An expression is a subset of the other.
9901 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +00009902 if (CKind == OMPC_map)
9903 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9904 else {
Samuel Antaoec172c62016-05-26 17:49:04 +00009905 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +00009906 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9907 << ERange;
9908 }
Samuel Antao5de996e2016-01-22 20:21:36 +00009909 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9910 << RE->getSourceRange();
9911 return true;
9912 }
9913
9914 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +00009915 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +00009916 if (!CurrentRegionOnly && SI != SE)
9917 EnclosingExpr = RE;
9918
9919 // The current expression is a subset of the expression in the data
9920 // environment.
9921 IsEnclosedByDataEnvironmentExpr |=
9922 (!CurrentRegionOnly && CI != CE && SI == SE);
9923
9924 return false;
9925 });
9926
9927 if (CurrentRegionOnly)
9928 return FoundError;
9929
9930 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9931 // If any part of the original storage of a list item has corresponding
9932 // storage in the device data environment, all of the original storage must
9933 // have corresponding storage in the device data environment.
9934 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9935 // If a list item is an element of a structure, and a different element of
9936 // the structure has a corresponding list item in the device data environment
9937 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +00009938 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +00009939 // data environment prior to the task encountering the construct.
9940 //
9941 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9942 SemaRef.Diag(ELoc,
9943 diag::err_omp_original_storage_is_shared_and_does_not_contain)
9944 << ERange;
9945 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
9946 << EnclosingExpr->getSourceRange();
9947 return true;
9948 }
9949
9950 return FoundError;
9951}
9952
Samuel Antao661c0902016-05-26 17:39:58 +00009953namespace {
9954// Utility struct that gathers all the related lists associated with a mappable
9955// expression.
9956struct MappableVarListInfo final {
9957 // The list of expressions.
9958 ArrayRef<Expr *> VarList;
9959 // The list of processed expressions.
9960 SmallVector<Expr *, 16> ProcessedVarList;
9961 // The mappble components for each expression.
9962 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
9963 // The base declaration of the variable.
9964 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
9965
9966 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
9967 // We have a list of components and base declarations for each entry in the
9968 // variable list.
9969 VarComponents.reserve(VarList.size());
9970 VarBaseDeclarations.reserve(VarList.size());
9971 }
9972};
9973}
9974
9975// Check the validity of the provided variable list for the provided clause kind
9976// \a CKind. In the check process the valid expressions, and mappable expression
9977// components and variables are extracted and used to fill \a Vars,
9978// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
9979// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
9980static void
9981checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
9982 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
9983 SourceLocation StartLoc,
9984 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
9985 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009986 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
9987 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +00009988 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009989
Samuel Antao90927002016-04-26 14:54:23 +00009990 // Keep track of the mappable components and base declarations in this clause.
9991 // Each entry in the list is going to have a list of components associated. We
9992 // record each set of the components so that we can build the clause later on.
9993 // In the end we should have the same amount of declarations and component
9994 // lists.
Samuel Antao90927002016-04-26 14:54:23 +00009995
Samuel Antao661c0902016-05-26 17:39:58 +00009996 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +00009997 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +00009998 SourceLocation ELoc = RE->getExprLoc();
9999
Kelvin Li0bff7af2015-11-23 05:32:03 +000010000 auto *VE = RE->IgnoreParenLValueCasts();
10001
10002 if (VE->isValueDependent() || VE->isTypeDependent() ||
10003 VE->isInstantiationDependent() ||
10004 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010005 // We can only analyze this information once the missing information is
10006 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010007 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010008 continue;
10009 }
10010
10011 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010012
Samuel Antao5de996e2016-01-22 20:21:36 +000010013 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010014 SemaRef.Diag(ELoc,
10015 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010016 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010017 continue;
10018 }
10019
Samuel Antao90927002016-04-26 14:54:23 +000010020 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10021 ValueDecl *CurDeclaration = nullptr;
10022
10023 // Obtain the array or member expression bases if required. Also, fill the
10024 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010025 auto *BE =
10026 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010027 if (!BE)
10028 continue;
10029
Samuel Antao90927002016-04-26 14:54:23 +000010030 assert(!CurComponents.empty() &&
10031 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010032
Samuel Antao90927002016-04-26 14:54:23 +000010033 // For the following checks, we rely on the base declaration which is
10034 // expected to be associated with the last component. The declaration is
10035 // expected to be a variable or a field (if 'this' is being mapped).
10036 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10037 assert(CurDeclaration && "Null decl on map clause.");
10038 assert(
10039 CurDeclaration->isCanonicalDecl() &&
10040 "Expecting components to have associated only canonical declarations.");
10041
10042 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10043 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010044
10045 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010046 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010047
10048 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010049 // threadprivate variables cannot appear in a map clause.
10050 // OpenMP 4.5 [2.10.5, target update Construct]
10051 // threadprivate variables cannot appear in a from clause.
10052 if (VD && DSAS->isThreadPrivate(VD)) {
10053 auto DVar = DSAS->getTopDSA(VD, false);
10054 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10055 << getOpenMPClauseName(CKind);
10056 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010057 continue;
10058 }
10059
Samuel Antao5de996e2016-01-22 20:21:36 +000010060 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10061 // A list item cannot appear in both a map clause and a data-sharing
10062 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010063
Samuel Antao5de996e2016-01-22 20:21:36 +000010064 // Check conflicts with other map clause expressions. We check the conflicts
10065 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010066 // environment, because the restrictions are different. We only have to
10067 // check conflicts across regions for the map clauses.
10068 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10069 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010070 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010071 if (CKind == OMPC_map &&
10072 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10073 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010074 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010075
Samuel Antao661c0902016-05-26 17:39:58 +000010076 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010077 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10078 // If the type of a list item is a reference to a type T then the type will
10079 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010080 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010081
Samuel Antao661c0902016-05-26 17:39:58 +000010082 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10083 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010084 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010085 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010086 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10087 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010088 continue;
10089
Samuel Antao661c0902016-05-26 17:39:58 +000010090 if (CKind == OMPC_map) {
10091 // target enter data
10092 // OpenMP [2.10.2, Restrictions, p. 99]
10093 // A map-type must be specified in all map clauses and must be either
10094 // to or alloc.
10095 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10096 if (DKind == OMPD_target_enter_data &&
10097 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10098 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10099 << (IsMapTypeImplicit ? 1 : 0)
10100 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10101 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010102 continue;
10103 }
Samuel Antao661c0902016-05-26 17:39:58 +000010104
10105 // target exit_data
10106 // OpenMP [2.10.3, Restrictions, p. 102]
10107 // A map-type must be specified in all map clauses and must be either
10108 // from, release, or delete.
10109 if (DKind == OMPD_target_exit_data &&
10110 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10111 MapType == OMPC_MAP_delete)) {
10112 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10113 << (IsMapTypeImplicit ? 1 : 0)
10114 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10115 << getOpenMPDirectiveName(DKind);
10116 continue;
10117 }
10118
10119 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10120 // A list item cannot appear in both a map clause and a data-sharing
10121 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010122 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
10123 DKind == OMPD_target_teams) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010124 auto DVar = DSAS->getTopDSA(VD, false);
10125 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010126 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010127 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010128 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010129 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10130 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10131 continue;
10132 }
10133 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010134 }
10135
Samuel Antao90927002016-04-26 14:54:23 +000010136 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010137 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010138
10139 // Store the components in the stack so that they can be used to check
10140 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010141 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10142 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010143
10144 // Save the components and declaration to create the clause. For purposes of
10145 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010146 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010147 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10148 MVLI.VarComponents.back().append(CurComponents.begin(),
10149 CurComponents.end());
10150 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10151 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010152 }
Samuel Antao661c0902016-05-26 17:39:58 +000010153}
10154
10155OMPClause *
10156Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10157 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10158 SourceLocation MapLoc, SourceLocation ColonLoc,
10159 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10160 SourceLocation LParenLoc, SourceLocation EndLoc) {
10161 MappableVarListInfo MVLI(VarList);
10162 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10163 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010164
Samuel Antao5de996e2016-01-22 20:21:36 +000010165 // We need to produce a map clause even if we don't have variables so that
10166 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010167 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10168 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10169 MVLI.VarComponents, MapTypeModifier, MapType,
10170 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010171}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010172
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010173QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10174 TypeResult ParsedType) {
10175 assert(ParsedType.isUsable());
10176
10177 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10178 if (ReductionType.isNull())
10179 return QualType();
10180
10181 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10182 // A type name in a declare reduction directive cannot be a function type, an
10183 // array type, a reference type, or a type qualified with const, volatile or
10184 // restrict.
10185 if (ReductionType.hasQualifiers()) {
10186 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10187 return QualType();
10188 }
10189
10190 if (ReductionType->isFunctionType()) {
10191 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10192 return QualType();
10193 }
10194 if (ReductionType->isReferenceType()) {
10195 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10196 return QualType();
10197 }
10198 if (ReductionType->isArrayType()) {
10199 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10200 return QualType();
10201 }
10202 return ReductionType;
10203}
10204
10205Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10206 Scope *S, DeclContext *DC, DeclarationName Name,
10207 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10208 AccessSpecifier AS, Decl *PrevDeclInScope) {
10209 SmallVector<Decl *, 8> Decls;
10210 Decls.reserve(ReductionTypes.size());
10211
10212 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10213 ForRedeclaration);
10214 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10215 // A reduction-identifier may not be re-declared in the current scope for the
10216 // same type or for a type that is compatible according to the base language
10217 // rules.
10218 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10219 OMPDeclareReductionDecl *PrevDRD = nullptr;
10220 bool InCompoundScope = true;
10221 if (S != nullptr) {
10222 // Find previous declaration with the same name not referenced in other
10223 // declarations.
10224 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10225 InCompoundScope =
10226 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10227 LookupName(Lookup, S);
10228 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10229 /*AllowInlineNamespace=*/false);
10230 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10231 auto Filter = Lookup.makeFilter();
10232 while (Filter.hasNext()) {
10233 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10234 if (InCompoundScope) {
10235 auto I = UsedAsPrevious.find(PrevDecl);
10236 if (I == UsedAsPrevious.end())
10237 UsedAsPrevious[PrevDecl] = false;
10238 if (auto *D = PrevDecl->getPrevDeclInScope())
10239 UsedAsPrevious[D] = true;
10240 }
10241 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10242 PrevDecl->getLocation();
10243 }
10244 Filter.done();
10245 if (InCompoundScope) {
10246 for (auto &PrevData : UsedAsPrevious) {
10247 if (!PrevData.second) {
10248 PrevDRD = PrevData.first;
10249 break;
10250 }
10251 }
10252 }
10253 } else if (PrevDeclInScope != nullptr) {
10254 auto *PrevDRDInScope = PrevDRD =
10255 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10256 do {
10257 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10258 PrevDRDInScope->getLocation();
10259 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10260 } while (PrevDRDInScope != nullptr);
10261 }
10262 for (auto &TyData : ReductionTypes) {
10263 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10264 bool Invalid = false;
10265 if (I != PreviousRedeclTypes.end()) {
10266 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10267 << TyData.first;
10268 Diag(I->second, diag::note_previous_definition);
10269 Invalid = true;
10270 }
10271 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10272 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10273 Name, TyData.first, PrevDRD);
10274 DC->addDecl(DRD);
10275 DRD->setAccess(AS);
10276 Decls.push_back(DRD);
10277 if (Invalid)
10278 DRD->setInvalidDecl();
10279 else
10280 PrevDRD = DRD;
10281 }
10282
10283 return DeclGroupPtrTy::make(
10284 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10285}
10286
10287void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10288 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10289
10290 // Enter new function scope.
10291 PushFunctionScope();
10292 getCurFunction()->setHasBranchProtectedScope();
10293 getCurFunction()->setHasOMPDeclareReductionCombiner();
10294
10295 if (S != nullptr)
10296 PushDeclContext(S, DRD);
10297 else
10298 CurContext = DRD;
10299
10300 PushExpressionEvaluationContext(PotentiallyEvaluated);
10301
10302 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010303 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10304 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10305 // uses semantics of argument handles by value, but it should be passed by
10306 // reference. C lang does not support references, so pass all parameters as
10307 // pointers.
10308 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010309 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010310 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010311 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10312 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10313 // uses semantics of argument handles by value, but it should be passed by
10314 // reference. C lang does not support references, so pass all parameters as
10315 // pointers.
10316 // Create 'T omp_out;' variable.
10317 auto *OmpOutParm =
10318 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10319 if (S != nullptr) {
10320 PushOnScopeChains(OmpInParm, S);
10321 PushOnScopeChains(OmpOutParm, S);
10322 } else {
10323 DRD->addDecl(OmpInParm);
10324 DRD->addDecl(OmpOutParm);
10325 }
10326}
10327
10328void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10329 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10330 DiscardCleanupsInEvaluationContext();
10331 PopExpressionEvaluationContext();
10332
10333 PopDeclContext();
10334 PopFunctionScopeInfo();
10335
10336 if (Combiner != nullptr)
10337 DRD->setCombiner(Combiner);
10338 else
10339 DRD->setInvalidDecl();
10340}
10341
10342void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10343 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10344
10345 // Enter new function scope.
10346 PushFunctionScope();
10347 getCurFunction()->setHasBranchProtectedScope();
10348
10349 if (S != nullptr)
10350 PushDeclContext(S, DRD);
10351 else
10352 CurContext = DRD;
10353
10354 PushExpressionEvaluationContext(PotentiallyEvaluated);
10355
10356 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010357 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10358 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10359 // uses semantics of argument handles by value, but it should be passed by
10360 // reference. C lang does not support references, so pass all parameters as
10361 // pointers.
10362 // Create 'T omp_priv;' variable.
10363 auto *OmpPrivParm =
10364 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010365 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10366 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10367 // uses semantics of argument handles by value, but it should be passed by
10368 // reference. C lang does not support references, so pass all parameters as
10369 // pointers.
10370 // Create 'T omp_orig;' variable.
10371 auto *OmpOrigParm =
10372 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010373 if (S != nullptr) {
10374 PushOnScopeChains(OmpPrivParm, S);
10375 PushOnScopeChains(OmpOrigParm, S);
10376 } else {
10377 DRD->addDecl(OmpPrivParm);
10378 DRD->addDecl(OmpOrigParm);
10379 }
10380}
10381
10382void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10383 Expr *Initializer) {
10384 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10385 DiscardCleanupsInEvaluationContext();
10386 PopExpressionEvaluationContext();
10387
10388 PopDeclContext();
10389 PopFunctionScopeInfo();
10390
10391 if (Initializer != nullptr)
10392 DRD->setInitializer(Initializer);
10393 else
10394 DRD->setInvalidDecl();
10395}
10396
10397Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10398 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10399 for (auto *D : DeclReductions.get()) {
10400 if (IsValid) {
10401 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10402 if (S != nullptr)
10403 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10404 } else
10405 D->setInvalidDecl();
10406 }
10407 return DeclReductions;
10408}
10409
David Majnemer9d168222016-08-05 17:44:54 +000010410OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010411 SourceLocation StartLoc,
10412 SourceLocation LParenLoc,
10413 SourceLocation EndLoc) {
10414 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010415
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010416 // OpenMP [teams Constrcut, Restrictions]
10417 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010418 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10419 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010420 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010421
10422 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10423}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010424
10425OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10426 SourceLocation StartLoc,
10427 SourceLocation LParenLoc,
10428 SourceLocation EndLoc) {
10429 Expr *ValExpr = ThreadLimit;
10430
10431 // OpenMP [teams Constrcut, Restrictions]
10432 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010433 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10434 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010435 return nullptr;
10436
David Majnemer9d168222016-08-05 17:44:54 +000010437 return new (Context)
10438 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010439}
Alexey Bataeva0569352015-12-01 10:17:31 +000010440
10441OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10442 SourceLocation StartLoc,
10443 SourceLocation LParenLoc,
10444 SourceLocation EndLoc) {
10445 Expr *ValExpr = Priority;
10446
10447 // OpenMP [2.9.1, task Constrcut]
10448 // The priority-value is a non-negative numerical scalar expression.
10449 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10450 /*StrictlyPositive=*/false))
10451 return nullptr;
10452
10453 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10454}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010455
10456OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10457 SourceLocation StartLoc,
10458 SourceLocation LParenLoc,
10459 SourceLocation EndLoc) {
10460 Expr *ValExpr = Grainsize;
10461
10462 // OpenMP [2.9.2, taskloop Constrcut]
10463 // The parameter of the grainsize clause must be a positive integer
10464 // expression.
10465 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10466 /*StrictlyPositive=*/true))
10467 return nullptr;
10468
10469 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10470}
Alexey Bataev382967a2015-12-08 12:06:20 +000010471
10472OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10473 SourceLocation StartLoc,
10474 SourceLocation LParenLoc,
10475 SourceLocation EndLoc) {
10476 Expr *ValExpr = NumTasks;
10477
10478 // OpenMP [2.9.2, taskloop Constrcut]
10479 // The parameter of the num_tasks clause must be a positive integer
10480 // expression.
10481 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10482 /*StrictlyPositive=*/true))
10483 return nullptr;
10484
10485 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10486}
10487
Alexey Bataev28c75412015-12-15 08:19:24 +000010488OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10489 SourceLocation LParenLoc,
10490 SourceLocation EndLoc) {
10491 // OpenMP [2.13.2, critical construct, Description]
10492 // ... where hint-expression is an integer constant expression that evaluates
10493 // to a valid lock hint.
10494 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10495 if (HintExpr.isInvalid())
10496 return nullptr;
10497 return new (Context)
10498 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10499}
10500
Carlo Bertollib4adf552016-01-15 18:50:31 +000010501OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10502 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10503 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10504 SourceLocation EndLoc) {
10505 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10506 std::string Values;
10507 Values += "'";
10508 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10509 Values += "'";
10510 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10511 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10512 return nullptr;
10513 }
10514 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010515 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010516 if (ChunkSize) {
10517 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10518 !ChunkSize->isInstantiationDependent() &&
10519 !ChunkSize->containsUnexpandedParameterPack()) {
10520 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10521 ExprResult Val =
10522 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10523 if (Val.isInvalid())
10524 return nullptr;
10525
10526 ValExpr = Val.get();
10527
10528 // OpenMP [2.7.1, Restrictions]
10529 // chunk_size must be a loop invariant integer expression with a positive
10530 // value.
10531 llvm::APSInt Result;
10532 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10533 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10534 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10535 << "dist_schedule" << ChunkSize->getSourceRange();
10536 return nullptr;
10537 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010538 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10539 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010540 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10541 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10542 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010543 }
10544 }
10545 }
10546
10547 return new (Context)
10548 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010549 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010550}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010551
10552OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10553 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10554 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10555 SourceLocation KindLoc, SourceLocation EndLoc) {
10556 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010557 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010558 std::string Value;
10559 SourceLocation Loc;
10560 Value += "'";
10561 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10562 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010563 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010564 Loc = MLoc;
10565 } else {
10566 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010567 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010568 Loc = KindLoc;
10569 }
10570 Value += "'";
10571 Diag(Loc, diag::err_omp_unexpected_clause_value)
10572 << Value << getOpenMPClauseName(OMPC_defaultmap);
10573 return nullptr;
10574 }
10575
10576 return new (Context)
10577 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10578}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010579
10580bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10581 DeclContext *CurLexicalContext = getCurLexicalContext();
10582 if (!CurLexicalContext->isFileContext() &&
10583 !CurLexicalContext->isExternCContext() &&
10584 !CurLexicalContext->isExternCXXContext()) {
10585 Diag(Loc, diag::err_omp_region_not_file_context);
10586 return false;
10587 }
10588 if (IsInOpenMPDeclareTargetContext) {
10589 Diag(Loc, diag::err_omp_enclosed_declare_target);
10590 return false;
10591 }
10592
10593 IsInOpenMPDeclareTargetContext = true;
10594 return true;
10595}
10596
10597void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10598 assert(IsInOpenMPDeclareTargetContext &&
10599 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10600
10601 IsInOpenMPDeclareTargetContext = false;
10602}
10603
David Majnemer9d168222016-08-05 17:44:54 +000010604void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10605 CXXScopeSpec &ScopeSpec,
10606 const DeclarationNameInfo &Id,
10607 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10608 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010609 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10610 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10611
10612 if (Lookup.isAmbiguous())
10613 return;
10614 Lookup.suppressDiagnostics();
10615
10616 if (!Lookup.isSingleResult()) {
10617 if (TypoCorrection Corrected =
10618 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10619 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10620 CTK_ErrorRecovery)) {
10621 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10622 << Id.getName());
10623 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10624 return;
10625 }
10626
10627 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10628 return;
10629 }
10630
10631 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10632 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10633 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10634 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10635
10636 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10637 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10638 ND->addAttr(A);
10639 if (ASTMutationListener *ML = Context.getASTMutationListener())
10640 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10641 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10642 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10643 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10644 << Id.getName();
10645 }
10646 } else
10647 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10648}
10649
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010650static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10651 Sema &SemaRef, Decl *D) {
10652 if (!D)
10653 return;
10654 Decl *LD = nullptr;
10655 if (isa<TagDecl>(D)) {
10656 LD = cast<TagDecl>(D)->getDefinition();
10657 } else if (isa<VarDecl>(D)) {
10658 LD = cast<VarDecl>(D)->getDefinition();
10659
10660 // If this is an implicit variable that is legal and we do not need to do
10661 // anything.
10662 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010663 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10664 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10665 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010666 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010667 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010668 return;
10669 }
10670
10671 } else if (isa<FunctionDecl>(D)) {
10672 const FunctionDecl *FD = nullptr;
10673 if (cast<FunctionDecl>(D)->hasBody(FD))
10674 LD = const_cast<FunctionDecl *>(FD);
10675
10676 // If the definition is associated with the current declaration in the
10677 // target region (it can be e.g. a lambda) that is legal and we do not need
10678 // to do anything else.
10679 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010680 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10681 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10682 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010683 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010684 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010685 return;
10686 }
10687 }
10688 if (!LD)
10689 LD = D;
10690 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10691 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10692 // Outlined declaration is not declared target.
10693 if (LD->isOutOfLine()) {
10694 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10695 SemaRef.Diag(SL, diag::note_used_here) << SR;
10696 } else {
10697 DeclContext *DC = LD->getDeclContext();
10698 while (DC) {
10699 if (isa<FunctionDecl>(DC) &&
10700 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10701 break;
10702 DC = DC->getParent();
10703 }
10704 if (DC)
10705 return;
10706
10707 // Is not declared in target context.
10708 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10709 SemaRef.Diag(SL, diag::note_used_here) << SR;
10710 }
10711 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010712 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10713 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10714 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010715 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010716 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010717 }
10718}
10719
10720static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10721 Sema &SemaRef, DSAStackTy *Stack,
10722 ValueDecl *VD) {
10723 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10724 return true;
10725 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10726 return false;
10727 return true;
10728}
10729
10730void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10731 if (!D || D->isInvalidDecl())
10732 return;
10733 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10734 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10735 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10736 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10737 if (DSAStack->isThreadPrivate(VD)) {
10738 Diag(SL, diag::err_omp_threadprivate_in_target);
10739 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10740 return;
10741 }
10742 }
10743 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10744 // Problem if any with var declared with incomplete type will be reported
10745 // as normal, so no need to check it here.
10746 if ((E || !VD->getType()->isIncompleteType()) &&
10747 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10748 // Mark decl as declared target to prevent further diagnostic.
10749 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010750 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10751 Context, OMPDeclareTargetDeclAttr::MT_To);
10752 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010753 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010754 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010755 }
10756 return;
10757 }
10758 }
10759 if (!E) {
10760 // Checking declaration inside declare target region.
10761 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10762 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010763 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10764 Context, OMPDeclareTargetDeclAttr::MT_To);
10765 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010766 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010767 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010768 }
10769 return;
10770 }
10771 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10772}
Samuel Antao661c0902016-05-26 17:39:58 +000010773
10774OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10775 SourceLocation StartLoc,
10776 SourceLocation LParenLoc,
10777 SourceLocation EndLoc) {
10778 MappableVarListInfo MVLI(VarList);
10779 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10780 if (MVLI.ProcessedVarList.empty())
10781 return nullptr;
10782
10783 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10784 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10785 MVLI.VarComponents);
10786}
Samuel Antaoec172c62016-05-26 17:49:04 +000010787
10788OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10789 SourceLocation StartLoc,
10790 SourceLocation LParenLoc,
10791 SourceLocation EndLoc) {
10792 MappableVarListInfo MVLI(VarList);
10793 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10794 if (MVLI.ProcessedVarList.empty())
10795 return nullptr;
10796
10797 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10798 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10799 MVLI.VarComponents);
10800}
Carlo Bertolli2404b172016-07-13 15:37:16 +000010801
10802OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10803 SourceLocation StartLoc,
10804 SourceLocation LParenLoc,
10805 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000010806 MappableVarListInfo MVLI(VarList);
10807 SmallVector<Expr *, 8> PrivateCopies;
10808 SmallVector<Expr *, 8> Inits;
10809
Carlo Bertolli2404b172016-07-13 15:37:16 +000010810 for (auto &RefExpr : VarList) {
10811 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10812 SourceLocation ELoc;
10813 SourceRange ERange;
10814 Expr *SimpleRefExpr = RefExpr;
10815 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10816 if (Res.second) {
10817 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000010818 MVLI.ProcessedVarList.push_back(RefExpr);
10819 PrivateCopies.push_back(nullptr);
10820 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010821 }
10822 ValueDecl *D = Res.first;
10823 if (!D)
10824 continue;
10825
10826 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000010827 Type = Type.getNonReferenceType().getUnqualifiedType();
10828
10829 auto *VD = dyn_cast<VarDecl>(D);
10830
10831 // Item should be a pointer or reference to pointer.
10832 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000010833 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10834 << 0 << RefExpr->getSourceRange();
10835 continue;
10836 }
Samuel Antaocc10b852016-07-28 14:23:26 +000010837
10838 // Build the private variable and the expression that refers to it.
10839 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10840 D->hasAttrs() ? &D->getAttrs() : nullptr);
10841 if (VDPrivate->isInvalidDecl())
10842 continue;
10843
10844 CurContext->addDecl(VDPrivate);
10845 auto VDPrivateRefExpr = buildDeclRefExpr(
10846 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10847
10848 // Add temporary variable to initialize the private copy of the pointer.
10849 auto *VDInit =
10850 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10851 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10852 RefExpr->getExprLoc());
10853 AddInitializerToDecl(VDPrivate,
10854 DefaultLvalueConversion(VDInitRefExpr).get(),
10855 /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10856
10857 // If required, build a capture to implement the privatization initialized
10858 // with the current list item value.
10859 DeclRefExpr *Ref = nullptr;
10860 if (!VD)
10861 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10862 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10863 PrivateCopies.push_back(VDPrivateRefExpr);
10864 Inits.push_back(VDInitRefExpr);
10865
10866 // We need to add a data sharing attribute for this variable to make sure it
10867 // is correctly captured. A variable that shows up in a use_device_ptr has
10868 // similar properties of a first private variable.
10869 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10870
10871 // Create a mappable component for the list item. List items in this clause
10872 // only need a component.
10873 MVLI.VarBaseDeclarations.push_back(D);
10874 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10875 MVLI.VarComponents.back().push_back(
10876 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000010877 }
10878
Samuel Antaocc10b852016-07-28 14:23:26 +000010879 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000010880 return nullptr;
10881
Samuel Antaocc10b852016-07-28 14:23:26 +000010882 return OMPUseDevicePtrClause::Create(
10883 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10884 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010885}
Carlo Bertolli70594e92016-07-13 17:16:49 +000010886
10887OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10888 SourceLocation StartLoc,
10889 SourceLocation LParenLoc,
10890 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000010891 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010892 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000010893 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000010894 SourceLocation ELoc;
10895 SourceRange ERange;
10896 Expr *SimpleRefExpr = RefExpr;
10897 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10898 if (Res.second) {
10899 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000010900 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010901 }
10902 ValueDecl *D = Res.first;
10903 if (!D)
10904 continue;
10905
10906 QualType Type = D->getType();
10907 // item should be a pointer or array or reference to pointer or array
10908 if (!Type.getNonReferenceType()->isPointerType() &&
10909 !Type.getNonReferenceType()->isArrayType()) {
10910 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10911 << 0 << RefExpr->getSourceRange();
10912 continue;
10913 }
Samuel Antao6890b092016-07-28 14:25:09 +000010914
10915 // Check if the declaration in the clause does not show up in any data
10916 // sharing attribute.
10917 auto DVar = DSAStack->getTopDSA(D, false);
10918 if (isOpenMPPrivate(DVar.CKind)) {
10919 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10920 << getOpenMPClauseName(DVar.CKind)
10921 << getOpenMPClauseName(OMPC_is_device_ptr)
10922 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10923 ReportOriginalDSA(*this, DSAStack, D, DVar);
10924 continue;
10925 }
10926
10927 Expr *ConflictExpr;
10928 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010929 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010930 [&ConflictExpr](
10931 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10932 OpenMPClauseKind) -> bool {
10933 ConflictExpr = R.front().getAssociatedExpression();
10934 return true;
10935 })) {
10936 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10937 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10938 << ConflictExpr->getSourceRange();
10939 continue;
10940 }
10941
10942 // Store the components in the stack so that they can be used to check
10943 // against other clauses later on.
10944 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
10945 DSAStack->addMappableExpressionComponents(
10946 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
10947
10948 // Record the expression we've just processed.
10949 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
10950
10951 // Create a mappable component for the list item. List items in this clause
10952 // only need a component. We use a null declaration to signal fields in
10953 // 'this'.
10954 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
10955 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
10956 "Unexpected device pointer expression!");
10957 MVLI.VarBaseDeclarations.push_back(
10958 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
10959 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10960 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010961 }
10962
Samuel Antao6890b092016-07-28 14:25:09 +000010963 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000010964 return nullptr;
10965
Samuel Antao6890b092016-07-28 14:25:09 +000010966 return OMPIsDevicePtrClause::Create(
10967 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10968 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010969}