blob: 87115054b0ca3510760523bd2e3306f4d111c5ca [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001092 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001597 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001598 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001599 QualType KmpInt32PtrTy =
1600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001601 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001602 std::make_pair(".global_tid.", KmpInt32PtrTy),
1603 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1604 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1607 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001608 break;
1609 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001610 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001611 case OMPD_target_parallel: {
1612 Sema::CapturedParamNameType ParamsTarget[] = {
1613 std::make_pair(StringRef(), QualType()) // __context with shared vars
1614 };
1615 // Start a captured region for 'target' with no implicit parameters.
1616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1617 ParamsTarget);
1618 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1619 QualType KmpInt32PtrTy =
1620 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001621 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001622 std::make_pair(".global_tid.", KmpInt32PtrTy),
1623 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1624 std::make_pair(StringRef(), QualType()) // __context with shared vars
1625 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001626 // Start a captured region for 'teams' or 'parallel'. Both regions have
1627 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001628 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001629 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001630 break;
1631 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001632 case OMPD_simd:
1633 case OMPD_for:
1634 case OMPD_for_simd:
1635 case OMPD_sections:
1636 case OMPD_section:
1637 case OMPD_single:
1638 case OMPD_master:
1639 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001640 case OMPD_taskgroup:
1641 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001642 case OMPD_ordered:
1643 case OMPD_atomic:
1644 case OMPD_target_data:
1645 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001646 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001647 case OMPD_target_parallel_for_simd:
1648 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001649 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001650 std::make_pair(StringRef(), QualType()) // __context with shared vars
1651 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001652 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1653 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001654 break;
1655 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001656 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001657 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001658 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1659 FunctionProtoType::ExtProtoInfo EPI;
1660 EPI.Variadic = true;
1661 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001662 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001663 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001664 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1665 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1666 std::make_pair(".copy_fn.",
1667 Context.getPointerType(CopyFnType).withConst()),
1668 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001669 std::make_pair(StringRef(), QualType()) // __context with shared vars
1670 };
1671 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1672 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001673 // Mark this captured region as inlined, because we don't use outlined
1674 // function directly.
1675 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1676 AlwaysInlineAttr::CreateImplicit(
1677 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001678 break;
1679 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001680 case OMPD_taskloop:
1681 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001682 QualType KmpInt32Ty =
1683 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1684 QualType KmpUInt64Ty =
1685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1686 QualType KmpInt64Ty =
1687 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1688 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1689 FunctionProtoType::ExtProtoInfo EPI;
1690 EPI.Variadic = true;
1691 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001692 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001693 std::make_pair(".global_tid.", KmpInt32Ty),
1694 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1695 std::make_pair(".privates.",
1696 Context.VoidPtrTy.withConst().withRestrict()),
1697 std::make_pair(
1698 ".copy_fn.",
1699 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1700 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1701 std::make_pair(".lb.", KmpUInt64Ty),
1702 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1703 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001704 std::make_pair(StringRef(), QualType()) // __context with shared vars
1705 };
1706 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1707 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001708 // Mark this captured region as inlined, because we don't use outlined
1709 // function directly.
1710 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1711 AlwaysInlineAttr::CreateImplicit(
1712 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001713 break;
1714 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001715 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001716 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001717 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001718 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001719 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001720 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001721 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001722 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001723 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001724 case OMPD_target_teams_distribute_parallel_for_simd:
1725 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001726 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1727 QualType KmpInt32PtrTy =
1728 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1729 Sema::CapturedParamNameType Params[] = {
1730 std::make_pair(".global_tid.", KmpInt32PtrTy),
1731 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1732 std::make_pair(".previous.lb.", Context.getSizeType()),
1733 std::make_pair(".previous.ub.", Context.getSizeType()),
1734 std::make_pair(StringRef(), QualType()) // __context with shared vars
1735 };
1736 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1737 Params);
1738 break;
1739 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001740 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001741 case OMPD_taskyield:
1742 case OMPD_barrier:
1743 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001744 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001745 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001746 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001747 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001748 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001749 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001750 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001751 case OMPD_declare_target:
1752 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001753 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001754 llvm_unreachable("OpenMP Directive is not allowed");
1755 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001756 llvm_unreachable("Unknown OpenMP directive");
1757 }
1758}
1759
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001760int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1761 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1762 getOpenMPCaptureRegions(CaptureRegions, DKind);
1763 return CaptureRegions.size();
1764}
1765
Alexey Bataev3392d762016-02-16 11:18:12 +00001766static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001767 Expr *CaptureExpr, bool WithInit,
1768 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001769 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001770 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001771 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001772 QualType Ty = Init->getType();
1773 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1774 if (S.getLangOpts().CPlusPlus)
1775 Ty = C.getLValueReferenceType(Ty);
1776 else {
1777 Ty = C.getPointerType(Ty);
1778 ExprResult Res =
1779 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1780 if (!Res.isUsable())
1781 return nullptr;
1782 Init = Res.get();
1783 }
Alexey Bataev61205072016-03-02 04:57:40 +00001784 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001785 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001786 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1787 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001788 if (!WithInit)
1789 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001790 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001791 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001792 return CED;
1793}
1794
Alexey Bataev61205072016-03-02 04:57:40 +00001795static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1796 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001797 OMPCapturedExprDecl *CD;
1798 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1799 CD = cast<OMPCapturedExprDecl>(VD);
1800 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001801 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1802 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001803 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001804 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001805}
1806
Alexey Bataev5a3af132016-03-29 08:58:54 +00001807static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1808 if (!Ref) {
1809 auto *CD =
1810 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1811 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1812 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1813 CaptureExpr->getExprLoc());
1814 }
1815 ExprResult Res = Ref;
1816 if (!S.getLangOpts().CPlusPlus &&
1817 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1818 Ref->getType()->isPointerType())
1819 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1820 if (!Res.isUsable())
1821 return ExprError();
1822 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001823}
1824
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001825namespace {
1826// OpenMP directives parsed in this section are represented as a
1827// CapturedStatement with an associated statement. If a syntax error
1828// is detected during the parsing of the associated statement, the
1829// compiler must abort processing and close the CapturedStatement.
1830//
1831// Combined directives such as 'target parallel' have more than one
1832// nested CapturedStatements. This RAII ensures that we unwind out
1833// of all the nested CapturedStatements when an error is found.
1834class CaptureRegionUnwinderRAII {
1835private:
1836 Sema &S;
1837 bool &ErrorFound;
1838 OpenMPDirectiveKind DKind;
1839
1840public:
1841 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1842 OpenMPDirectiveKind DKind)
1843 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1844 ~CaptureRegionUnwinderRAII() {
1845 if (ErrorFound) {
1846 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1847 while (--ThisCaptureLevel >= 0)
1848 S.ActOnCapturedRegionError();
1849 }
1850 }
1851};
1852} // namespace
1853
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001854StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1855 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001856 bool ErrorFound = false;
1857 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1858 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001859 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001860 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001861 return StmtError();
1862 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001863
1864 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001865 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001866 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001867 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001868 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001869 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001870 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001871 Clause->getClauseKind() == OMPC_copyprivate ||
1872 (getLangOpts().OpenMPUseTLS &&
1873 getASTContext().getTargetInfo().isTLSSupported() &&
1874 Clause->getClauseKind() == OMPC_copyin)) {
1875 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001876 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001877 for (auto *VarRef : Clause->children()) {
1878 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001879 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001880 }
1881 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001882 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001883 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001884 if (auto *C = OMPClauseWithPreInit::get(Clause))
1885 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001886 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1887 if (auto *E = C->getPostUpdateExpr())
1888 MarkDeclarationsReferencedInExpr(E);
1889 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001890 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001891 if (Clause->getClauseKind() == OMPC_schedule)
1892 SC = cast<OMPScheduleClause>(Clause);
1893 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001894 OC = cast<OMPOrderedClause>(Clause);
1895 else if (Clause->getClauseKind() == OMPC_linear)
1896 LCs.push_back(cast<OMPLinearClause>(Clause));
1897 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001898 // OpenMP, 2.7.1 Loop Construct, Restrictions
1899 // The nonmonotonic modifier cannot be specified if an ordered clause is
1900 // specified.
1901 if (SC &&
1902 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1903 SC->getSecondScheduleModifier() ==
1904 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1905 OC) {
1906 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1907 ? SC->getFirstScheduleModifierLoc()
1908 : SC->getSecondScheduleModifierLoc(),
1909 diag::err_omp_schedule_nonmonotonic_ordered)
1910 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1911 ErrorFound = true;
1912 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001913 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1914 for (auto *C : LCs) {
1915 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1916 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1917 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001918 ErrorFound = true;
1919 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001920 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1921 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1922 OC->getNumForLoops()) {
1923 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1924 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1925 ErrorFound = true;
1926 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001927 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001928 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001929 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001930 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001931 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1932 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
1933 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
1934 // Mark all variables in private list clauses as used in inner region.
1935 // Required for proper codegen of combined directives.
1936 // TODO: add processing for other clauses.
1937 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1938 for (auto *C : PICs) {
1939 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
1940 // Find the particular capture region for the clause if the
1941 // directive is a combined one with multiple capture regions.
1942 // If the directive is not a combined one, the capture region
1943 // associated with the clause is OMPD_unknown and is generated
1944 // only once.
1945 if (CaptureRegion == ThisCaptureRegion ||
1946 CaptureRegion == OMPD_unknown) {
1947 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1948 for (auto *D : DS->decls())
1949 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1950 }
1951 }
1952 }
1953 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001954 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001955 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001956 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001957}
1958
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001959static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1960 OpenMPDirectiveKind CurrentRegion,
1961 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001962 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001963 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001964 if (Stack->getCurScope()) {
1965 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001966 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001967 bool NestingProhibited = false;
1968 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001969 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001970 enum {
1971 NoRecommend,
1972 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001973 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001974 ShouldBeInTargetRegion,
1975 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001976 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001977 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001978 // OpenMP [2.16, Nesting of Regions]
1979 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001980 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001981 // An ordered construct with the simd clause is the only OpenMP
1982 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001983 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001984 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1985 // message.
1986 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1987 ? diag::err_omp_prohibited_region_simd
1988 : diag::warn_omp_nesting_simd);
1989 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001990 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001991 if (ParentRegion == OMPD_atomic) {
1992 // OpenMP [2.16, Nesting of Regions]
1993 // OpenMP constructs may not be nested inside an atomic region.
1994 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1995 return true;
1996 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001997 if (CurrentRegion == OMPD_section) {
1998 // OpenMP [2.7.2, sections Construct, Restrictions]
1999 // Orphaned section directives are prohibited. That is, the section
2000 // directives must appear within the sections construct and must not be
2001 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002002 if (ParentRegion != OMPD_sections &&
2003 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002004 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2005 << (ParentRegion != OMPD_unknown)
2006 << getOpenMPDirectiveName(ParentRegion);
2007 return true;
2008 }
2009 return false;
2010 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002011 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002012 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002013 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002014 if (ParentRegion == OMPD_unknown &&
2015 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002016 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002017 if (CurrentRegion == OMPD_cancellation_point ||
2018 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002019 // OpenMP [2.16, Nesting of Regions]
2020 // A cancellation point construct for which construct-type-clause is
2021 // taskgroup must be nested inside a task construct. A cancellation
2022 // point construct for which construct-type-clause is not taskgroup must
2023 // be closely nested inside an OpenMP construct that matches the type
2024 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002025 // A cancel construct for which construct-type-clause is taskgroup must be
2026 // nested inside a task construct. A cancel construct for which
2027 // construct-type-clause is not taskgroup must be closely nested inside an
2028 // OpenMP construct that matches the type specified in
2029 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002030 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002031 !((CancelRegion == OMPD_parallel &&
2032 (ParentRegion == OMPD_parallel ||
2033 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002034 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002035 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2036 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002037 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2038 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002039 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2040 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002041 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002042 // OpenMP [2.16, Nesting of Regions]
2043 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002044 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002045 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002046 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002047 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2048 // OpenMP [2.16, Nesting of Regions]
2049 // A critical region may not be nested (closely or otherwise) inside a
2050 // critical region with the same name. Note that this restriction is not
2051 // sufficient to prevent deadlock.
2052 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002053 bool DeadLock = Stack->hasDirective(
2054 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2055 const DeclarationNameInfo &DNI,
2056 SourceLocation Loc) -> bool {
2057 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2058 PreviousCriticalLoc = Loc;
2059 return true;
2060 } else
2061 return false;
2062 },
2063 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002064 if (DeadLock) {
2065 SemaRef.Diag(StartLoc,
2066 diag::err_omp_prohibited_region_critical_same_name)
2067 << CurrentName.getName();
2068 if (PreviousCriticalLoc.isValid())
2069 SemaRef.Diag(PreviousCriticalLoc,
2070 diag::note_omp_previous_critical_region);
2071 return true;
2072 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002073 } else if (CurrentRegion == OMPD_barrier) {
2074 // OpenMP [2.16, Nesting of Regions]
2075 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002076 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002077 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2078 isOpenMPTaskingDirective(ParentRegion) ||
2079 ParentRegion == OMPD_master ||
2080 ParentRegion == OMPD_critical ||
2081 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002082 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002083 !isOpenMPParallelDirective(CurrentRegion) &&
2084 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002085 // OpenMP [2.16, Nesting of Regions]
2086 // A worksharing region may not be closely nested inside a worksharing,
2087 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002088 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2089 isOpenMPTaskingDirective(ParentRegion) ||
2090 ParentRegion == OMPD_master ||
2091 ParentRegion == OMPD_critical ||
2092 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002093 Recommend = ShouldBeInParallelRegion;
2094 } else if (CurrentRegion == OMPD_ordered) {
2095 // OpenMP [2.16, Nesting of Regions]
2096 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002097 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002098 // An ordered region must be closely nested inside a loop region (or
2099 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002100 // OpenMP [2.8.1,simd Construct, Restrictions]
2101 // An ordered construct with the simd clause is the only OpenMP construct
2102 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002103 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002104 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002105 !(isOpenMPSimdDirective(ParentRegion) ||
2106 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002107 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002108 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002109 // OpenMP [2.16, Nesting of Regions]
2110 // If specified, a teams construct must be contained within a target
2111 // construct.
2112 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002113 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002114 Recommend = ShouldBeInTargetRegion;
2115 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2116 }
Kelvin Libf594a52016-12-17 05:48:59 +00002117 if (!NestingProhibited &&
2118 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2119 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2120 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002121 // OpenMP [2.16, Nesting of Regions]
2122 // distribute, parallel, parallel sections, parallel workshare, and the
2123 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2124 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002125 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2126 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002127 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002128 }
David Majnemer9d168222016-08-05 17:44:54 +00002129 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002130 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002131 // OpenMP 4.5 [2.17 Nesting of Regions]
2132 // The region associated with the distribute construct must be strictly
2133 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002134 NestingProhibited =
2135 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002136 Recommend = ShouldBeInTeamsRegion;
2137 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002138 if (!NestingProhibited &&
2139 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2140 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2141 // OpenMP 4.5 [2.17 Nesting of Regions]
2142 // If a target, target update, target data, target enter data, or
2143 // target exit data construct is encountered during execution of a
2144 // target region, the behavior is unspecified.
2145 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002146 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2147 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002148 if (isOpenMPTargetExecutionDirective(K)) {
2149 OffendingRegion = K;
2150 return true;
2151 } else
2152 return false;
2153 },
2154 false /* don't skip top directive */);
2155 CloseNesting = false;
2156 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002157 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002158 if (OrphanSeen) {
2159 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2160 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2161 } else {
2162 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2163 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2164 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2165 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002166 return true;
2167 }
2168 }
2169 return false;
2170}
2171
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002172static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2173 ArrayRef<OMPClause *> Clauses,
2174 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2175 bool ErrorFound = false;
2176 unsigned NamedModifiersNumber = 0;
2177 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2178 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002179 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002180 for (const auto *C : Clauses) {
2181 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2182 // At most one if clause without a directive-name-modifier can appear on
2183 // the directive.
2184 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2185 if (FoundNameModifiers[CurNM]) {
2186 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2187 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2188 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2189 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002190 } else if (CurNM != OMPD_unknown) {
2191 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002192 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002193 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002194 FoundNameModifiers[CurNM] = IC;
2195 if (CurNM == OMPD_unknown)
2196 continue;
2197 // Check if the specified name modifier is allowed for the current
2198 // directive.
2199 // At most one if clause with the particular directive-name-modifier can
2200 // appear on the directive.
2201 bool MatchFound = false;
2202 for (auto NM : AllowedNameModifiers) {
2203 if (CurNM == NM) {
2204 MatchFound = true;
2205 break;
2206 }
2207 }
2208 if (!MatchFound) {
2209 S.Diag(IC->getNameModifierLoc(),
2210 diag::err_omp_wrong_if_directive_name_modifier)
2211 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2212 ErrorFound = true;
2213 }
2214 }
2215 }
2216 // If any if clause on the directive includes a directive-name-modifier then
2217 // all if clauses on the directive must include a directive-name-modifier.
2218 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2219 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2220 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2221 diag::err_omp_no_more_if_clause);
2222 } else {
2223 std::string Values;
2224 std::string Sep(", ");
2225 unsigned AllowedCnt = 0;
2226 unsigned TotalAllowedNum =
2227 AllowedNameModifiers.size() - NamedModifiersNumber;
2228 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2229 ++Cnt) {
2230 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2231 if (!FoundNameModifiers[NM]) {
2232 Values += "'";
2233 Values += getOpenMPDirectiveName(NM);
2234 Values += "'";
2235 if (AllowedCnt + 2 == TotalAllowedNum)
2236 Values += " or ";
2237 else if (AllowedCnt + 1 != TotalAllowedNum)
2238 Values += Sep;
2239 ++AllowedCnt;
2240 }
2241 }
2242 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2243 diag::err_omp_unnamed_if_clause)
2244 << (TotalAllowedNum > 1) << Values;
2245 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002246 for (auto Loc : NameModifierLoc) {
2247 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2248 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002249 ErrorFound = true;
2250 }
2251 return ErrorFound;
2252}
2253
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002254StmtResult Sema::ActOnOpenMPExecutableDirective(
2255 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2256 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2257 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002258 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002259 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2260 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002261 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002262
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002263 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002264 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002265 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002266 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002267 if (AStmt) {
2268 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2269
2270 // Check default data sharing attributes for referenced variables.
2271 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002272 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2273 Stmt *S = AStmt;
2274 while (--ThisCaptureLevel >= 0)
2275 S = cast<CapturedStmt>(S)->getCapturedStmt();
2276 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002277 if (DSAChecker.isErrorFound())
2278 return StmtError();
2279 // Generate list of implicitly defined firstprivate variables.
2280 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002281
2282 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2283 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2284 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2285 SourceLocation(), SourceLocation())) {
2286 ClausesWithImplicit.push_back(Implicit);
2287 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2288 DSAChecker.getImplicitFirstprivate().size();
2289 } else
2290 ErrorFound = true;
2291 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002292 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002293
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002294 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002295 switch (Kind) {
2296 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002297 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2298 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002299 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002300 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002301 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002302 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2303 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002304 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002305 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002306 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2307 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002308 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002309 case OMPD_for_simd:
2310 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2311 EndLoc, VarsWithInheritedDSA);
2312 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002313 case OMPD_sections:
2314 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2315 EndLoc);
2316 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002317 case OMPD_section:
2318 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002319 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002320 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2321 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002322 case OMPD_single:
2323 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2324 EndLoc);
2325 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002326 case OMPD_master:
2327 assert(ClausesWithImplicit.empty() &&
2328 "No clauses are allowed for 'omp master' directive");
2329 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2330 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002331 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002332 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2333 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002334 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002335 case OMPD_parallel_for:
2336 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2337 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002338 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002339 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002340 case OMPD_parallel_for_simd:
2341 Res = ActOnOpenMPParallelForSimdDirective(
2342 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002343 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002344 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002345 case OMPD_parallel_sections:
2346 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2347 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002348 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002349 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002350 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002351 Res =
2352 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002353 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002354 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002355 case OMPD_taskyield:
2356 assert(ClausesWithImplicit.empty() &&
2357 "No clauses are allowed for 'omp taskyield' directive");
2358 assert(AStmt == nullptr &&
2359 "No associated statement allowed for 'omp taskyield' directive");
2360 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2361 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002362 case OMPD_barrier:
2363 assert(ClausesWithImplicit.empty() &&
2364 "No clauses are allowed for 'omp barrier' directive");
2365 assert(AStmt == nullptr &&
2366 "No associated statement allowed for 'omp barrier' directive");
2367 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2368 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002369 case OMPD_taskwait:
2370 assert(ClausesWithImplicit.empty() &&
2371 "No clauses are allowed for 'omp taskwait' directive");
2372 assert(AStmt == nullptr &&
2373 "No associated statement allowed for 'omp taskwait' directive");
2374 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2375 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002376 case OMPD_taskgroup:
2377 assert(ClausesWithImplicit.empty() &&
2378 "No clauses are allowed for 'omp taskgroup' directive");
2379 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2380 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002381 case OMPD_flush:
2382 assert(AStmt == nullptr &&
2383 "No associated statement allowed for 'omp flush' directive");
2384 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2385 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002386 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002387 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2388 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002389 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002390 case OMPD_atomic:
2391 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2392 EndLoc);
2393 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002394 case OMPD_teams:
2395 Res =
2396 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2397 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002398 case OMPD_target:
2399 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2400 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002401 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002402 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002403 case OMPD_target_parallel:
2404 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2405 StartLoc, EndLoc);
2406 AllowedNameModifiers.push_back(OMPD_target);
2407 AllowedNameModifiers.push_back(OMPD_parallel);
2408 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002409 case OMPD_target_parallel_for:
2410 Res = ActOnOpenMPTargetParallelForDirective(
2411 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2412 AllowedNameModifiers.push_back(OMPD_target);
2413 AllowedNameModifiers.push_back(OMPD_parallel);
2414 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002415 case OMPD_cancellation_point:
2416 assert(ClausesWithImplicit.empty() &&
2417 "No clauses are allowed for 'omp cancellation point' directive");
2418 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2419 "cancellation point' directive");
2420 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2421 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002422 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002423 assert(AStmt == nullptr &&
2424 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002425 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2426 CancelRegion);
2427 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002428 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002429 case OMPD_target_data:
2430 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2431 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002432 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002433 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002434 case OMPD_target_enter_data:
2435 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2436 EndLoc);
2437 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2438 break;
Samuel Antao72590762016-01-19 20:04:50 +00002439 case OMPD_target_exit_data:
2440 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2441 EndLoc);
2442 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2443 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002444 case OMPD_taskloop:
2445 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2446 EndLoc, VarsWithInheritedDSA);
2447 AllowedNameModifiers.push_back(OMPD_taskloop);
2448 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002449 case OMPD_taskloop_simd:
2450 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2451 EndLoc, VarsWithInheritedDSA);
2452 AllowedNameModifiers.push_back(OMPD_taskloop);
2453 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002454 case OMPD_distribute:
2455 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2456 EndLoc, VarsWithInheritedDSA);
2457 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002458 case OMPD_target_update:
2459 assert(!AStmt && "Statement is not allowed for target update");
2460 Res =
2461 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2462 AllowedNameModifiers.push_back(OMPD_target_update);
2463 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002464 case OMPD_distribute_parallel_for:
2465 Res = ActOnOpenMPDistributeParallelForDirective(
2466 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2467 AllowedNameModifiers.push_back(OMPD_parallel);
2468 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002469 case OMPD_distribute_parallel_for_simd:
2470 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2472 AllowedNameModifiers.push_back(OMPD_parallel);
2473 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002474 case OMPD_distribute_simd:
2475 Res = ActOnOpenMPDistributeSimdDirective(
2476 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2477 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002478 case OMPD_target_parallel_for_simd:
2479 Res = ActOnOpenMPTargetParallelForSimdDirective(
2480 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2481 AllowedNameModifiers.push_back(OMPD_target);
2482 AllowedNameModifiers.push_back(OMPD_parallel);
2483 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002484 case OMPD_target_simd:
2485 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2486 EndLoc, VarsWithInheritedDSA);
2487 AllowedNameModifiers.push_back(OMPD_target);
2488 break;
Kelvin Li02532872016-08-05 14:37:37 +00002489 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002490 Res = ActOnOpenMPTeamsDistributeDirective(
2491 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002492 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002493 case OMPD_teams_distribute_simd:
2494 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2495 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2496 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002497 case OMPD_teams_distribute_parallel_for_simd:
2498 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2500 AllowedNameModifiers.push_back(OMPD_parallel);
2501 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002502 case OMPD_teams_distribute_parallel_for:
2503 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2504 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2505 AllowedNameModifiers.push_back(OMPD_parallel);
2506 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002507 case OMPD_target_teams:
2508 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2509 EndLoc);
2510 AllowedNameModifiers.push_back(OMPD_target);
2511 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002512 case OMPD_target_teams_distribute:
2513 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2515 AllowedNameModifiers.push_back(OMPD_target);
2516 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002517 case OMPD_target_teams_distribute_parallel_for:
2518 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2519 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2520 AllowedNameModifiers.push_back(OMPD_target);
2521 AllowedNameModifiers.push_back(OMPD_parallel);
2522 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002523 case OMPD_target_teams_distribute_parallel_for_simd:
2524 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2525 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2526 AllowedNameModifiers.push_back(OMPD_target);
2527 AllowedNameModifiers.push_back(OMPD_parallel);
2528 break;
Kelvin Lida681182017-01-10 18:08:18 +00002529 case OMPD_target_teams_distribute_simd:
2530 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2531 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2532 AllowedNameModifiers.push_back(OMPD_target);
2533 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002534 case OMPD_declare_target:
2535 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002536 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002537 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002538 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002539 llvm_unreachable("OpenMP Directive is not allowed");
2540 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002541 llvm_unreachable("Unknown OpenMP directive");
2542 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002543
Alexey Bataev4acb8592014-07-07 13:01:15 +00002544 for (auto P : VarsWithInheritedDSA) {
2545 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2546 << P.first << P.second->getSourceRange();
2547 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002548 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2549
2550 if (!AllowedNameModifiers.empty())
2551 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2552 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002553
Alexey Bataeved09d242014-05-28 05:53:51 +00002554 if (ErrorFound)
2555 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002556 return Res;
2557}
2558
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002559Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2560 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002561 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002562 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2563 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002564 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002565 assert(Linears.size() == LinModifiers.size());
2566 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002567 if (!DG || DG.get().isNull())
2568 return DeclGroupPtrTy();
2569
2570 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002571 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002572 return DG;
2573 }
2574 auto *ADecl = DG.get().getSingleDecl();
2575 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2576 ADecl = FTD->getTemplatedDecl();
2577
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002578 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2579 if (!FD) {
2580 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002581 return DeclGroupPtrTy();
2582 }
2583
Alexey Bataev2af33e32016-04-07 12:45:37 +00002584 // OpenMP [2.8.2, declare simd construct, Description]
2585 // The parameter of the simdlen clause must be a constant positive integer
2586 // expression.
2587 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002588 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002589 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002590 // OpenMP [2.8.2, declare simd construct, Description]
2591 // The special this pointer can be used as if was one of the arguments to the
2592 // function in any of the linear, aligned, or uniform clauses.
2593 // The uniform clause declares one or more arguments to have an invariant
2594 // value for all concurrent invocations of the function in the execution of a
2595 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002596 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2597 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002598 for (auto *E : Uniforms) {
2599 E = E->IgnoreParenImpCasts();
2600 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2601 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2602 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2603 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002604 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2605 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002606 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002607 }
2608 if (isa<CXXThisExpr>(E)) {
2609 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002610 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002611 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002612 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2613 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002614 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002615 // OpenMP [2.8.2, declare simd construct, Description]
2616 // The aligned clause declares that the object to which each list item points
2617 // is aligned to the number of bytes expressed in the optional parameter of
2618 // the aligned clause.
2619 // The special this pointer can be used as if was one of the arguments to the
2620 // function in any of the linear, aligned, or uniform clauses.
2621 // The type of list items appearing in the aligned clause must be array,
2622 // pointer, reference to array, or reference to pointer.
2623 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2624 Expr *AlignedThis = nullptr;
2625 for (auto *E : Aligneds) {
2626 E = E->IgnoreParenImpCasts();
2627 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2628 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2629 auto *CanonPVD = PVD->getCanonicalDecl();
2630 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2631 FD->getParamDecl(PVD->getFunctionScopeIndex())
2632 ->getCanonicalDecl() == CanonPVD) {
2633 // OpenMP [2.8.1, simd construct, Restrictions]
2634 // A list-item cannot appear in more than one aligned clause.
2635 if (AlignedArgs.count(CanonPVD) > 0) {
2636 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2637 << 1 << E->getSourceRange();
2638 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2639 diag::note_omp_explicit_dsa)
2640 << getOpenMPClauseName(OMPC_aligned);
2641 continue;
2642 }
2643 AlignedArgs[CanonPVD] = E;
2644 QualType QTy = PVD->getType()
2645 .getNonReferenceType()
2646 .getUnqualifiedType()
2647 .getCanonicalType();
2648 const Type *Ty = QTy.getTypePtrOrNull();
2649 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2650 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2651 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2652 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2653 }
2654 continue;
2655 }
2656 }
2657 if (isa<CXXThisExpr>(E)) {
2658 if (AlignedThis) {
2659 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2660 << 2 << E->getSourceRange();
2661 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2662 << getOpenMPClauseName(OMPC_aligned);
2663 }
2664 AlignedThis = E;
2665 continue;
2666 }
2667 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2668 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2669 }
2670 // The optional parameter of the aligned clause, alignment, must be a constant
2671 // positive integer expression. If no optional parameter is specified,
2672 // implementation-defined default alignments for SIMD instructions on the
2673 // target platforms are assumed.
2674 SmallVector<Expr *, 4> NewAligns;
2675 for (auto *E : Alignments) {
2676 ExprResult Align;
2677 if (E)
2678 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2679 NewAligns.push_back(Align.get());
2680 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002681 // OpenMP [2.8.2, declare simd construct, Description]
2682 // The linear clause declares one or more list items to be private to a SIMD
2683 // lane and to have a linear relationship with respect to the iteration space
2684 // of a loop.
2685 // The special this pointer can be used as if was one of the arguments to the
2686 // function in any of the linear, aligned, or uniform clauses.
2687 // When a linear-step expression is specified in a linear clause it must be
2688 // either a constant integer expression or an integer-typed parameter that is
2689 // specified in a uniform clause on the directive.
2690 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2691 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2692 auto MI = LinModifiers.begin();
2693 for (auto *E : Linears) {
2694 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2695 ++MI;
2696 E = E->IgnoreParenImpCasts();
2697 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2698 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2699 auto *CanonPVD = PVD->getCanonicalDecl();
2700 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2701 FD->getParamDecl(PVD->getFunctionScopeIndex())
2702 ->getCanonicalDecl() == CanonPVD) {
2703 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2704 // A list-item cannot appear in more than one linear clause.
2705 if (LinearArgs.count(CanonPVD) > 0) {
2706 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2707 << getOpenMPClauseName(OMPC_linear)
2708 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2709 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2710 diag::note_omp_explicit_dsa)
2711 << getOpenMPClauseName(OMPC_linear);
2712 continue;
2713 }
2714 // Each argument can appear in at most one uniform or linear clause.
2715 if (UniformedArgs.count(CanonPVD) > 0) {
2716 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2717 << getOpenMPClauseName(OMPC_linear)
2718 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2719 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2720 diag::note_omp_explicit_dsa)
2721 << getOpenMPClauseName(OMPC_uniform);
2722 continue;
2723 }
2724 LinearArgs[CanonPVD] = E;
2725 if (E->isValueDependent() || E->isTypeDependent() ||
2726 E->isInstantiationDependent() ||
2727 E->containsUnexpandedParameterPack())
2728 continue;
2729 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2730 PVD->getOriginalType());
2731 continue;
2732 }
2733 }
2734 if (isa<CXXThisExpr>(E)) {
2735 if (UniformedLinearThis) {
2736 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2737 << getOpenMPClauseName(OMPC_linear)
2738 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2739 << E->getSourceRange();
2740 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2741 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2742 : OMPC_linear);
2743 continue;
2744 }
2745 UniformedLinearThis = E;
2746 if (E->isValueDependent() || E->isTypeDependent() ||
2747 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2748 continue;
2749 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2750 E->getType());
2751 continue;
2752 }
2753 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2754 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2755 }
2756 Expr *Step = nullptr;
2757 Expr *NewStep = nullptr;
2758 SmallVector<Expr *, 4> NewSteps;
2759 for (auto *E : Steps) {
2760 // Skip the same step expression, it was checked already.
2761 if (Step == E || !E) {
2762 NewSteps.push_back(E ? NewStep : nullptr);
2763 continue;
2764 }
2765 Step = E;
2766 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2767 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2768 auto *CanonPVD = PVD->getCanonicalDecl();
2769 if (UniformedArgs.count(CanonPVD) == 0) {
2770 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2771 << Step->getSourceRange();
2772 } else if (E->isValueDependent() || E->isTypeDependent() ||
2773 E->isInstantiationDependent() ||
2774 E->containsUnexpandedParameterPack() ||
2775 CanonPVD->getType()->hasIntegerRepresentation())
2776 NewSteps.push_back(Step);
2777 else {
2778 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2779 << Step->getSourceRange();
2780 }
2781 continue;
2782 }
2783 NewStep = Step;
2784 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2785 !Step->isInstantiationDependent() &&
2786 !Step->containsUnexpandedParameterPack()) {
2787 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2788 .get();
2789 if (NewStep)
2790 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2791 }
2792 NewSteps.push_back(NewStep);
2793 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002794 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2795 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002796 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002797 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2798 const_cast<Expr **>(Linears.data()), Linears.size(),
2799 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2800 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002801 ADecl->addAttr(NewAttr);
2802 return ConvertDeclToDeclGroup(ADecl);
2803}
2804
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002805StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2806 Stmt *AStmt,
2807 SourceLocation StartLoc,
2808 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002809 if (!AStmt)
2810 return StmtError();
2811
Alexey Bataev9959db52014-05-06 10:08:46 +00002812 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2813 // 1.2.2 OpenMP Language Terminology
2814 // Structured block - An executable statement with a single entry at the
2815 // top and a single exit at the bottom.
2816 // The point of exit cannot be a branch out of the structured block.
2817 // longjmp() and throw() must not violate the entry/exit criteria.
2818 CS->getCapturedDecl()->setNothrow();
2819
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002820 getCurFunction()->setHasBranchProtectedScope();
2821
Alexey Bataev25e5b442015-09-15 12:52:43 +00002822 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2823 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002824}
2825
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002826namespace {
2827/// \brief Helper class for checking canonical form of the OpenMP loops and
2828/// extracting iteration space of each loop in the loop nest, that will be used
2829/// for IR generation.
2830class OpenMPIterationSpaceChecker {
2831 /// \brief Reference to Sema.
2832 Sema &SemaRef;
2833 /// \brief A location for diagnostics (when there is no some better location).
2834 SourceLocation DefaultLoc;
2835 /// \brief A location for diagnostics (when increment is not compatible).
2836 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002837 /// \brief A source location for referring to loop init later.
2838 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002839 /// \brief A source location for referring to condition later.
2840 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002841 /// \brief A source location for referring to increment later.
2842 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002843 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002844 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002845 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002846 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002847 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002848 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002849 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002850 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002851 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002852 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002853 /// \brief This flag is true when condition is one of:
2854 /// Var < UB
2855 /// Var <= UB
2856 /// UB > Var
2857 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002858 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002859 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002860 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002861 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002862 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002863
2864public:
2865 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002866 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002867 /// \brief Check init-expr for canonical loop form and save loop counter
2868 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002869 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002870 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2871 /// for less/greater and for strict/non-strict comparison.
2872 bool CheckCond(Expr *S);
2873 /// \brief Check incr-expr for canonical loop form and return true if it
2874 /// does not conform, otherwise save loop step (#Step).
2875 bool CheckInc(Expr *S);
2876 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002877 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002878 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002879 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002880 /// \brief Source range of the loop init.
2881 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2882 /// \brief Source range of the loop condition.
2883 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2884 /// \brief Source range of the loop increment.
2885 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2886 /// \brief True if the step should be subtracted.
2887 bool ShouldSubtractStep() const { return SubtractStep; }
2888 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002889 Expr *
2890 BuildNumIterations(Scope *S, const bool LimitedType,
2891 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002892 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002893 Expr *BuildPreCond(Scope *S, Expr *Cond,
2894 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002895 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002896 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2897 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002898 /// \brief Build reference expression to the private counter be used for
2899 /// codegen.
2900 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002901 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002902 Expr *BuildCounterInit() const;
2903 /// \brief Build step of the counter be used for codegen.
2904 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002905 /// \brief Return true if any expression is dependent.
2906 bool Dependent() const;
2907
2908private:
2909 /// \brief Check the right-hand side of an assignment in the increment
2910 /// expression.
2911 bool CheckIncRHS(Expr *RHS);
2912 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002913 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002914 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002915 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002916 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002917 /// \brief Helper to set loop increment.
2918 bool SetStep(Expr *NewStep, bool Subtract);
2919};
2920
2921bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002922 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002923 assert(!LB && !UB && !Step);
2924 return false;
2925 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002926 return LCDecl->getType()->isDependentType() ||
2927 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2928 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002929}
2930
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002931static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002932 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2933 E = ExprTemp->getSubExpr();
2934
2935 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2936 E = MTE->GetTemporaryExpr();
2937
2938 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2939 E = Binder->getSubExpr();
2940
2941 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2942 E = ICE->getSubExprAsWritten();
2943 return E->IgnoreParens();
2944}
2945
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002946bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2947 Expr *NewLCRefExpr,
2948 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002949 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002950 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002951 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002952 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002953 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002954 LCDecl = getCanonicalDecl(NewLCDecl);
2955 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002956 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2957 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002958 if ((Ctor->isCopyOrMoveConstructor() ||
2959 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2960 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002961 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002962 LB = NewLB;
2963 return false;
2964}
2965
2966bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002967 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002968 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002969 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2970 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002971 if (!NewUB)
2972 return true;
2973 UB = NewUB;
2974 TestIsLessOp = LessOp;
2975 TestIsStrictOp = StrictOp;
2976 ConditionSrcRange = SR;
2977 ConditionLoc = SL;
2978 return false;
2979}
2980
2981bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2982 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002983 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002984 if (!NewStep)
2985 return true;
2986 if (!NewStep->isValueDependent()) {
2987 // Check that the step is integer expression.
2988 SourceLocation StepLoc = NewStep->getLocStart();
2989 ExprResult Val =
2990 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2991 if (Val.isInvalid())
2992 return true;
2993 NewStep = Val.get();
2994
2995 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2996 // If test-expr is of form var relational-op b and relational-op is < or
2997 // <= then incr-expr must cause var to increase on each iteration of the
2998 // loop. If test-expr is of form var relational-op b and relational-op is
2999 // > or >= then incr-expr must cause var to decrease on each iteration of
3000 // the loop.
3001 // If test-expr is of form b relational-op var and relational-op is < or
3002 // <= then incr-expr must cause var to decrease on each iteration of the
3003 // loop. If test-expr is of form b relational-op var and relational-op is
3004 // > or >= then incr-expr must cause var to increase on each iteration of
3005 // the loop.
3006 llvm::APSInt Result;
3007 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3008 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3009 bool IsConstNeg =
3010 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003011 bool IsConstPos =
3012 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003013 bool IsConstZero = IsConstant && !Result.getBoolValue();
3014 if (UB && (IsConstZero ||
3015 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003016 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003017 SemaRef.Diag(NewStep->getExprLoc(),
3018 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003019 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003020 SemaRef.Diag(ConditionLoc,
3021 diag::note_omp_loop_cond_requres_compatible_incr)
3022 << TestIsLessOp << ConditionSrcRange;
3023 return true;
3024 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003025 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003026 NewStep =
3027 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3028 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003029 Subtract = !Subtract;
3030 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003031 }
3032
3033 Step = NewStep;
3034 SubtractStep = Subtract;
3035 return false;
3036}
3037
Alexey Bataev9c821032015-04-30 04:23:23 +00003038bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003039 // Check init-expr for canonical loop form and save loop counter
3040 // variable - #Var and its initialization value - #LB.
3041 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3042 // var = lb
3043 // integer-type var = lb
3044 // random-access-iterator-type var = lb
3045 // pointer-type var = lb
3046 //
3047 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003048 if (EmitDiags) {
3049 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3050 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003051 return true;
3052 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003053 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3054 if (!ExprTemp->cleanupsHaveSideEffects())
3055 S = ExprTemp->getSubExpr();
3056
Alexander Musmana5f070a2014-10-01 06:03:56 +00003057 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003058 if (Expr *E = dyn_cast<Expr>(S))
3059 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003060 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003061 if (BO->getOpcode() == BO_Assign) {
3062 auto *LHS = BO->getLHS()->IgnoreParens();
3063 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3064 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3065 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3066 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3067 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3068 }
3069 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3070 if (ME->isArrow() &&
3071 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3072 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3073 }
3074 }
David Majnemer9d168222016-08-05 17:44:54 +00003075 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003076 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003077 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003078 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003079 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003080 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003081 SemaRef.Diag(S->getLocStart(),
3082 diag::ext_omp_loop_not_canonical_init)
3083 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003084 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003085 }
3086 }
3087 }
David Majnemer9d168222016-08-05 17:44:54 +00003088 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003089 if (CE->getOperator() == OO_Equal) {
3090 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003091 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003092 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3093 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3094 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3095 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3096 }
3097 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3098 if (ME->isArrow() &&
3099 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3100 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3101 }
3102 }
3103 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003104
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003105 if (Dependent() || SemaRef.CurContext->isDependentContext())
3106 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003107 if (EmitDiags) {
3108 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3109 << S->getSourceRange();
3110 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111 return true;
3112}
3113
Alexey Bataev23b69422014-06-18 07:08:49 +00003114/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003115/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003116static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003117 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003118 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003119 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003120 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3121 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003122 if ((Ctor->isCopyOrMoveConstructor() ||
3123 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3124 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003125 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003126 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3127 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3128 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3129 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3130 return getCanonicalDecl(ME->getMemberDecl());
3131 return getCanonicalDecl(VD);
3132 }
3133 }
3134 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3135 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3136 return getCanonicalDecl(ME->getMemberDecl());
3137 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003138}
3139
3140bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3141 // Check test-expr for canonical form, save upper-bound UB, flags for
3142 // less/greater and for strict/non-strict comparison.
3143 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3144 // var relational-op b
3145 // b relational-op var
3146 //
3147 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003148 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003149 return true;
3150 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003151 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003152 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003153 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003154 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003155 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003156 return SetUB(BO->getRHS(),
3157 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3159 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003160 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003161 return SetUB(BO->getLHS(),
3162 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3163 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3164 BO->getSourceRange(), BO->getOperatorLoc());
3165 }
David Majnemer9d168222016-08-05 17:44:54 +00003166 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003167 if (CE->getNumArgs() == 2) {
3168 auto Op = CE->getOperator();
3169 switch (Op) {
3170 case OO_Greater:
3171 case OO_GreaterEqual:
3172 case OO_Less:
3173 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003174 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003175 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3176 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3177 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003178 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003179 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3180 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3181 CE->getOperatorLoc());
3182 break;
3183 default:
3184 break;
3185 }
3186 }
3187 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003188 if (Dependent() || SemaRef.CurContext->isDependentContext())
3189 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003190 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003191 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003192 return true;
3193}
3194
3195bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3196 // RHS of canonical loop form increment can be:
3197 // var + incr
3198 // incr + var
3199 // var - incr
3200 //
3201 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003202 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003203 if (BO->isAdditiveOp()) {
3204 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003205 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003206 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003207 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003208 return SetStep(BO->getLHS(), false);
3209 }
David Majnemer9d168222016-08-05 17:44:54 +00003210 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003211 bool IsAdd = CE->getOperator() == OO_Plus;
3212 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003213 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003214 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003215 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003216 return SetStep(CE->getArg(0), false);
3217 }
3218 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003219 if (Dependent() || SemaRef.CurContext->isDependentContext())
3220 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003221 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003222 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003223 return true;
3224}
3225
3226bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3227 // Check incr-expr for canonical loop form and return true if it
3228 // does not conform.
3229 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3230 // ++var
3231 // var++
3232 // --var
3233 // var--
3234 // var += incr
3235 // var -= incr
3236 // var = var + incr
3237 // var = incr + var
3238 // var = var - incr
3239 //
3240 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003241 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003242 return true;
3243 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003244 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3245 if (!ExprTemp->cleanupsHaveSideEffects())
3246 S = ExprTemp->getSubExpr();
3247
Alexander Musmana5f070a2014-10-01 06:03:56 +00003248 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003249 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003250 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003251 if (UO->isIncrementDecrementOp() &&
3252 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003253 return SetStep(SemaRef
3254 .ActOnIntegerConstant(UO->getLocStart(),
3255 (UO->isDecrementOp() ? -1 : 1))
3256 .get(),
3257 false);
3258 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003259 switch (BO->getOpcode()) {
3260 case BO_AddAssign:
3261 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003262 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003263 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3264 break;
3265 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003266 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003267 return CheckIncRHS(BO->getRHS());
3268 break;
3269 default:
3270 break;
3271 }
David Majnemer9d168222016-08-05 17:44:54 +00003272 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003273 switch (CE->getOperator()) {
3274 case OO_PlusPlus:
3275 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003276 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003277 return SetStep(SemaRef
3278 .ActOnIntegerConstant(
3279 CE->getLocStart(),
3280 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3281 .get(),
3282 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003283 break;
3284 case OO_PlusEqual:
3285 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003286 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003287 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3288 break;
3289 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003290 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003291 return CheckIncRHS(CE->getArg(1));
3292 break;
3293 default:
3294 break;
3295 }
3296 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003297 if (Dependent() || SemaRef.CurContext->isDependentContext())
3298 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003299 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003300 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003301 return true;
3302}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003303
Alexey Bataev5a3af132016-03-29 08:58:54 +00003304static ExprResult
3305tryBuildCapture(Sema &SemaRef, Expr *Capture,
3306 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003307 if (SemaRef.CurContext->isDependentContext())
3308 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003309 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3310 return SemaRef.PerformImplicitConversion(
3311 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3312 /*AllowExplicit=*/true);
3313 auto I = Captures.find(Capture);
3314 if (I != Captures.end())
3315 return buildCapture(SemaRef, Capture, I->second);
3316 DeclRefExpr *Ref = nullptr;
3317 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3318 Captures[Capture] = Ref;
3319 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003320}
3321
Alexander Musmana5f070a2014-10-01 06:03:56 +00003322/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003323Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3324 Scope *S, const bool LimitedType,
3325 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003326 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003327 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003328 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003329 SemaRef.getLangOpts().CPlusPlus) {
3330 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003331 auto *UBExpr = TestIsLessOp ? UB : LB;
3332 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003333 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3334 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003335 if (!Upper || !Lower)
3336 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003337
3338 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3339
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003340 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003341 // BuildBinOp already emitted error, this one is to point user to upper
3342 // and lower bound, and to tell what is passed to 'operator-'.
3343 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3344 << Upper->getSourceRange() << Lower->getSourceRange();
3345 return nullptr;
3346 }
3347 }
3348
3349 if (!Diff.isUsable())
3350 return nullptr;
3351
3352 // Upper - Lower [- 1]
3353 if (TestIsStrictOp)
3354 Diff = SemaRef.BuildBinOp(
3355 S, DefaultLoc, BO_Sub, Diff.get(),
3356 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3357 if (!Diff.isUsable())
3358 return nullptr;
3359
3360 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003361 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3362 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003363 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003364 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003365 if (!Diff.isUsable())
3366 return nullptr;
3367
3368 // Parentheses (for dumping/debugging purposes only).
3369 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3370 if (!Diff.isUsable())
3371 return nullptr;
3372
3373 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003374 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003375 if (!Diff.isUsable())
3376 return nullptr;
3377
Alexander Musman174b3ca2014-10-06 11:16:29 +00003378 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003379 QualType Type = Diff.get()->getType();
3380 auto &C = SemaRef.Context;
3381 bool UseVarType = VarType->hasIntegerRepresentation() &&
3382 C.getTypeSize(Type) > C.getTypeSize(VarType);
3383 if (!Type->isIntegerType() || UseVarType) {
3384 unsigned NewSize =
3385 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3386 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3387 : Type->hasSignedIntegerRepresentation();
3388 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003389 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3390 Diff = SemaRef.PerformImplicitConversion(
3391 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3392 if (!Diff.isUsable())
3393 return nullptr;
3394 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003395 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003396 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003397 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3398 if (NewSize != C.getTypeSize(Type)) {
3399 if (NewSize < C.getTypeSize(Type)) {
3400 assert(NewSize == 64 && "incorrect loop var size");
3401 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3402 << InitSrcRange << ConditionSrcRange;
3403 }
3404 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003405 NewSize, Type->hasSignedIntegerRepresentation() ||
3406 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003407 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3408 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3409 Sema::AA_Converting, true);
3410 if (!Diff.isUsable())
3411 return nullptr;
3412 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003413 }
3414 }
3415
Alexander Musmana5f070a2014-10-01 06:03:56 +00003416 return Diff.get();
3417}
3418
Alexey Bataev5a3af132016-03-29 08:58:54 +00003419Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3420 Scope *S, Expr *Cond,
3421 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003422 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3423 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3424 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003425
Alexey Bataev5a3af132016-03-29 08:58:54 +00003426 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3427 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3428 if (!NewLB.isUsable() || !NewUB.isUsable())
3429 return nullptr;
3430
Alexey Bataev62dbb972015-04-22 11:59:37 +00003431 auto CondExpr = SemaRef.BuildBinOp(
3432 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3433 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003434 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003435 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003436 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3437 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003438 CondExpr = SemaRef.PerformImplicitConversion(
3439 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3440 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003441 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003442 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3443 // Otherwise use original loop conditon and evaluate it in runtime.
3444 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3445}
3446
Alexander Musmana5f070a2014-10-01 06:03:56 +00003447/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003449 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003450 auto *VD = dyn_cast<VarDecl>(LCDecl);
3451 if (!VD) {
3452 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3453 auto *Ref = buildDeclRefExpr(
3454 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003455 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3456 // If the loop control decl is explicitly marked as private, do not mark it
3457 // as captured again.
3458 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3459 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003460 return Ref;
3461 }
3462 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003463 DefaultLoc);
3464}
3465
3466Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003467 if (LCDecl && !LCDecl->isInvalidDecl()) {
3468 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003469 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003470 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3471 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003472 if (PrivateVar->isInvalidDecl())
3473 return nullptr;
3474 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3475 }
3476 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003477}
3478
Samuel Antao4c8035b2016-12-12 18:00:20 +00003479/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003480Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3481
3482/// \brief Build step of the counter be used for codegen.
3483Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3484
3485/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003486struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003487 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003488 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003489 /// \brief This expression calculates the number of iterations in the loop.
3490 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003491 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003492 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003493 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003494 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003495 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003496 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003497 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003498 /// \brief This is step for the #CounterVar used to generate its update:
3499 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003500 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003501 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003502 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003503 /// \brief Source range of the loop init.
3504 SourceRange InitSrcRange;
3505 /// \brief Source range of the loop condition.
3506 SourceRange CondSrcRange;
3507 /// \brief Source range of the loop increment.
3508 SourceRange IncSrcRange;
3509};
3510
Alexey Bataev23b69422014-06-18 07:08:49 +00003511} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003512
Alexey Bataev9c821032015-04-30 04:23:23 +00003513void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3514 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3515 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003516 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3517 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003518 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3519 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003520 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3521 if (auto *D = ISC.GetLoopDecl()) {
3522 auto *VD = dyn_cast<VarDecl>(D);
3523 if (!VD) {
3524 if (auto *Private = IsOpenMPCapturedDecl(D))
3525 VD = Private;
3526 else {
3527 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3528 /*WithInit=*/false);
3529 VD = cast<VarDecl>(Ref->getDecl());
3530 }
3531 }
3532 DSAStack->addLoopControlVariable(D, VD);
3533 }
3534 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003535 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003536 }
3537}
3538
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003539/// \brief Called on a for stmt to check and extract its iteration space
3540/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003541static bool CheckOpenMPIterationSpace(
3542 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3543 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003544 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003545 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003546 LoopIterationSpace &ResultIterSpace,
3547 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003548 // OpenMP [2.6, Canonical Loop Form]
3549 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003550 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003551 if (!For) {
3552 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003553 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3554 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3555 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3556 if (NestedLoopCount > 1) {
3557 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3558 SemaRef.Diag(DSA.getConstructLoc(),
3559 diag::note_omp_collapse_ordered_expr)
3560 << 2 << CollapseLoopCountExpr->getSourceRange()
3561 << OrderedLoopCountExpr->getSourceRange();
3562 else if (CollapseLoopCountExpr)
3563 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3564 diag::note_omp_collapse_ordered_expr)
3565 << 0 << CollapseLoopCountExpr->getSourceRange();
3566 else
3567 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3568 diag::note_omp_collapse_ordered_expr)
3569 << 1 << OrderedLoopCountExpr->getSourceRange();
3570 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003571 return true;
3572 }
3573 assert(For->getBody());
3574
3575 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3576
3577 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003578 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003579 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003580 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003581
3582 bool HasErrors = false;
3583
3584 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003585 if (auto *LCDecl = ISC.GetLoopDecl()) {
3586 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003587
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003588 // OpenMP [2.6, Canonical Loop Form]
3589 // Var is one of the following:
3590 // A variable of signed or unsigned integer type.
3591 // For C++, a variable of a random access iterator type.
3592 // For C, a variable of a pointer type.
3593 auto VarType = LCDecl->getType().getNonReferenceType();
3594 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3595 !VarType->isPointerType() &&
3596 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3597 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3598 << SemaRef.getLangOpts().CPlusPlus;
3599 HasErrors = true;
3600 }
3601
3602 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3603 // a Construct
3604 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3605 // parallel for construct is (are) private.
3606 // The loop iteration variable in the associated for-loop of a simd
3607 // construct with just one associated for-loop is linear with a
3608 // constant-linear-step that is the increment of the associated for-loop.
3609 // Exclude loop var from the list of variables with implicitly defined data
3610 // sharing attributes.
3611 VarsWithImplicitDSA.erase(LCDecl);
3612
3613 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3614 // in a Construct, C/C++].
3615 // The loop iteration variable in the associated for-loop of a simd
3616 // construct with just one associated for-loop may be listed in a linear
3617 // clause with a constant-linear-step that is the increment of the
3618 // associated for-loop.
3619 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3620 // parallel for construct may be listed in a private or lastprivate clause.
3621 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3622 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3623 // declared in the loop and it is predetermined as a private.
3624 auto PredeterminedCKind =
3625 isOpenMPSimdDirective(DKind)
3626 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3627 : OMPC_private;
3628 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3629 DVar.CKind != PredeterminedCKind) ||
3630 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3631 isOpenMPDistributeDirective(DKind)) &&
3632 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3633 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3634 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3635 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3636 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3637 << getOpenMPClauseName(PredeterminedCKind);
3638 if (DVar.RefExpr == nullptr)
3639 DVar.CKind = PredeterminedCKind;
3640 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3641 HasErrors = true;
3642 } else if (LoopDeclRefExpr != nullptr) {
3643 // Make the loop iteration variable private (for worksharing constructs),
3644 // linear (for simd directives with the only one associated loop) or
3645 // lastprivate (for simd directives with several collapsed or ordered
3646 // loops).
3647 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003648 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3649 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003650 /*FromParent=*/false);
3651 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3652 }
3653
3654 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3655
3656 // Check test-expr.
3657 HasErrors |= ISC.CheckCond(For->getCond());
3658
3659 // Check incr-expr.
3660 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003661 }
3662
Alexander Musmana5f070a2014-10-01 06:03:56 +00003663 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003664 return HasErrors;
3665
Alexander Musmana5f070a2014-10-01 06:03:56 +00003666 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003667 ResultIterSpace.PreCond =
3668 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003669 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003670 DSA.getCurScope(),
3671 (isOpenMPWorksharingDirective(DKind) ||
3672 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3673 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003674 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003675 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003676 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3677 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3678 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3679 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3680 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3681 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3682
Alexey Bataev62dbb972015-04-22 11:59:37 +00003683 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3684 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003685 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003686 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003687 ResultIterSpace.CounterInit == nullptr ||
3688 ResultIterSpace.CounterStep == nullptr);
3689
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003690 return HasErrors;
3691}
3692
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003693/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003694static ExprResult
3695BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3696 ExprResult Start,
3697 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003698 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003699 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3700 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003701 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003702 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003703 VarRef.get()->getType())) {
3704 NewStart = SemaRef.PerformImplicitConversion(
3705 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3706 /*AllowExplicit=*/true);
3707 if (!NewStart.isUsable())
3708 return ExprError();
3709 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003710
3711 auto Init =
3712 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3713 return Init;
3714}
3715
Alexander Musmana5f070a2014-10-01 06:03:56 +00003716/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003717static ExprResult
3718BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3719 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3720 ExprResult Step, bool Subtract,
3721 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003722 // Add parentheses (for debugging purposes only).
3723 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3724 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3725 !Step.isUsable())
3726 return ExprError();
3727
Alexey Bataev5a3af132016-03-29 08:58:54 +00003728 ExprResult NewStep = Step;
3729 if (Captures)
3730 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003731 if (NewStep.isInvalid())
3732 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003733 ExprResult Update =
3734 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003735 if (!Update.isUsable())
3736 return ExprError();
3737
Alexey Bataevc0214e02016-02-16 12:13:49 +00003738 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3739 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003740 ExprResult NewStart = Start;
3741 if (Captures)
3742 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003743 if (NewStart.isInvalid())
3744 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003745
Alexey Bataevc0214e02016-02-16 12:13:49 +00003746 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3747 ExprResult SavedUpdate = Update;
3748 ExprResult UpdateVal;
3749 if (VarRef.get()->getType()->isOverloadableType() ||
3750 NewStart.get()->getType()->isOverloadableType() ||
3751 Update.get()->getType()->isOverloadableType()) {
3752 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3753 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3754 Update =
3755 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3756 if (Update.isUsable()) {
3757 UpdateVal =
3758 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3759 VarRef.get(), SavedUpdate.get());
3760 if (UpdateVal.isUsable()) {
3761 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3762 UpdateVal.get());
3763 }
3764 }
3765 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3766 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003767
Alexey Bataevc0214e02016-02-16 12:13:49 +00003768 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3769 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3770 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3771 NewStart.get(), SavedUpdate.get());
3772 if (!Update.isUsable())
3773 return ExprError();
3774
Alexey Bataev11481f52016-02-17 10:29:05 +00003775 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3776 VarRef.get()->getType())) {
3777 Update = SemaRef.PerformImplicitConversion(
3778 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3779 if (!Update.isUsable())
3780 return ExprError();
3781 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003782
3783 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3784 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003785 return Update;
3786}
3787
3788/// \brief Convert integer expression \a E to make it have at least \a Bits
3789/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003790static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791 if (E == nullptr)
3792 return ExprError();
3793 auto &C = SemaRef.Context;
3794 QualType OldType = E->getType();
3795 unsigned HasBits = C.getTypeSize(OldType);
3796 if (HasBits >= Bits)
3797 return ExprResult(E);
3798 // OK to convert to signed, because new type has more bits than old.
3799 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3800 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3801 true);
3802}
3803
3804/// \brief Check if the given expression \a E is a constant integer that fits
3805/// into \a Bits bits.
3806static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3807 if (E == nullptr)
3808 return false;
3809 llvm::APSInt Result;
3810 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3811 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3812 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003813}
3814
Alexey Bataev5a3af132016-03-29 08:58:54 +00003815/// Build preinits statement for the given declarations.
3816static Stmt *buildPreInits(ASTContext &Context,
3817 SmallVectorImpl<Decl *> &PreInits) {
3818 if (!PreInits.empty()) {
3819 return new (Context) DeclStmt(
3820 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3821 SourceLocation(), SourceLocation());
3822 }
3823 return nullptr;
3824}
3825
3826/// Build preinits statement for the given declarations.
3827static Stmt *buildPreInits(ASTContext &Context,
3828 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3829 if (!Captures.empty()) {
3830 SmallVector<Decl *, 16> PreInits;
3831 for (auto &Pair : Captures)
3832 PreInits.push_back(Pair.second->getDecl());
3833 return buildPreInits(Context, PreInits);
3834 }
3835 return nullptr;
3836}
3837
3838/// Build postupdate expression for the given list of postupdates expressions.
3839static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3840 Expr *PostUpdate = nullptr;
3841 if (!PostUpdates.empty()) {
3842 for (auto *E : PostUpdates) {
3843 Expr *ConvE = S.BuildCStyleCastExpr(
3844 E->getExprLoc(),
3845 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3846 E->getExprLoc(), E)
3847 .get();
3848 PostUpdate = PostUpdate
3849 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3850 PostUpdate, ConvE)
3851 .get()
3852 : ConvE;
3853 }
3854 }
3855 return PostUpdate;
3856}
3857
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003858/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003859/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3860/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003861static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003862CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3863 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3864 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003865 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003866 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003867 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003868 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003869 // Found 'collapse' clause - calculate collapse number.
3870 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003871 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003872 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003873 }
3874 if (OrderedLoopCountExpr) {
3875 // Found 'ordered' clause - calculate collapse number.
3876 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003877 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3878 if (Result.getLimitedValue() < NestedLoopCount) {
3879 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3880 diag::err_omp_wrong_ordered_loop_count)
3881 << OrderedLoopCountExpr->getSourceRange();
3882 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3883 diag::note_collapse_loop_count)
3884 << CollapseLoopCountExpr->getSourceRange();
3885 }
3886 NestedLoopCount = Result.getLimitedValue();
3887 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003888 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003889 // This is helper routine for loop directives (e.g., 'for', 'simd',
3890 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003891 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892 SmallVector<LoopIterationSpace, 4> IterSpaces;
3893 IterSpaces.resize(NestedLoopCount);
3894 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003895 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003896 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003897 NestedLoopCount, CollapseLoopCountExpr,
3898 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003899 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003900 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003901 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003902 // OpenMP [2.8.1, simd construct, Restrictions]
3903 // All loops associated with the construct must be perfectly nested; that
3904 // is, there must be no intervening code nor any OpenMP directive between
3905 // any two loops.
3906 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003907 }
3908
Alexander Musmana5f070a2014-10-01 06:03:56 +00003909 Built.clear(/* size */ NestedLoopCount);
3910
3911 if (SemaRef.CurContext->isDependentContext())
3912 return NestedLoopCount;
3913
3914 // An example of what is generated for the following code:
3915 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003916 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003917 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003918 // for (k = 0; k < NK; ++k)
3919 // for (j = J0; j < NJ; j+=2) {
3920 // <loop body>
3921 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003922 //
3923 // We generate the code below.
3924 // Note: the loop body may be outlined in CodeGen.
3925 // Note: some counters may be C++ classes, operator- is used to find number of
3926 // iterations and operator+= to calculate counter value.
3927 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3928 // or i64 is currently supported).
3929 //
3930 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3931 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3932 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3933 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3934 // // similar updates for vars in clauses (e.g. 'linear')
3935 // <loop body (using local i and j)>
3936 // }
3937 // i = NI; // assign final values of counters
3938 // j = NJ;
3939 //
3940
3941 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3942 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003943 // Precondition tests if there is at least one iteration (all conditions are
3944 // true).
3945 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003946 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003947 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003948 32 /* Bits */, SemaRef
3949 .PerformImplicitConversion(
3950 N0->IgnoreImpCasts(), N0->getType(),
3951 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003952 .get(),
3953 SemaRef);
3954 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003955 64 /* Bits */, SemaRef
3956 .PerformImplicitConversion(
3957 N0->IgnoreImpCasts(), N0->getType(),
3958 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003959 .get(),
3960 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003961
3962 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3963 return NestedLoopCount;
3964
3965 auto &C = SemaRef.Context;
3966 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3967
3968 Scope *CurScope = DSA.getCurScope();
3969 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003970 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003971 PreCond =
3972 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3973 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003974 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003975 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003976 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003977 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3978 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003979 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003980 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003981 SemaRef
3982 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3983 Sema::AA_Converting,
3984 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003985 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003986 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003987 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003988 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003989 SemaRef
3990 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3991 Sema::AA_Converting,
3992 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003993 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003994 }
3995
3996 // Choose either the 32-bit or 64-bit version.
3997 ExprResult LastIteration = LastIteration64;
3998 if (LastIteration32.isUsable() &&
3999 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4000 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4001 FitsInto(
4002 32 /* Bits */,
4003 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4004 LastIteration64.get(), SemaRef)))
4005 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004006 QualType VType = LastIteration.get()->getType();
4007 QualType RealVType = VType;
4008 QualType StrideVType = VType;
4009 if (isOpenMPTaskLoopDirective(DKind)) {
4010 VType =
4011 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4012 StrideVType =
4013 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4014 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004015
4016 if (!LastIteration.isUsable())
4017 return 0;
4018
4019 // Save the number of iterations.
4020 ExprResult NumIterations = LastIteration;
4021 {
4022 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004023 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4024 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004025 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4026 if (!LastIteration.isUsable())
4027 return 0;
4028 }
4029
4030 // Calculate the last iteration number beforehand instead of doing this on
4031 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4032 llvm::APSInt Result;
4033 bool IsConstant =
4034 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4035 ExprResult CalcLastIteration;
4036 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004037 ExprResult SaveRef =
4038 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004039 LastIteration = SaveRef;
4040
4041 // Prepare SaveRef + 1.
4042 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004043 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004044 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4045 if (!NumIterations.isUsable())
4046 return 0;
4047 }
4048
4049 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4050
David Majnemer9d168222016-08-05 17:44:54 +00004051 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00004052 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004053 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4054 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004055 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004056 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4057 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004058 SemaRef.AddInitializerToDecl(LBDecl,
4059 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4060 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004061
4062 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004063 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4064 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004065 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004066 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004067
4068 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4069 // This will be used to implement clause 'lastprivate'.
4070 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004071 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4072 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004073 SemaRef.AddInitializerToDecl(ILDecl,
4074 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4075 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004076
4077 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004078 VarDecl *STDecl =
4079 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4080 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004081 SemaRef.AddInitializerToDecl(STDecl,
4082 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4083 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004084
4085 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004086 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004087 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4088 UB.get(), LastIteration.get());
4089 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4090 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4091 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4092 CondOp.get());
4093 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004094
4095 // If we have a combined directive that combines 'distribute', 'for' or
4096 // 'simd' we need to be able to access the bounds of the schedule of the
4097 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4098 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4099 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4100 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4101
4102 // We expect to have at least 2 more parameters than the 'parallel'
4103 // directive does - the lower and upper bounds of the previous schedule.
4104 assert(CD->getNumParams() >= 4 &&
4105 "Unexpected number of parameters in loop combined directive");
4106
4107 // Set the proper type for the bounds given what we learned from the
4108 // enclosed loops.
4109 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4110 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4111
4112 // Previous lower and upper bounds are obtained from the region
4113 // parameters.
4114 PrevLB =
4115 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4116 PrevUB =
4117 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4118 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004119 }
4120
4121 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004122 ExprResult IV;
4123 ExprResult Init;
4124 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004125 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4126 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004127 Expr *RHS =
4128 (isOpenMPWorksharingDirective(DKind) ||
4129 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4130 ? LB.get()
4131 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004132 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4133 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004134 }
4135
Alexander Musmanc6388682014-12-15 07:07:06 +00004136 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004137 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004138 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004139 (isOpenMPWorksharingDirective(DKind) ||
4140 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004141 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4142 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4143 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004144
4145 // Loop increment (IV = IV + 1)
4146 SourceLocation IncLoc;
4147 ExprResult Inc =
4148 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4149 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4150 if (!Inc.isUsable())
4151 return 0;
4152 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004153 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4154 if (!Inc.isUsable())
4155 return 0;
4156
4157 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4158 // Used for directives with static scheduling.
4159 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004160 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4161 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004162 // LB + ST
4163 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4164 if (!NextLB.isUsable())
4165 return 0;
4166 // LB = LB + ST
4167 NextLB =
4168 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4169 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4170 if (!NextLB.isUsable())
4171 return 0;
4172 // UB + ST
4173 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4174 if (!NextUB.isUsable())
4175 return 0;
4176 // UB = UB + ST
4177 NextUB =
4178 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4179 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4180 if (!NextUB.isUsable())
4181 return 0;
4182 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183
Carlo Bertolli8429d812017-02-17 21:29:13 +00004184 // Create: increment expression for distribute loop when combined in a same
4185 // directive with for as IV = IV + ST; ensure upper bound expression based
4186 // on PrevUB instead of NumIterations - used to implement 'for' when found
4187 // in combination with 'distribute', like in 'distribute parallel for'
4188 SourceLocation DistIncLoc;
4189 ExprResult DistCond, DistInc, PrevEUB;
4190 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4191 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4192 assert(DistCond.isUsable() && "distribute cond expr was not built");
4193
4194 DistInc =
4195 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4196 assert(DistInc.isUsable() && "distribute inc expr was not built");
4197 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4198 DistInc.get());
4199 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4200 assert(DistInc.isUsable() && "distribute inc expr was not built");
4201
4202 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4203 // construct
4204 SourceLocation DistEUBLoc;
4205 ExprResult IsUBGreater =
4206 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4207 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4208 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4209 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4210 CondOp.get());
4211 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4212 }
4213
Alexander Musmana5f070a2014-10-01 06:03:56 +00004214 // Build updates and final values of the loop counters.
4215 bool HasErrors = false;
4216 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004217 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004218 Built.Updates.resize(NestedLoopCount);
4219 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004220 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004221 {
4222 ExprResult Div;
4223 // Go from inner nested loop to outer.
4224 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4225 LoopIterationSpace &IS = IterSpaces[Cnt];
4226 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4227 // Build: Iter = (IV / Div) % IS.NumIters
4228 // where Div is product of previous iterations' IS.NumIters.
4229 ExprResult Iter;
4230 if (Div.isUsable()) {
4231 Iter =
4232 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4233 } else {
4234 Iter = IV;
4235 assert((Cnt == (int)NestedLoopCount - 1) &&
4236 "unusable div expected on first iteration only");
4237 }
4238
4239 if (Cnt != 0 && Iter.isUsable())
4240 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4241 IS.NumIterations);
4242 if (!Iter.isUsable()) {
4243 HasErrors = true;
4244 break;
4245 }
4246
Alexey Bataev39f915b82015-05-08 10:41:21 +00004247 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004248 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4249 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4250 IS.CounterVar->getExprLoc(),
4251 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004252 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004253 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004254 if (!Init.isUsable()) {
4255 HasErrors = true;
4256 break;
4257 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004258 ExprResult Update = BuildCounterUpdate(
4259 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4260 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004261 if (!Update.isUsable()) {
4262 HasErrors = true;
4263 break;
4264 }
4265
4266 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4267 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004268 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004269 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004270 if (!Final.isUsable()) {
4271 HasErrors = true;
4272 break;
4273 }
4274
4275 // Build Div for the next iteration: Div <- Div * IS.NumIters
4276 if (Cnt != 0) {
4277 if (Div.isUnset())
4278 Div = IS.NumIterations;
4279 else
4280 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4281 IS.NumIterations);
4282
4283 // Add parentheses (for debugging purposes only).
4284 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004285 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004286 if (!Div.isUsable()) {
4287 HasErrors = true;
4288 break;
4289 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004290 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004291 }
4292 if (!Update.isUsable() || !Final.isUsable()) {
4293 HasErrors = true;
4294 break;
4295 }
4296 // Save results
4297 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004298 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004299 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004300 Built.Updates[Cnt] = Update.get();
4301 Built.Finals[Cnt] = Final.get();
4302 }
4303 }
4304
4305 if (HasErrors)
4306 return 0;
4307
4308 // Save results
4309 Built.IterationVarRef = IV.get();
4310 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004311 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004312 Built.CalcLastIteration =
4313 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004314 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004315 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004316 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004317 Built.Init = Init.get();
4318 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004319 Built.LB = LB.get();
4320 Built.UB = UB.get();
4321 Built.IL = IL.get();
4322 Built.ST = ST.get();
4323 Built.EUB = EUB.get();
4324 Built.NLB = NextLB.get();
4325 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004326 Built.PrevLB = PrevLB.get();
4327 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004328 Built.DistInc = DistInc.get();
4329 Built.PrevEUB = PrevEUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004330
Alexey Bataev8b427062016-05-25 12:36:08 +00004331 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4332 // Fill data for doacross depend clauses.
4333 for (auto Pair : DSA.getDoacrossDependClauses()) {
4334 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4335 Pair.first->setCounterValue(CounterVal);
4336 else {
4337 if (NestedLoopCount != Pair.second.size() ||
4338 NestedLoopCount != LoopMultipliers.size() + 1) {
4339 // Erroneous case - clause has some problems.
4340 Pair.first->setCounterValue(CounterVal);
4341 continue;
4342 }
4343 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4344 auto I = Pair.second.rbegin();
4345 auto IS = IterSpaces.rbegin();
4346 auto ILM = LoopMultipliers.rbegin();
4347 Expr *UpCounterVal = CounterVal;
4348 Expr *Multiplier = nullptr;
4349 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4350 if (I->first) {
4351 assert(IS->CounterStep);
4352 Expr *NormalizedOffset =
4353 SemaRef
4354 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4355 I->first, IS->CounterStep)
4356 .get();
4357 if (Multiplier) {
4358 NormalizedOffset =
4359 SemaRef
4360 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4361 NormalizedOffset, Multiplier)
4362 .get();
4363 }
4364 assert(I->second == OO_Plus || I->second == OO_Minus);
4365 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004366 UpCounterVal = SemaRef
4367 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4368 UpCounterVal, NormalizedOffset)
4369 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004370 }
4371 Multiplier = *ILM;
4372 ++I;
4373 ++IS;
4374 ++ILM;
4375 }
4376 Pair.first->setCounterValue(UpCounterVal);
4377 }
4378 }
4379
Alexey Bataevabfc0692014-06-25 06:52:00 +00004380 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004381}
4382
Alexey Bataev10e775f2015-07-30 11:36:16 +00004383static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004384 auto CollapseClauses =
4385 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4386 if (CollapseClauses.begin() != CollapseClauses.end())
4387 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004388 return nullptr;
4389}
4390
Alexey Bataev10e775f2015-07-30 11:36:16 +00004391static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004392 auto OrderedClauses =
4393 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4394 if (OrderedClauses.begin() != OrderedClauses.end())
4395 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004396 return nullptr;
4397}
4398
Kelvin Lic5609492016-07-15 04:39:07 +00004399static bool checkSimdlenSafelenSpecified(Sema &S,
4400 const ArrayRef<OMPClause *> Clauses) {
4401 OMPSafelenClause *Safelen = nullptr;
4402 OMPSimdlenClause *Simdlen = nullptr;
4403
4404 for (auto *Clause : Clauses) {
4405 if (Clause->getClauseKind() == OMPC_safelen)
4406 Safelen = cast<OMPSafelenClause>(Clause);
4407 else if (Clause->getClauseKind() == OMPC_simdlen)
4408 Simdlen = cast<OMPSimdlenClause>(Clause);
4409 if (Safelen && Simdlen)
4410 break;
4411 }
4412
4413 if (Simdlen && Safelen) {
4414 llvm::APSInt SimdlenRes, SafelenRes;
4415 auto SimdlenLength = Simdlen->getSimdlen();
4416 auto SafelenLength = Safelen->getSafelen();
4417 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4418 SimdlenLength->isInstantiationDependent() ||
4419 SimdlenLength->containsUnexpandedParameterPack())
4420 return false;
4421 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4422 SafelenLength->isInstantiationDependent() ||
4423 SafelenLength->containsUnexpandedParameterPack())
4424 return false;
4425 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4426 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4427 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4428 // If both simdlen and safelen clauses are specified, the value of the
4429 // simdlen parameter must be less than or equal to the value of the safelen
4430 // parameter.
4431 if (SimdlenRes > SafelenRes) {
4432 S.Diag(SimdlenLength->getExprLoc(),
4433 diag::err_omp_wrong_simdlen_safelen_values)
4434 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4435 return true;
4436 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004437 }
4438 return false;
4439}
4440
Alexey Bataev4acb8592014-07-07 13:01:15 +00004441StmtResult Sema::ActOnOpenMPSimdDirective(
4442 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4443 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004444 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004445 if (!AStmt)
4446 return StmtError();
4447
4448 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004449 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004450 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4451 // define the nested loops number.
4452 unsigned NestedLoopCount = CheckOpenMPLoop(
4453 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4454 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004455 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004456 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004457
Alexander Musmana5f070a2014-10-01 06:03:56 +00004458 assert((CurContext->isDependentContext() || B.builtAll()) &&
4459 "omp simd loop exprs were not built");
4460
Alexander Musman3276a272015-03-21 10:12:56 +00004461 if (!CurContext->isDependentContext()) {
4462 // Finalize the clauses that need pre-built expressions for CodeGen.
4463 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004464 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004465 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004466 B.NumIterations, *this, CurScope,
4467 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004468 return StmtError();
4469 }
4470 }
4471
Kelvin Lic5609492016-07-15 04:39:07 +00004472 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004473 return StmtError();
4474
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004475 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004476 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4477 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004478}
4479
Alexey Bataev4acb8592014-07-07 13:01:15 +00004480StmtResult Sema::ActOnOpenMPForDirective(
4481 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4482 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004483 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004484 if (!AStmt)
4485 return StmtError();
4486
4487 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004488 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004489 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4490 // define the nested loops number.
4491 unsigned NestedLoopCount = CheckOpenMPLoop(
4492 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4493 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004494 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004495 return StmtError();
4496
Alexander Musmana5f070a2014-10-01 06:03:56 +00004497 assert((CurContext->isDependentContext() || B.builtAll()) &&
4498 "omp for loop exprs were not built");
4499
Alexey Bataev54acd402015-08-04 11:18:19 +00004500 if (!CurContext->isDependentContext()) {
4501 // Finalize the clauses that need pre-built expressions for CodeGen.
4502 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004503 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004504 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004505 B.NumIterations, *this, CurScope,
4506 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004507 return StmtError();
4508 }
4509 }
4510
Alexey Bataevf29276e2014-06-18 04:14:57 +00004511 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004512 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004513 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004514}
4515
Alexander Musmanf82886e2014-09-18 05:12:34 +00004516StmtResult Sema::ActOnOpenMPForSimdDirective(
4517 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4518 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004519 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004520 if (!AStmt)
4521 return StmtError();
4522
4523 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004524 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004525 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4526 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004527 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004528 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4529 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4530 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004531 if (NestedLoopCount == 0)
4532 return StmtError();
4533
Alexander Musmanc6388682014-12-15 07:07:06 +00004534 assert((CurContext->isDependentContext() || B.builtAll()) &&
4535 "omp for simd loop exprs were not built");
4536
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004537 if (!CurContext->isDependentContext()) {
4538 // Finalize the clauses that need pre-built expressions for CodeGen.
4539 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004540 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004541 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004542 B.NumIterations, *this, CurScope,
4543 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004544 return StmtError();
4545 }
4546 }
4547
Kelvin Lic5609492016-07-15 04:39:07 +00004548 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004549 return StmtError();
4550
Alexander Musmanf82886e2014-09-18 05:12:34 +00004551 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004552 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4553 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004554}
4555
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004556StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4557 Stmt *AStmt,
4558 SourceLocation StartLoc,
4559 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004560 if (!AStmt)
4561 return StmtError();
4562
4563 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004564 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004565 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004566 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004567 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004568 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004569 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004570 return StmtError();
4571 // All associated statements must be '#pragma omp section' except for
4572 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004573 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004574 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4575 if (SectionStmt)
4576 Diag(SectionStmt->getLocStart(),
4577 diag::err_omp_sections_substmt_not_section);
4578 return StmtError();
4579 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004580 cast<OMPSectionDirective>(SectionStmt)
4581 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004582 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004583 } else {
4584 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4585 return StmtError();
4586 }
4587
4588 getCurFunction()->setHasBranchProtectedScope();
4589
Alexey Bataev25e5b442015-09-15 12:52:43 +00004590 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4591 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004592}
4593
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004594StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4595 SourceLocation StartLoc,
4596 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004597 if (!AStmt)
4598 return StmtError();
4599
4600 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004601
4602 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004603 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004604
Alexey Bataev25e5b442015-09-15 12:52:43 +00004605 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4606 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004607}
4608
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004609StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4610 Stmt *AStmt,
4611 SourceLocation StartLoc,
4612 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004613 if (!AStmt)
4614 return StmtError();
4615
4616 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004617
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004618 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004619
Alexey Bataev3255bf32015-01-19 05:20:46 +00004620 // OpenMP [2.7.3, single Construct, Restrictions]
4621 // The copyprivate clause must not be used with the nowait clause.
4622 OMPClause *Nowait = nullptr;
4623 OMPClause *Copyprivate = nullptr;
4624 for (auto *Clause : Clauses) {
4625 if (Clause->getClauseKind() == OMPC_nowait)
4626 Nowait = Clause;
4627 else if (Clause->getClauseKind() == OMPC_copyprivate)
4628 Copyprivate = Clause;
4629 if (Copyprivate && Nowait) {
4630 Diag(Copyprivate->getLocStart(),
4631 diag::err_omp_single_copyprivate_with_nowait);
4632 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4633 return StmtError();
4634 }
4635 }
4636
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004637 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4638}
4639
Alexander Musman80c22892014-07-17 08:54:58 +00004640StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4641 SourceLocation StartLoc,
4642 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004643 if (!AStmt)
4644 return StmtError();
4645
4646 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004647
4648 getCurFunction()->setHasBranchProtectedScope();
4649
4650 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4651}
4652
Alexey Bataev28c75412015-12-15 08:19:24 +00004653StmtResult Sema::ActOnOpenMPCriticalDirective(
4654 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4655 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004656 if (!AStmt)
4657 return StmtError();
4658
4659 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004660
Alexey Bataev28c75412015-12-15 08:19:24 +00004661 bool ErrorFound = false;
4662 llvm::APSInt Hint;
4663 SourceLocation HintLoc;
4664 bool DependentHint = false;
4665 for (auto *C : Clauses) {
4666 if (C->getClauseKind() == OMPC_hint) {
4667 if (!DirName.getName()) {
4668 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4669 ErrorFound = true;
4670 }
4671 Expr *E = cast<OMPHintClause>(C)->getHint();
4672 if (E->isTypeDependent() || E->isValueDependent() ||
4673 E->isInstantiationDependent())
4674 DependentHint = true;
4675 else {
4676 Hint = E->EvaluateKnownConstInt(Context);
4677 HintLoc = C->getLocStart();
4678 }
4679 }
4680 }
4681 if (ErrorFound)
4682 return StmtError();
4683 auto Pair = DSAStack->getCriticalWithHint(DirName);
4684 if (Pair.first && DirName.getName() && !DependentHint) {
4685 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4686 Diag(StartLoc, diag::err_omp_critical_with_hint);
4687 if (HintLoc.isValid()) {
4688 Diag(HintLoc, diag::note_omp_critical_hint_here)
4689 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4690 } else
4691 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4692 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4693 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4694 << 1
4695 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4696 /*Radix=*/10, /*Signed=*/false);
4697 } else
4698 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4699 }
4700 }
4701
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004702 getCurFunction()->setHasBranchProtectedScope();
4703
Alexey Bataev28c75412015-12-15 08:19:24 +00004704 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4705 Clauses, AStmt);
4706 if (!Pair.first && DirName.getName() && !DependentHint)
4707 DSAStack->addCriticalWithHint(Dir, Hint);
4708 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004709}
4710
Alexey Bataev4acb8592014-07-07 13:01:15 +00004711StmtResult Sema::ActOnOpenMPParallelForDirective(
4712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4713 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004714 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004715 if (!AStmt)
4716 return StmtError();
4717
Alexey Bataev4acb8592014-07-07 13:01:15 +00004718 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4719 // 1.2.2 OpenMP Language Terminology
4720 // Structured block - An executable statement with a single entry at the
4721 // top and a single exit at the bottom.
4722 // The point of exit cannot be a branch out of the structured block.
4723 // longjmp() and throw() must not violate the entry/exit criteria.
4724 CS->getCapturedDecl()->setNothrow();
4725
Alexander Musmanc6388682014-12-15 07:07:06 +00004726 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004727 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4728 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004729 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004730 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4731 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4732 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004733 if (NestedLoopCount == 0)
4734 return StmtError();
4735
Alexander Musmana5f070a2014-10-01 06:03:56 +00004736 assert((CurContext->isDependentContext() || B.builtAll()) &&
4737 "omp parallel for loop exprs were not built");
4738
Alexey Bataev54acd402015-08-04 11:18:19 +00004739 if (!CurContext->isDependentContext()) {
4740 // Finalize the clauses that need pre-built expressions for CodeGen.
4741 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004742 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004743 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004744 B.NumIterations, *this, CurScope,
4745 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004746 return StmtError();
4747 }
4748 }
4749
Alexey Bataev4acb8592014-07-07 13:01:15 +00004750 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004751 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004752 NestedLoopCount, Clauses, AStmt, B,
4753 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004754}
4755
Alexander Musmane4e893b2014-09-23 09:33:00 +00004756StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4758 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004759 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004760 if (!AStmt)
4761 return StmtError();
4762
Alexander Musmane4e893b2014-09-23 09:33:00 +00004763 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4764 // 1.2.2 OpenMP Language Terminology
4765 // Structured block - An executable statement with a single entry at the
4766 // top and a single exit at the bottom.
4767 // The point of exit cannot be a branch out of the structured block.
4768 // longjmp() and throw() must not violate the entry/exit criteria.
4769 CS->getCapturedDecl()->setNothrow();
4770
Alexander Musmanc6388682014-12-15 07:07:06 +00004771 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004772 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4773 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004774 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004775 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4776 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4777 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004778 if (NestedLoopCount == 0)
4779 return StmtError();
4780
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004781 if (!CurContext->isDependentContext()) {
4782 // Finalize the clauses that need pre-built expressions for CodeGen.
4783 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004784 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004785 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004786 B.NumIterations, *this, CurScope,
4787 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004788 return StmtError();
4789 }
4790 }
4791
Kelvin Lic5609492016-07-15 04:39:07 +00004792 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004793 return StmtError();
4794
Alexander Musmane4e893b2014-09-23 09:33:00 +00004795 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004796 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004797 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004798}
4799
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004800StmtResult
4801Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4802 Stmt *AStmt, SourceLocation StartLoc,
4803 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004804 if (!AStmt)
4805 return StmtError();
4806
4807 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004808 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004809 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004810 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004811 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004812 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004813 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004814 return StmtError();
4815 // All associated statements must be '#pragma omp section' except for
4816 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004817 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004818 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4819 if (SectionStmt)
4820 Diag(SectionStmt->getLocStart(),
4821 diag::err_omp_parallel_sections_substmt_not_section);
4822 return StmtError();
4823 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004824 cast<OMPSectionDirective>(SectionStmt)
4825 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004826 }
4827 } else {
4828 Diag(AStmt->getLocStart(),
4829 diag::err_omp_parallel_sections_not_compound_stmt);
4830 return StmtError();
4831 }
4832
4833 getCurFunction()->setHasBranchProtectedScope();
4834
Alexey Bataev25e5b442015-09-15 12:52:43 +00004835 return OMPParallelSectionsDirective::Create(
4836 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004837}
4838
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004839StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4840 Stmt *AStmt, SourceLocation StartLoc,
4841 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004842 if (!AStmt)
4843 return StmtError();
4844
David Majnemer9d168222016-08-05 17:44:54 +00004845 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004846 // 1.2.2 OpenMP Language Terminology
4847 // Structured block - An executable statement with a single entry at the
4848 // top and a single exit at the bottom.
4849 // The point of exit cannot be a branch out of the structured block.
4850 // longjmp() and throw() must not violate the entry/exit criteria.
4851 CS->getCapturedDecl()->setNothrow();
4852
4853 getCurFunction()->setHasBranchProtectedScope();
4854
Alexey Bataev25e5b442015-09-15 12:52:43 +00004855 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4856 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004857}
4858
Alexey Bataev68446b72014-07-18 07:47:19 +00004859StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4860 SourceLocation EndLoc) {
4861 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4862}
4863
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004864StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4865 SourceLocation EndLoc) {
4866 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4867}
4868
Alexey Bataev2df347a2014-07-18 10:17:07 +00004869StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4870 SourceLocation EndLoc) {
4871 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4872}
4873
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004874StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4875 SourceLocation StartLoc,
4876 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004877 if (!AStmt)
4878 return StmtError();
4879
4880 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004881
4882 getCurFunction()->setHasBranchProtectedScope();
4883
4884 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4885}
4886
Alexey Bataev6125da92014-07-21 11:26:11 +00004887StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4888 SourceLocation StartLoc,
4889 SourceLocation EndLoc) {
4890 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4891 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4892}
4893
Alexey Bataev346265e2015-09-25 10:37:12 +00004894StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4895 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004896 SourceLocation StartLoc,
4897 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004898 OMPClause *DependFound = nullptr;
4899 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004900 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004901 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004902 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004903 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004904 for (auto *C : Clauses) {
4905 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4906 DependFound = C;
4907 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4908 if (DependSourceClause) {
4909 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4910 << getOpenMPDirectiveName(OMPD_ordered)
4911 << getOpenMPClauseName(OMPC_depend) << 2;
4912 ErrorFound = true;
4913 } else
4914 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004915 if (DependSinkClause) {
4916 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4917 << 0;
4918 ErrorFound = true;
4919 }
4920 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4921 if (DependSourceClause) {
4922 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4923 << 1;
4924 ErrorFound = true;
4925 }
4926 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004927 }
4928 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004929 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004930 else if (C->getClauseKind() == OMPC_simd)
4931 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004932 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004933 if (!ErrorFound && !SC &&
4934 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004935 // OpenMP [2.8.1,simd Construct, Restrictions]
4936 // An ordered construct with the simd clause is the only OpenMP construct
4937 // that can appear in the simd region.
4938 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004939 ErrorFound = true;
4940 } else if (DependFound && (TC || SC)) {
4941 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4942 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4943 ErrorFound = true;
4944 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4945 Diag(DependFound->getLocStart(),
4946 diag::err_omp_ordered_directive_without_param);
4947 ErrorFound = true;
4948 } else if (TC || Clauses.empty()) {
4949 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4950 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4951 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4952 << (TC != nullptr);
4953 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4954 ErrorFound = true;
4955 }
4956 }
4957 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004958 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004959
4960 if (AStmt) {
4961 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4962
4963 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004964 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004965
4966 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004967}
4968
Alexey Bataev1d160b12015-03-13 12:27:31 +00004969namespace {
4970/// \brief Helper class for checking expression in 'omp atomic [update]'
4971/// construct.
4972class OpenMPAtomicUpdateChecker {
4973 /// \brief Error results for atomic update expressions.
4974 enum ExprAnalysisErrorCode {
4975 /// \brief A statement is not an expression statement.
4976 NotAnExpression,
4977 /// \brief Expression is not builtin binary or unary operation.
4978 NotABinaryOrUnaryExpression,
4979 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4980 NotAnUnaryIncDecExpression,
4981 /// \brief An expression is not of scalar type.
4982 NotAScalarType,
4983 /// \brief A binary operation is not an assignment operation.
4984 NotAnAssignmentOp,
4985 /// \brief RHS part of the binary operation is not a binary expression.
4986 NotABinaryExpression,
4987 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4988 /// expression.
4989 NotABinaryOperator,
4990 /// \brief RHS binary operation does not have reference to the updated LHS
4991 /// part.
4992 NotAnUpdateExpression,
4993 /// \brief No errors is found.
4994 NoError
4995 };
4996 /// \brief Reference to Sema.
4997 Sema &SemaRef;
4998 /// \brief A location for note diagnostics (when error is found).
4999 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005000 /// \brief 'x' lvalue part of the source atomic expression.
5001 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005002 /// \brief 'expr' rvalue part of the source atomic expression.
5003 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005004 /// \brief Helper expression of the form
5005 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5006 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5007 Expr *UpdateExpr;
5008 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5009 /// important for non-associative operations.
5010 bool IsXLHSInRHSPart;
5011 BinaryOperatorKind Op;
5012 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005013 /// \brief true if the source expression is a postfix unary operation, false
5014 /// if it is a prefix unary operation.
5015 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005016
5017public:
5018 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005019 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005020 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005021 /// \brief Check specified statement that it is suitable for 'atomic update'
5022 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005023 /// expression. If DiagId and NoteId == 0, then only check is performed
5024 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005025 /// \param DiagId Diagnostic which should be emitted if error is found.
5026 /// \param NoteId Diagnostic note for the main error message.
5027 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005028 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005029 /// \brief Return the 'x' lvalue part of the source atomic expression.
5030 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005031 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5032 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005033 /// \brief Return the update expression used in calculation of the updated
5034 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5035 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5036 Expr *getUpdateExpr() const { return UpdateExpr; }
5037 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5038 /// false otherwise.
5039 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5040
Alexey Bataevb78ca832015-04-01 03:33:17 +00005041 /// \brief true if the source expression is a postfix unary operation, false
5042 /// if it is a prefix unary operation.
5043 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5044
Alexey Bataev1d160b12015-03-13 12:27:31 +00005045private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005046 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5047 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005048};
5049} // namespace
5050
5051bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5052 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5053 ExprAnalysisErrorCode ErrorFound = NoError;
5054 SourceLocation ErrorLoc, NoteLoc;
5055 SourceRange ErrorRange, NoteRange;
5056 // Allowed constructs are:
5057 // x = x binop expr;
5058 // x = expr binop x;
5059 if (AtomicBinOp->getOpcode() == BO_Assign) {
5060 X = AtomicBinOp->getLHS();
5061 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5062 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5063 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5064 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5065 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005066 Op = AtomicInnerBinOp->getOpcode();
5067 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005068 auto *LHS = AtomicInnerBinOp->getLHS();
5069 auto *RHS = AtomicInnerBinOp->getRHS();
5070 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5071 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5072 /*Canonical=*/true);
5073 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5074 /*Canonical=*/true);
5075 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5076 /*Canonical=*/true);
5077 if (XId == LHSId) {
5078 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005079 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005080 } else if (XId == RHSId) {
5081 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005082 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005083 } else {
5084 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5085 ErrorRange = AtomicInnerBinOp->getSourceRange();
5086 NoteLoc = X->getExprLoc();
5087 NoteRange = X->getSourceRange();
5088 ErrorFound = NotAnUpdateExpression;
5089 }
5090 } else {
5091 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5092 ErrorRange = AtomicInnerBinOp->getSourceRange();
5093 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5094 NoteRange = SourceRange(NoteLoc, NoteLoc);
5095 ErrorFound = NotABinaryOperator;
5096 }
5097 } else {
5098 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5099 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5100 ErrorFound = NotABinaryExpression;
5101 }
5102 } else {
5103 ErrorLoc = AtomicBinOp->getExprLoc();
5104 ErrorRange = AtomicBinOp->getSourceRange();
5105 NoteLoc = AtomicBinOp->getOperatorLoc();
5106 NoteRange = SourceRange(NoteLoc, NoteLoc);
5107 ErrorFound = NotAnAssignmentOp;
5108 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005109 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005110 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5111 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5112 return true;
5113 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005114 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005115 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005116}
5117
5118bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5119 unsigned NoteId) {
5120 ExprAnalysisErrorCode ErrorFound = NoError;
5121 SourceLocation ErrorLoc, NoteLoc;
5122 SourceRange ErrorRange, NoteRange;
5123 // Allowed constructs are:
5124 // x++;
5125 // x--;
5126 // ++x;
5127 // --x;
5128 // x binop= expr;
5129 // x = x binop expr;
5130 // x = expr binop x;
5131 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5132 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5133 if (AtomicBody->getType()->isScalarType() ||
5134 AtomicBody->isInstantiationDependent()) {
5135 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5136 AtomicBody->IgnoreParenImpCasts())) {
5137 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005138 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005139 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005140 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005141 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005142 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005143 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005144 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5145 AtomicBody->IgnoreParenImpCasts())) {
5146 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005147 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005148 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005149 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5150 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005151 // Check for Unary Operation
5152 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005153 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005154 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5155 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005156 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005157 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5158 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005159 } else {
5160 ErrorFound = NotAnUnaryIncDecExpression;
5161 ErrorLoc = AtomicUnaryOp->getExprLoc();
5162 ErrorRange = AtomicUnaryOp->getSourceRange();
5163 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5164 NoteRange = SourceRange(NoteLoc, NoteLoc);
5165 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005166 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005167 ErrorFound = NotABinaryOrUnaryExpression;
5168 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5169 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5170 }
5171 } else {
5172 ErrorFound = NotAScalarType;
5173 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5174 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5175 }
5176 } else {
5177 ErrorFound = NotAnExpression;
5178 NoteLoc = ErrorLoc = S->getLocStart();
5179 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5180 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005181 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005182 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5183 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5184 return true;
5185 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005186 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005187 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005188 // Build an update expression of form 'OpaqueValueExpr(x) binop
5189 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5190 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5191 auto *OVEX = new (SemaRef.getASTContext())
5192 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5193 auto *OVEExpr = new (SemaRef.getASTContext())
5194 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5195 auto Update =
5196 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5197 IsXLHSInRHSPart ? OVEExpr : OVEX);
5198 if (Update.isInvalid())
5199 return true;
5200 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5201 Sema::AA_Casting);
5202 if (Update.isInvalid())
5203 return true;
5204 UpdateExpr = Update.get();
5205 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005206 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005207}
5208
Alexey Bataev0162e452014-07-22 10:10:35 +00005209StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5210 Stmt *AStmt,
5211 SourceLocation StartLoc,
5212 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005213 if (!AStmt)
5214 return StmtError();
5215
David Majnemer9d168222016-08-05 17:44:54 +00005216 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005217 // 1.2.2 OpenMP Language Terminology
5218 // Structured block - An executable statement with a single entry at the
5219 // top and a single exit at the bottom.
5220 // The point of exit cannot be a branch out of the structured block.
5221 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005222 OpenMPClauseKind AtomicKind = OMPC_unknown;
5223 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005224 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005225 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005226 C->getClauseKind() == OMPC_update ||
5227 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005228 if (AtomicKind != OMPC_unknown) {
5229 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5230 << SourceRange(C->getLocStart(), C->getLocEnd());
5231 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5232 << getOpenMPClauseName(AtomicKind);
5233 } else {
5234 AtomicKind = C->getClauseKind();
5235 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005236 }
5237 }
5238 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005239
Alexey Bataev459dec02014-07-24 06:46:57 +00005240 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005241 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5242 Body = EWC->getSubExpr();
5243
Alexey Bataev62cec442014-11-18 10:14:22 +00005244 Expr *X = nullptr;
5245 Expr *V = nullptr;
5246 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005247 Expr *UE = nullptr;
5248 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005249 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005250 // OpenMP [2.12.6, atomic Construct]
5251 // In the next expressions:
5252 // * x and v (as applicable) are both l-value expressions with scalar type.
5253 // * During the execution of an atomic region, multiple syntactic
5254 // occurrences of x must designate the same storage location.
5255 // * Neither of v and expr (as applicable) may access the storage location
5256 // designated by x.
5257 // * Neither of x and expr (as applicable) may access the storage location
5258 // designated by v.
5259 // * expr is an expression with scalar type.
5260 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5261 // * binop, binop=, ++, and -- are not overloaded operators.
5262 // * The expression x binop expr must be numerically equivalent to x binop
5263 // (expr). This requirement is satisfied if the operators in expr have
5264 // precedence greater than binop, or by using parentheses around expr or
5265 // subexpressions of expr.
5266 // * The expression expr binop x must be numerically equivalent to (expr)
5267 // binop x. This requirement is satisfied if the operators in expr have
5268 // precedence equal to or greater than binop, or by using parentheses around
5269 // expr or subexpressions of expr.
5270 // * For forms that allow multiple occurrences of x, the number of times
5271 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005272 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005273 enum {
5274 NotAnExpression,
5275 NotAnAssignmentOp,
5276 NotAScalarType,
5277 NotAnLValue,
5278 NoError
5279 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005280 SourceLocation ErrorLoc, NoteLoc;
5281 SourceRange ErrorRange, NoteRange;
5282 // If clause is read:
5283 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005284 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5285 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005286 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5287 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5288 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5289 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5290 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5291 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5292 if (!X->isLValue() || !V->isLValue()) {
5293 auto NotLValueExpr = X->isLValue() ? V : X;
5294 ErrorFound = NotAnLValue;
5295 ErrorLoc = AtomicBinOp->getExprLoc();
5296 ErrorRange = AtomicBinOp->getSourceRange();
5297 NoteLoc = NotLValueExpr->getExprLoc();
5298 NoteRange = NotLValueExpr->getSourceRange();
5299 }
5300 } else if (!X->isInstantiationDependent() ||
5301 !V->isInstantiationDependent()) {
5302 auto NotScalarExpr =
5303 (X->isInstantiationDependent() || X->getType()->isScalarType())
5304 ? V
5305 : X;
5306 ErrorFound = NotAScalarType;
5307 ErrorLoc = AtomicBinOp->getExprLoc();
5308 ErrorRange = AtomicBinOp->getSourceRange();
5309 NoteLoc = NotScalarExpr->getExprLoc();
5310 NoteRange = NotScalarExpr->getSourceRange();
5311 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005312 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005313 ErrorFound = NotAnAssignmentOp;
5314 ErrorLoc = AtomicBody->getExprLoc();
5315 ErrorRange = AtomicBody->getSourceRange();
5316 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5317 : AtomicBody->getExprLoc();
5318 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5319 : AtomicBody->getSourceRange();
5320 }
5321 } else {
5322 ErrorFound = NotAnExpression;
5323 NoteLoc = ErrorLoc = Body->getLocStart();
5324 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005325 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005326 if (ErrorFound != NoError) {
5327 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5328 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005329 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5330 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005331 return StmtError();
5332 } else if (CurContext->isDependentContext())
5333 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005334 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005335 enum {
5336 NotAnExpression,
5337 NotAnAssignmentOp,
5338 NotAScalarType,
5339 NotAnLValue,
5340 NoError
5341 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005342 SourceLocation ErrorLoc, NoteLoc;
5343 SourceRange ErrorRange, NoteRange;
5344 // If clause is write:
5345 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005346 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5347 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005348 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5349 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005350 X = AtomicBinOp->getLHS();
5351 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005352 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5353 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5354 if (!X->isLValue()) {
5355 ErrorFound = NotAnLValue;
5356 ErrorLoc = AtomicBinOp->getExprLoc();
5357 ErrorRange = AtomicBinOp->getSourceRange();
5358 NoteLoc = X->getExprLoc();
5359 NoteRange = X->getSourceRange();
5360 }
5361 } else if (!X->isInstantiationDependent() ||
5362 !E->isInstantiationDependent()) {
5363 auto NotScalarExpr =
5364 (X->isInstantiationDependent() || X->getType()->isScalarType())
5365 ? E
5366 : X;
5367 ErrorFound = NotAScalarType;
5368 ErrorLoc = AtomicBinOp->getExprLoc();
5369 ErrorRange = AtomicBinOp->getSourceRange();
5370 NoteLoc = NotScalarExpr->getExprLoc();
5371 NoteRange = NotScalarExpr->getSourceRange();
5372 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005373 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005374 ErrorFound = NotAnAssignmentOp;
5375 ErrorLoc = AtomicBody->getExprLoc();
5376 ErrorRange = AtomicBody->getSourceRange();
5377 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5378 : AtomicBody->getExprLoc();
5379 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5380 : AtomicBody->getSourceRange();
5381 }
5382 } else {
5383 ErrorFound = NotAnExpression;
5384 NoteLoc = ErrorLoc = Body->getLocStart();
5385 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005386 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005387 if (ErrorFound != NoError) {
5388 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5389 << ErrorRange;
5390 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5391 << NoteRange;
5392 return StmtError();
5393 } else if (CurContext->isDependentContext())
5394 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005395 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005396 // If clause is update:
5397 // x++;
5398 // x--;
5399 // ++x;
5400 // --x;
5401 // x binop= expr;
5402 // x = x binop expr;
5403 // x = expr binop x;
5404 OpenMPAtomicUpdateChecker Checker(*this);
5405 if (Checker.checkStatement(
5406 Body, (AtomicKind == OMPC_update)
5407 ? diag::err_omp_atomic_update_not_expression_statement
5408 : diag::err_omp_atomic_not_expression_statement,
5409 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005410 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005411 if (!CurContext->isDependentContext()) {
5412 E = Checker.getExpr();
5413 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005414 UE = Checker.getUpdateExpr();
5415 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005416 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005417 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005418 enum {
5419 NotAnAssignmentOp,
5420 NotACompoundStatement,
5421 NotTwoSubstatements,
5422 NotASpecificExpression,
5423 NoError
5424 } ErrorFound = NoError;
5425 SourceLocation ErrorLoc, NoteLoc;
5426 SourceRange ErrorRange, NoteRange;
5427 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5428 // If clause is a capture:
5429 // v = x++;
5430 // v = x--;
5431 // v = ++x;
5432 // v = --x;
5433 // v = x binop= expr;
5434 // v = x = x binop expr;
5435 // v = x = expr binop x;
5436 auto *AtomicBinOp =
5437 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5438 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5439 V = AtomicBinOp->getLHS();
5440 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5441 OpenMPAtomicUpdateChecker Checker(*this);
5442 if (Checker.checkStatement(
5443 Body, diag::err_omp_atomic_capture_not_expression_statement,
5444 diag::note_omp_atomic_update))
5445 return StmtError();
5446 E = Checker.getExpr();
5447 X = Checker.getX();
5448 UE = Checker.getUpdateExpr();
5449 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5450 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005451 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005452 ErrorLoc = AtomicBody->getExprLoc();
5453 ErrorRange = AtomicBody->getSourceRange();
5454 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5455 : AtomicBody->getExprLoc();
5456 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5457 : AtomicBody->getSourceRange();
5458 ErrorFound = NotAnAssignmentOp;
5459 }
5460 if (ErrorFound != NoError) {
5461 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5462 << ErrorRange;
5463 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5464 return StmtError();
5465 } else if (CurContext->isDependentContext()) {
5466 UE = V = E = X = nullptr;
5467 }
5468 } else {
5469 // If clause is a capture:
5470 // { v = x; x = expr; }
5471 // { v = x; x++; }
5472 // { v = x; x--; }
5473 // { v = x; ++x; }
5474 // { v = x; --x; }
5475 // { v = x; x binop= expr; }
5476 // { v = x; x = x binop expr; }
5477 // { v = x; x = expr binop x; }
5478 // { x++; v = x; }
5479 // { x--; v = x; }
5480 // { ++x; v = x; }
5481 // { --x; v = x; }
5482 // { x binop= expr; v = x; }
5483 // { x = x binop expr; v = x; }
5484 // { x = expr binop x; v = x; }
5485 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5486 // Check that this is { expr1; expr2; }
5487 if (CS->size() == 2) {
5488 auto *First = CS->body_front();
5489 auto *Second = CS->body_back();
5490 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5491 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5492 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5493 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5494 // Need to find what subexpression is 'v' and what is 'x'.
5495 OpenMPAtomicUpdateChecker Checker(*this);
5496 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5497 BinaryOperator *BinOp = nullptr;
5498 if (IsUpdateExprFound) {
5499 BinOp = dyn_cast<BinaryOperator>(First);
5500 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5501 }
5502 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5503 // { v = x; x++; }
5504 // { v = x; x--; }
5505 // { v = x; ++x; }
5506 // { v = x; --x; }
5507 // { v = x; x binop= expr; }
5508 // { v = x; x = x binop expr; }
5509 // { v = x; x = expr binop x; }
5510 // Check that the first expression has form v = x.
5511 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5512 llvm::FoldingSetNodeID XId, PossibleXId;
5513 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5514 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5515 IsUpdateExprFound = XId == PossibleXId;
5516 if (IsUpdateExprFound) {
5517 V = BinOp->getLHS();
5518 X = Checker.getX();
5519 E = Checker.getExpr();
5520 UE = Checker.getUpdateExpr();
5521 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005522 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005523 }
5524 }
5525 if (!IsUpdateExprFound) {
5526 IsUpdateExprFound = !Checker.checkStatement(First);
5527 BinOp = nullptr;
5528 if (IsUpdateExprFound) {
5529 BinOp = dyn_cast<BinaryOperator>(Second);
5530 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5531 }
5532 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5533 // { x++; v = x; }
5534 // { x--; v = x; }
5535 // { ++x; v = x; }
5536 // { --x; v = x; }
5537 // { x binop= expr; v = x; }
5538 // { x = x binop expr; v = x; }
5539 // { x = expr binop x; v = x; }
5540 // Check that the second expression has form v = x.
5541 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5542 llvm::FoldingSetNodeID XId, PossibleXId;
5543 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5544 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5545 IsUpdateExprFound = XId == PossibleXId;
5546 if (IsUpdateExprFound) {
5547 V = BinOp->getLHS();
5548 X = Checker.getX();
5549 E = Checker.getExpr();
5550 UE = Checker.getUpdateExpr();
5551 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005552 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005553 }
5554 }
5555 }
5556 if (!IsUpdateExprFound) {
5557 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005558 auto *FirstExpr = dyn_cast<Expr>(First);
5559 auto *SecondExpr = dyn_cast<Expr>(Second);
5560 if (!FirstExpr || !SecondExpr ||
5561 !(FirstExpr->isInstantiationDependent() ||
5562 SecondExpr->isInstantiationDependent())) {
5563 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5564 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005565 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005566 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5567 : First->getLocStart();
5568 NoteRange = ErrorRange = FirstBinOp
5569 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005570 : SourceRange(ErrorLoc, ErrorLoc);
5571 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005572 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5573 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5574 ErrorFound = NotAnAssignmentOp;
5575 NoteLoc = ErrorLoc = SecondBinOp
5576 ? SecondBinOp->getOperatorLoc()
5577 : Second->getLocStart();
5578 NoteRange = ErrorRange =
5579 SecondBinOp ? SecondBinOp->getSourceRange()
5580 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005581 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005582 auto *PossibleXRHSInFirst =
5583 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5584 auto *PossibleXLHSInSecond =
5585 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5586 llvm::FoldingSetNodeID X1Id, X2Id;
5587 PossibleXRHSInFirst->Profile(X1Id, Context,
5588 /*Canonical=*/true);
5589 PossibleXLHSInSecond->Profile(X2Id, Context,
5590 /*Canonical=*/true);
5591 IsUpdateExprFound = X1Id == X2Id;
5592 if (IsUpdateExprFound) {
5593 V = FirstBinOp->getLHS();
5594 X = SecondBinOp->getLHS();
5595 E = SecondBinOp->getRHS();
5596 UE = nullptr;
5597 IsXLHSInRHSPart = false;
5598 IsPostfixUpdate = true;
5599 } else {
5600 ErrorFound = NotASpecificExpression;
5601 ErrorLoc = FirstBinOp->getExprLoc();
5602 ErrorRange = FirstBinOp->getSourceRange();
5603 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5604 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5605 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005606 }
5607 }
5608 }
5609 }
5610 } else {
5611 NoteLoc = ErrorLoc = Body->getLocStart();
5612 NoteRange = ErrorRange =
5613 SourceRange(Body->getLocStart(), Body->getLocStart());
5614 ErrorFound = NotTwoSubstatements;
5615 }
5616 } else {
5617 NoteLoc = ErrorLoc = Body->getLocStart();
5618 NoteRange = ErrorRange =
5619 SourceRange(Body->getLocStart(), Body->getLocStart());
5620 ErrorFound = NotACompoundStatement;
5621 }
5622 if (ErrorFound != NoError) {
5623 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5624 << ErrorRange;
5625 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5626 return StmtError();
5627 } else if (CurContext->isDependentContext()) {
5628 UE = V = E = X = nullptr;
5629 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005630 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005631 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005632
5633 getCurFunction()->setHasBranchProtectedScope();
5634
Alexey Bataev62cec442014-11-18 10:14:22 +00005635 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005636 X, V, E, UE, IsXLHSInRHSPart,
5637 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005638}
5639
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005640StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5641 Stmt *AStmt,
5642 SourceLocation StartLoc,
5643 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005644 if (!AStmt)
5645 return StmtError();
5646
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005647 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5648 // 1.2.2 OpenMP Language Terminology
5649 // Structured block - An executable statement with a single entry at the
5650 // top and a single exit at the bottom.
5651 // The point of exit cannot be a branch out of the structured block.
5652 // longjmp() and throw() must not violate the entry/exit criteria.
5653 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005654
Alexey Bataev13314bf2014-10-09 04:18:56 +00005655 // OpenMP [2.16, Nesting of Regions]
5656 // If specified, a teams construct must be contained within a target
5657 // construct. That target construct must contain no statements or directives
5658 // outside of the teams construct.
5659 if (DSAStack->hasInnerTeamsRegion()) {
5660 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5661 bool OMPTeamsFound = true;
5662 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5663 auto I = CS->body_begin();
5664 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005665 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005666 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5667 OMPTeamsFound = false;
5668 break;
5669 }
5670 ++I;
5671 }
5672 assert(I != CS->body_end() && "Not found statement");
5673 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005674 } else {
5675 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5676 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005677 }
5678 if (!OMPTeamsFound) {
5679 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5680 Diag(DSAStack->getInnerTeamsRegionLoc(),
5681 diag::note_omp_nested_teams_construct_here);
5682 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5683 << isa<OMPExecutableDirective>(S);
5684 return StmtError();
5685 }
5686 }
5687
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005688 getCurFunction()->setHasBranchProtectedScope();
5689
5690 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5691}
5692
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005693StmtResult
5694Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5695 Stmt *AStmt, SourceLocation StartLoc,
5696 SourceLocation EndLoc) {
5697 if (!AStmt)
5698 return StmtError();
5699
5700 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5701 // 1.2.2 OpenMP Language Terminology
5702 // Structured block - An executable statement with a single entry at the
5703 // top and a single exit at the bottom.
5704 // The point of exit cannot be a branch out of the structured block.
5705 // longjmp() and throw() must not violate the entry/exit criteria.
5706 CS->getCapturedDecl()->setNothrow();
5707
5708 getCurFunction()->setHasBranchProtectedScope();
5709
5710 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5711 AStmt);
5712}
5713
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005714StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5715 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5716 SourceLocation EndLoc,
5717 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5718 if (!AStmt)
5719 return StmtError();
5720
5721 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5722 // 1.2.2 OpenMP Language Terminology
5723 // Structured block - An executable statement with a single entry at the
5724 // top and a single exit at the bottom.
5725 // The point of exit cannot be a branch out of the structured block.
5726 // longjmp() and throw() must not violate the entry/exit criteria.
5727 CS->getCapturedDecl()->setNothrow();
5728
5729 OMPLoopDirective::HelperExprs B;
5730 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5731 // define the nested loops number.
5732 unsigned NestedLoopCount =
5733 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5734 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5735 VarsWithImplicitDSA, B);
5736 if (NestedLoopCount == 0)
5737 return StmtError();
5738
5739 assert((CurContext->isDependentContext() || B.builtAll()) &&
5740 "omp target parallel for loop exprs were not built");
5741
5742 if (!CurContext->isDependentContext()) {
5743 // Finalize the clauses that need pre-built expressions for CodeGen.
5744 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005745 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005746 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005747 B.NumIterations, *this, CurScope,
5748 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005749 return StmtError();
5750 }
5751 }
5752
5753 getCurFunction()->setHasBranchProtectedScope();
5754 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5755 NestedLoopCount, Clauses, AStmt,
5756 B, DSAStack->isCancelRegion());
5757}
5758
Samuel Antaodf67fc42016-01-19 19:15:56 +00005759/// \brief Check for existence of a map clause in the list of clauses.
5760static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5761 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5762 I != E; ++I) {
5763 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5764 return true;
5765 }
5766 }
5767
5768 return false;
5769}
5770
Michael Wong65f367f2015-07-21 13:44:28 +00005771StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5772 Stmt *AStmt,
5773 SourceLocation StartLoc,
5774 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005775 if (!AStmt)
5776 return StmtError();
5777
5778 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5779
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005780 // OpenMP [2.10.1, Restrictions, p. 97]
5781 // At least one map clause must appear on the directive.
5782 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005783 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5784 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005785 return StmtError();
5786 }
5787
Michael Wong65f367f2015-07-21 13:44:28 +00005788 getCurFunction()->setHasBranchProtectedScope();
5789
5790 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5791 AStmt);
5792}
5793
Samuel Antaodf67fc42016-01-19 19:15:56 +00005794StmtResult
5795Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5796 SourceLocation StartLoc,
5797 SourceLocation EndLoc) {
5798 // OpenMP [2.10.2, Restrictions, p. 99]
5799 // At least one map clause must appear on the directive.
5800 if (!HasMapClause(Clauses)) {
5801 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5802 << getOpenMPDirectiveName(OMPD_target_enter_data);
5803 return StmtError();
5804 }
5805
5806 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5807 Clauses);
5808}
5809
Samuel Antao72590762016-01-19 20:04:50 +00005810StmtResult
5811Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5812 SourceLocation StartLoc,
5813 SourceLocation EndLoc) {
5814 // OpenMP [2.10.3, Restrictions, p. 102]
5815 // At least one map clause must appear on the directive.
5816 if (!HasMapClause(Clauses)) {
5817 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5818 << getOpenMPDirectiveName(OMPD_target_exit_data);
5819 return StmtError();
5820 }
5821
5822 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5823}
5824
Samuel Antao686c70c2016-05-26 17:30:50 +00005825StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5826 SourceLocation StartLoc,
5827 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005828 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005829 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005830 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005831 seenMotionClause = true;
5832 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005833 if (!seenMotionClause) {
5834 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5835 return StmtError();
5836 }
5837 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5838}
5839
Alexey Bataev13314bf2014-10-09 04:18:56 +00005840StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5841 Stmt *AStmt, SourceLocation StartLoc,
5842 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005843 if (!AStmt)
5844 return StmtError();
5845
Alexey Bataev13314bf2014-10-09 04:18:56 +00005846 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5847 // 1.2.2 OpenMP Language Terminology
5848 // Structured block - An executable statement with a single entry at the
5849 // top and a single exit at the bottom.
5850 // The point of exit cannot be a branch out of the structured block.
5851 // longjmp() and throw() must not violate the entry/exit criteria.
5852 CS->getCapturedDecl()->setNothrow();
5853
5854 getCurFunction()->setHasBranchProtectedScope();
5855
5856 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5857}
5858
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005859StmtResult
5860Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5861 SourceLocation EndLoc,
5862 OpenMPDirectiveKind CancelRegion) {
5863 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5864 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5865 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5866 << getOpenMPDirectiveName(CancelRegion);
5867 return StmtError();
5868 }
5869 if (DSAStack->isParentNowaitRegion()) {
5870 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5871 return StmtError();
5872 }
5873 if (DSAStack->isParentOrderedRegion()) {
5874 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5875 return StmtError();
5876 }
5877 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5878 CancelRegion);
5879}
5880
Alexey Bataev87933c72015-09-18 08:07:34 +00005881StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5882 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005883 SourceLocation EndLoc,
5884 OpenMPDirectiveKind CancelRegion) {
5885 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5886 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5887 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5888 << getOpenMPDirectiveName(CancelRegion);
5889 return StmtError();
5890 }
5891 if (DSAStack->isParentNowaitRegion()) {
5892 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5893 return StmtError();
5894 }
5895 if (DSAStack->isParentOrderedRegion()) {
5896 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5897 return StmtError();
5898 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005899 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005900 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5901 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005902}
5903
Alexey Bataev382967a2015-12-08 12:06:20 +00005904static bool checkGrainsizeNumTasksClauses(Sema &S,
5905 ArrayRef<OMPClause *> Clauses) {
5906 OMPClause *PrevClause = nullptr;
5907 bool ErrorFound = false;
5908 for (auto *C : Clauses) {
5909 if (C->getClauseKind() == OMPC_grainsize ||
5910 C->getClauseKind() == OMPC_num_tasks) {
5911 if (!PrevClause)
5912 PrevClause = C;
5913 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5914 S.Diag(C->getLocStart(),
5915 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5916 << getOpenMPClauseName(C->getClauseKind())
5917 << getOpenMPClauseName(PrevClause->getClauseKind());
5918 S.Diag(PrevClause->getLocStart(),
5919 diag::note_omp_previous_grainsize_num_tasks)
5920 << getOpenMPClauseName(PrevClause->getClauseKind());
5921 ErrorFound = true;
5922 }
5923 }
5924 }
5925 return ErrorFound;
5926}
5927
Alexey Bataev49f6e782015-12-01 04:18:41 +00005928StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5929 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5930 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005931 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005932 if (!AStmt)
5933 return StmtError();
5934
5935 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5936 OMPLoopDirective::HelperExprs B;
5937 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5938 // define the nested loops number.
5939 unsigned NestedLoopCount =
5940 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005941 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005942 VarsWithImplicitDSA, B);
5943 if (NestedLoopCount == 0)
5944 return StmtError();
5945
5946 assert((CurContext->isDependentContext() || B.builtAll()) &&
5947 "omp for loop exprs were not built");
5948
Alexey Bataev382967a2015-12-08 12:06:20 +00005949 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5950 // The grainsize clause and num_tasks clause are mutually exclusive and may
5951 // not appear on the same taskloop directive.
5952 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5953 return StmtError();
5954
Alexey Bataev49f6e782015-12-01 04:18:41 +00005955 getCurFunction()->setHasBranchProtectedScope();
5956 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5957 NestedLoopCount, Clauses, AStmt, B);
5958}
5959
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005960StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5961 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5962 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005963 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005964 if (!AStmt)
5965 return StmtError();
5966
5967 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5968 OMPLoopDirective::HelperExprs B;
5969 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5970 // define the nested loops number.
5971 unsigned NestedLoopCount =
5972 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5973 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5974 VarsWithImplicitDSA, B);
5975 if (NestedLoopCount == 0)
5976 return StmtError();
5977
5978 assert((CurContext->isDependentContext() || B.builtAll()) &&
5979 "omp for loop exprs were not built");
5980
Alexey Bataev5a3af132016-03-29 08:58:54 +00005981 if (!CurContext->isDependentContext()) {
5982 // Finalize the clauses that need pre-built expressions for CodeGen.
5983 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005984 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005985 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005986 B.NumIterations, *this, CurScope,
5987 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005988 return StmtError();
5989 }
5990 }
5991
Alexey Bataev382967a2015-12-08 12:06:20 +00005992 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5993 // The grainsize clause and num_tasks clause are mutually exclusive and may
5994 // not appear on the same taskloop directive.
5995 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5996 return StmtError();
5997
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005998 getCurFunction()->setHasBranchProtectedScope();
5999 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6000 NestedLoopCount, Clauses, AStmt, B);
6001}
6002
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006003StmtResult Sema::ActOnOpenMPDistributeDirective(
6004 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6005 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006006 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006007 if (!AStmt)
6008 return StmtError();
6009
6010 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6011 OMPLoopDirective::HelperExprs B;
6012 // In presence of clause 'collapse' with number of loops, it will
6013 // define the nested loops number.
6014 unsigned NestedLoopCount =
6015 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6016 nullptr /*ordered not a clause on distribute*/, AStmt,
6017 *this, *DSAStack, VarsWithImplicitDSA, B);
6018 if (NestedLoopCount == 0)
6019 return StmtError();
6020
6021 assert((CurContext->isDependentContext() || B.builtAll()) &&
6022 "omp for loop exprs were not built");
6023
6024 getCurFunction()->setHasBranchProtectedScope();
6025 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6026 NestedLoopCount, Clauses, AStmt, B);
6027}
6028
Carlo Bertolli9925f152016-06-27 14:55:37 +00006029StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6030 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6031 SourceLocation EndLoc,
6032 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6033 if (!AStmt)
6034 return StmtError();
6035
6036 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6037 // 1.2.2 OpenMP Language Terminology
6038 // Structured block - An executable statement with a single entry at the
6039 // top and a single exit at the bottom.
6040 // The point of exit cannot be a branch out of the structured block.
6041 // longjmp() and throw() must not violate the entry/exit criteria.
6042 CS->getCapturedDecl()->setNothrow();
6043
6044 OMPLoopDirective::HelperExprs B;
6045 // In presence of clause 'collapse' with number of loops, it will
6046 // define the nested loops number.
6047 unsigned NestedLoopCount = CheckOpenMPLoop(
6048 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6049 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6050 VarsWithImplicitDSA, B);
6051 if (NestedLoopCount == 0)
6052 return StmtError();
6053
6054 assert((CurContext->isDependentContext() || B.builtAll()) &&
6055 "omp for loop exprs were not built");
6056
6057 getCurFunction()->setHasBranchProtectedScope();
6058 return OMPDistributeParallelForDirective::Create(
6059 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6060}
6061
Kelvin Li4a39add2016-07-05 05:00:15 +00006062StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6063 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6064 SourceLocation EndLoc,
6065 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6066 if (!AStmt)
6067 return StmtError();
6068
6069 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6070 // 1.2.2 OpenMP Language Terminology
6071 // Structured block - An executable statement with a single entry at the
6072 // top and a single exit at the bottom.
6073 // The point of exit cannot be a branch out of the structured block.
6074 // longjmp() and throw() must not violate the entry/exit criteria.
6075 CS->getCapturedDecl()->setNothrow();
6076
6077 OMPLoopDirective::HelperExprs B;
6078 // In presence of clause 'collapse' with number of loops, it will
6079 // define the nested loops number.
6080 unsigned NestedLoopCount = CheckOpenMPLoop(
6081 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6082 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6083 VarsWithImplicitDSA, B);
6084 if (NestedLoopCount == 0)
6085 return StmtError();
6086
6087 assert((CurContext->isDependentContext() || B.builtAll()) &&
6088 "omp for loop exprs were not built");
6089
Kelvin Lic5609492016-07-15 04:39:07 +00006090 if (checkSimdlenSafelenSpecified(*this, Clauses))
6091 return StmtError();
6092
Kelvin Li4a39add2016-07-05 05:00:15 +00006093 getCurFunction()->setHasBranchProtectedScope();
6094 return OMPDistributeParallelForSimdDirective::Create(
6095 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6096}
6097
Kelvin Li787f3fc2016-07-06 04:45:38 +00006098StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6099 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6100 SourceLocation EndLoc,
6101 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6102 if (!AStmt)
6103 return StmtError();
6104
6105 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6106 // 1.2.2 OpenMP Language Terminology
6107 // Structured block - An executable statement with a single entry at the
6108 // top and a single exit at the bottom.
6109 // The point of exit cannot be a branch out of the structured block.
6110 // longjmp() and throw() must not violate the entry/exit criteria.
6111 CS->getCapturedDecl()->setNothrow();
6112
6113 OMPLoopDirective::HelperExprs B;
6114 // In presence of clause 'collapse' with number of loops, it will
6115 // define the nested loops number.
6116 unsigned NestedLoopCount =
6117 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6118 nullptr /*ordered not a clause on distribute*/, AStmt,
6119 *this, *DSAStack, VarsWithImplicitDSA, B);
6120 if (NestedLoopCount == 0)
6121 return StmtError();
6122
6123 assert((CurContext->isDependentContext() || B.builtAll()) &&
6124 "omp for loop exprs were not built");
6125
Kelvin Lic5609492016-07-15 04:39:07 +00006126 if (checkSimdlenSafelenSpecified(*this, Clauses))
6127 return StmtError();
6128
Kelvin Li787f3fc2016-07-06 04:45:38 +00006129 getCurFunction()->setHasBranchProtectedScope();
6130 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6131 NestedLoopCount, Clauses, AStmt, B);
6132}
6133
Kelvin Lia579b912016-07-14 02:54:56 +00006134StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6135 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6136 SourceLocation EndLoc,
6137 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6138 if (!AStmt)
6139 return StmtError();
6140
6141 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6142 // 1.2.2 OpenMP Language Terminology
6143 // Structured block - An executable statement with a single entry at the
6144 // top and a single exit at the bottom.
6145 // The point of exit cannot be a branch out of the structured block.
6146 // longjmp() and throw() must not violate the entry/exit criteria.
6147 CS->getCapturedDecl()->setNothrow();
6148
6149 OMPLoopDirective::HelperExprs B;
6150 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6151 // define the nested loops number.
6152 unsigned NestedLoopCount = CheckOpenMPLoop(
6153 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6154 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6155 VarsWithImplicitDSA, B);
6156 if (NestedLoopCount == 0)
6157 return StmtError();
6158
6159 assert((CurContext->isDependentContext() || B.builtAll()) &&
6160 "omp target parallel for simd loop exprs were not built");
6161
6162 if (!CurContext->isDependentContext()) {
6163 // Finalize the clauses that need pre-built expressions for CodeGen.
6164 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006165 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006166 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6167 B.NumIterations, *this, CurScope,
6168 DSAStack))
6169 return StmtError();
6170 }
6171 }
Kelvin Lic5609492016-07-15 04:39:07 +00006172 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006173 return StmtError();
6174
6175 getCurFunction()->setHasBranchProtectedScope();
6176 return OMPTargetParallelForSimdDirective::Create(
6177 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6178}
6179
Kelvin Li986330c2016-07-20 22:57:10 +00006180StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6181 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6182 SourceLocation EndLoc,
6183 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6184 if (!AStmt)
6185 return StmtError();
6186
6187 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6188 // 1.2.2 OpenMP Language Terminology
6189 // Structured block - An executable statement with a single entry at the
6190 // top and a single exit at the bottom.
6191 // The point of exit cannot be a branch out of the structured block.
6192 // longjmp() and throw() must not violate the entry/exit criteria.
6193 CS->getCapturedDecl()->setNothrow();
6194
6195 OMPLoopDirective::HelperExprs B;
6196 // In presence of clause 'collapse' with number of loops, it will define the
6197 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006198 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006199 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6200 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6201 VarsWithImplicitDSA, B);
6202 if (NestedLoopCount == 0)
6203 return StmtError();
6204
6205 assert((CurContext->isDependentContext() || B.builtAll()) &&
6206 "omp target simd loop exprs were not built");
6207
6208 if (!CurContext->isDependentContext()) {
6209 // Finalize the clauses that need pre-built expressions for CodeGen.
6210 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006211 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006212 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6213 B.NumIterations, *this, CurScope,
6214 DSAStack))
6215 return StmtError();
6216 }
6217 }
6218
6219 if (checkSimdlenSafelenSpecified(*this, Clauses))
6220 return StmtError();
6221
6222 getCurFunction()->setHasBranchProtectedScope();
6223 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6224 NestedLoopCount, Clauses, AStmt, B);
6225}
6226
Kelvin Li02532872016-08-05 14:37:37 +00006227StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6228 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6229 SourceLocation EndLoc,
6230 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6231 if (!AStmt)
6232 return StmtError();
6233
6234 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6235 // 1.2.2 OpenMP Language Terminology
6236 // Structured block - An executable statement with a single entry at the
6237 // top and a single exit at the bottom.
6238 // The point of exit cannot be a branch out of the structured block.
6239 // longjmp() and throw() must not violate the entry/exit criteria.
6240 CS->getCapturedDecl()->setNothrow();
6241
6242 OMPLoopDirective::HelperExprs B;
6243 // In presence of clause 'collapse' with number of loops, it will
6244 // define the nested loops number.
6245 unsigned NestedLoopCount =
6246 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6247 nullptr /*ordered not a clause on distribute*/, AStmt,
6248 *this, *DSAStack, VarsWithImplicitDSA, B);
6249 if (NestedLoopCount == 0)
6250 return StmtError();
6251
6252 assert((CurContext->isDependentContext() || B.builtAll()) &&
6253 "omp teams distribute loop exprs were not built");
6254
6255 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006256 return OMPTeamsDistributeDirective::Create(
6257 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006258}
6259
Kelvin Li4e325f72016-10-25 12:50:55 +00006260StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6261 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6262 SourceLocation EndLoc,
6263 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6264 if (!AStmt)
6265 return StmtError();
6266
6267 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6268 // 1.2.2 OpenMP Language Terminology
6269 // Structured block - An executable statement with a single entry at the
6270 // top and a single exit at the bottom.
6271 // The point of exit cannot be a branch out of the structured block.
6272 // longjmp() and throw() must not violate the entry/exit criteria.
6273 CS->getCapturedDecl()->setNothrow();
6274
6275 OMPLoopDirective::HelperExprs B;
6276 // In presence of clause 'collapse' with number of loops, it will
6277 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006278 unsigned NestedLoopCount = CheckOpenMPLoop(
6279 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6280 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6281 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006282
6283 if (NestedLoopCount == 0)
6284 return StmtError();
6285
6286 assert((CurContext->isDependentContext() || B.builtAll()) &&
6287 "omp teams distribute simd loop exprs were not built");
6288
6289 if (!CurContext->isDependentContext()) {
6290 // Finalize the clauses that need pre-built expressions for CodeGen.
6291 for (auto C : Clauses) {
6292 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6293 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6294 B.NumIterations, *this, CurScope,
6295 DSAStack))
6296 return StmtError();
6297 }
6298 }
6299
6300 if (checkSimdlenSafelenSpecified(*this, Clauses))
6301 return StmtError();
6302
6303 getCurFunction()->setHasBranchProtectedScope();
6304 return OMPTeamsDistributeSimdDirective::Create(
6305 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6306}
6307
Kelvin Li579e41c2016-11-30 23:51:03 +00006308StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6309 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6310 SourceLocation EndLoc,
6311 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6312 if (!AStmt)
6313 return StmtError();
6314
6315 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6316 // 1.2.2 OpenMP Language Terminology
6317 // Structured block - An executable statement with a single entry at the
6318 // top and a single exit at the bottom.
6319 // The point of exit cannot be a branch out of the structured block.
6320 // longjmp() and throw() must not violate the entry/exit criteria.
6321 CS->getCapturedDecl()->setNothrow();
6322
6323 OMPLoopDirective::HelperExprs B;
6324 // In presence of clause 'collapse' with number of loops, it will
6325 // define the nested loops number.
6326 auto NestedLoopCount = CheckOpenMPLoop(
6327 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6328 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6329 VarsWithImplicitDSA, B);
6330
6331 if (NestedLoopCount == 0)
6332 return StmtError();
6333
6334 assert((CurContext->isDependentContext() || B.builtAll()) &&
6335 "omp for loop exprs were not built");
6336
6337 if (!CurContext->isDependentContext()) {
6338 // Finalize the clauses that need pre-built expressions for CodeGen.
6339 for (auto C : Clauses) {
6340 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6341 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6342 B.NumIterations, *this, CurScope,
6343 DSAStack))
6344 return StmtError();
6345 }
6346 }
6347
6348 if (checkSimdlenSafelenSpecified(*this, Clauses))
6349 return StmtError();
6350
6351 getCurFunction()->setHasBranchProtectedScope();
6352 return OMPTeamsDistributeParallelForSimdDirective::Create(
6353 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6354}
6355
Kelvin Li7ade93f2016-12-09 03:24:30 +00006356StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6357 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6358 SourceLocation EndLoc,
6359 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6360 if (!AStmt)
6361 return StmtError();
6362
6363 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6364 // 1.2.2 OpenMP Language Terminology
6365 // Structured block - An executable statement with a single entry at the
6366 // top and a single exit at the bottom.
6367 // The point of exit cannot be a branch out of the structured block.
6368 // longjmp() and throw() must not violate the entry/exit criteria.
6369 CS->getCapturedDecl()->setNothrow();
6370
6371 OMPLoopDirective::HelperExprs B;
6372 // In presence of clause 'collapse' with number of loops, it will
6373 // define the nested loops number.
6374 unsigned NestedLoopCount = CheckOpenMPLoop(
6375 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6376 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6377 VarsWithImplicitDSA, B);
6378
6379 if (NestedLoopCount == 0)
6380 return StmtError();
6381
6382 assert((CurContext->isDependentContext() || B.builtAll()) &&
6383 "omp for loop exprs were not built");
6384
6385 if (!CurContext->isDependentContext()) {
6386 // Finalize the clauses that need pre-built expressions for CodeGen.
6387 for (auto C : Clauses) {
6388 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6389 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6390 B.NumIterations, *this, CurScope,
6391 DSAStack))
6392 return StmtError();
6393 }
6394 }
6395
6396 getCurFunction()->setHasBranchProtectedScope();
6397 return OMPTeamsDistributeParallelForDirective::Create(
6398 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6399}
6400
Kelvin Libf594a52016-12-17 05:48:59 +00006401StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6402 Stmt *AStmt,
6403 SourceLocation StartLoc,
6404 SourceLocation EndLoc) {
6405 if (!AStmt)
6406 return StmtError();
6407
6408 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6409 // 1.2.2 OpenMP Language Terminology
6410 // Structured block - An executable statement with a single entry at the
6411 // top and a single exit at the bottom.
6412 // The point of exit cannot be a branch out of the structured block.
6413 // longjmp() and throw() must not violate the entry/exit criteria.
6414 CS->getCapturedDecl()->setNothrow();
6415
6416 getCurFunction()->setHasBranchProtectedScope();
6417
6418 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6419 AStmt);
6420}
6421
Kelvin Li83c451e2016-12-25 04:52:54 +00006422StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6423 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6424 SourceLocation EndLoc,
6425 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6426 if (!AStmt)
6427 return StmtError();
6428
6429 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6430 // 1.2.2 OpenMP Language Terminology
6431 // Structured block - An executable statement with a single entry at the
6432 // top and a single exit at the bottom.
6433 // The point of exit cannot be a branch out of the structured block.
6434 // longjmp() and throw() must not violate the entry/exit criteria.
6435 CS->getCapturedDecl()->setNothrow();
6436
6437 OMPLoopDirective::HelperExprs B;
6438 // In presence of clause 'collapse' with number of loops, it will
6439 // define the nested loops number.
6440 auto NestedLoopCount = CheckOpenMPLoop(
6441 OMPD_target_teams_distribute,
6442 getCollapseNumberExpr(Clauses),
6443 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6444 VarsWithImplicitDSA, B);
6445 if (NestedLoopCount == 0)
6446 return StmtError();
6447
6448 assert((CurContext->isDependentContext() || B.builtAll()) &&
6449 "omp target teams distribute loop exprs were not built");
6450
6451 getCurFunction()->setHasBranchProtectedScope();
6452 return OMPTargetTeamsDistributeDirective::Create(
6453 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6454}
6455
Kelvin Li80e8f562016-12-29 22:16:30 +00006456StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6457 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6458 SourceLocation EndLoc,
6459 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6460 if (!AStmt)
6461 return StmtError();
6462
6463 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6464 // 1.2.2 OpenMP Language Terminology
6465 // Structured block - An executable statement with a single entry at the
6466 // top and a single exit at the bottom.
6467 // The point of exit cannot be a branch out of the structured block.
6468 // longjmp() and throw() must not violate the entry/exit criteria.
6469 CS->getCapturedDecl()->setNothrow();
6470
6471 OMPLoopDirective::HelperExprs B;
6472 // In presence of clause 'collapse' with number of loops, it will
6473 // define the nested loops number.
6474 auto NestedLoopCount = CheckOpenMPLoop(
6475 OMPD_target_teams_distribute_parallel_for,
6476 getCollapseNumberExpr(Clauses),
6477 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6478 VarsWithImplicitDSA, B);
6479 if (NestedLoopCount == 0)
6480 return StmtError();
6481
6482 assert((CurContext->isDependentContext() || B.builtAll()) &&
6483 "omp target teams distribute parallel for loop exprs were not built");
6484
6485 if (!CurContext->isDependentContext()) {
6486 // Finalize the clauses that need pre-built expressions for CodeGen.
6487 for (auto C : Clauses) {
6488 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6489 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6490 B.NumIterations, *this, CurScope,
6491 DSAStack))
6492 return StmtError();
6493 }
6494 }
6495
6496 getCurFunction()->setHasBranchProtectedScope();
6497 return OMPTargetTeamsDistributeParallelForDirective::Create(
6498 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6499}
6500
Kelvin Li1851df52017-01-03 05:23:48 +00006501StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6502 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6503 SourceLocation EndLoc,
6504 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6505 if (!AStmt)
6506 return StmtError();
6507
6508 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6509 // 1.2.2 OpenMP Language Terminology
6510 // Structured block - An executable statement with a single entry at the
6511 // top and a single exit at the bottom.
6512 // The point of exit cannot be a branch out of the structured block.
6513 // longjmp() and throw() must not violate the entry/exit criteria.
6514 CS->getCapturedDecl()->setNothrow();
6515
6516 OMPLoopDirective::HelperExprs B;
6517 // In presence of clause 'collapse' with number of loops, it will
6518 // define the nested loops number.
6519 auto NestedLoopCount = CheckOpenMPLoop(
6520 OMPD_target_teams_distribute_parallel_for_simd,
6521 getCollapseNumberExpr(Clauses),
6522 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6523 VarsWithImplicitDSA, B);
6524 if (NestedLoopCount == 0)
6525 return StmtError();
6526
6527 assert((CurContext->isDependentContext() || B.builtAll()) &&
6528 "omp target teams distribute parallel for simd loop exprs were not "
6529 "built");
6530
6531 if (!CurContext->isDependentContext()) {
6532 // Finalize the clauses that need pre-built expressions for CodeGen.
6533 for (auto C : Clauses) {
6534 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6535 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6536 B.NumIterations, *this, CurScope,
6537 DSAStack))
6538 return StmtError();
6539 }
6540 }
6541
6542 getCurFunction()->setHasBranchProtectedScope();
6543 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6544 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6545}
6546
Kelvin Lida681182017-01-10 18:08:18 +00006547StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6548 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6549 SourceLocation EndLoc,
6550 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6551 if (!AStmt)
6552 return StmtError();
6553
6554 auto *CS = cast<CapturedStmt>(AStmt);
6555 // 1.2.2 OpenMP Language Terminology
6556 // Structured block - An executable statement with a single entry at the
6557 // top and a single exit at the bottom.
6558 // The point of exit cannot be a branch out of the structured block.
6559 // longjmp() and throw() must not violate the entry/exit criteria.
6560 CS->getCapturedDecl()->setNothrow();
6561
6562 OMPLoopDirective::HelperExprs B;
6563 // In presence of clause 'collapse' with number of loops, it will
6564 // define the nested loops number.
6565 auto NestedLoopCount = CheckOpenMPLoop(
6566 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6567 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6568 VarsWithImplicitDSA, B);
6569 if (NestedLoopCount == 0)
6570 return StmtError();
6571
6572 assert((CurContext->isDependentContext() || B.builtAll()) &&
6573 "omp target teams distribute simd loop exprs were not built");
6574
6575 getCurFunction()->setHasBranchProtectedScope();
6576 return OMPTargetTeamsDistributeSimdDirective::Create(
6577 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6578}
6579
Alexey Bataeved09d242014-05-28 05:53:51 +00006580OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006581 SourceLocation StartLoc,
6582 SourceLocation LParenLoc,
6583 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006584 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006585 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006586 case OMPC_final:
6587 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6588 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006589 case OMPC_num_threads:
6590 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6591 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006592 case OMPC_safelen:
6593 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6594 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006595 case OMPC_simdlen:
6596 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6597 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006598 case OMPC_collapse:
6599 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6600 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006601 case OMPC_ordered:
6602 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6603 break;
Michael Wonge710d542015-08-07 16:16:36 +00006604 case OMPC_device:
6605 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6606 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006607 case OMPC_num_teams:
6608 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6609 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006610 case OMPC_thread_limit:
6611 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6612 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006613 case OMPC_priority:
6614 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6615 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006616 case OMPC_grainsize:
6617 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6618 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006619 case OMPC_num_tasks:
6620 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6621 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006622 case OMPC_hint:
6623 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6624 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006625 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006626 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006627 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006628 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006629 case OMPC_private:
6630 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006631 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006632 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006633 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006634 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006635 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006636 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006637 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006638 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006639 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006640 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006641 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006642 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006643 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006644 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006645 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006646 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006647 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006648 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006649 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006650 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006651 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006652 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006653 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006654 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006655 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006656 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006657 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006658 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006659 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006660 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006661 llvm_unreachable("Clause is not allowed.");
6662 }
6663 return Res;
6664}
6665
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006666// An OpenMP directive such as 'target parallel' has two captured regions:
6667// for the 'target' and 'parallel' respectively. This function returns
6668// the region in which to capture expressions associated with a clause.
6669// A return value of OMPD_unknown signifies that the expression should not
6670// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006671static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6672 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6673 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006674 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6675
6676 switch (CKind) {
6677 case OMPC_if:
6678 switch (DKind) {
6679 case OMPD_target_parallel:
6680 // If this clause applies to the nested 'parallel' region, capture within
6681 // the 'target' region, otherwise do not capture.
6682 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6683 CaptureRegion = OMPD_target;
6684 break;
6685 case OMPD_cancel:
6686 case OMPD_parallel:
6687 case OMPD_parallel_sections:
6688 case OMPD_parallel_for:
6689 case OMPD_parallel_for_simd:
6690 case OMPD_target:
6691 case OMPD_target_simd:
6692 case OMPD_target_parallel_for:
6693 case OMPD_target_parallel_for_simd:
6694 case OMPD_target_teams:
6695 case OMPD_target_teams_distribute:
6696 case OMPD_target_teams_distribute_simd:
6697 case OMPD_target_teams_distribute_parallel_for:
6698 case OMPD_target_teams_distribute_parallel_for_simd:
6699 case OMPD_teams_distribute_parallel_for:
6700 case OMPD_teams_distribute_parallel_for_simd:
6701 case OMPD_distribute_parallel_for:
6702 case OMPD_distribute_parallel_for_simd:
6703 case OMPD_task:
6704 case OMPD_taskloop:
6705 case OMPD_taskloop_simd:
6706 case OMPD_target_data:
6707 case OMPD_target_enter_data:
6708 case OMPD_target_exit_data:
6709 case OMPD_target_update:
6710 // Do not capture if-clause expressions.
6711 break;
6712 case OMPD_threadprivate:
6713 case OMPD_taskyield:
6714 case OMPD_barrier:
6715 case OMPD_taskwait:
6716 case OMPD_cancellation_point:
6717 case OMPD_flush:
6718 case OMPD_declare_reduction:
6719 case OMPD_declare_simd:
6720 case OMPD_declare_target:
6721 case OMPD_end_declare_target:
6722 case OMPD_teams:
6723 case OMPD_simd:
6724 case OMPD_for:
6725 case OMPD_for_simd:
6726 case OMPD_sections:
6727 case OMPD_section:
6728 case OMPD_single:
6729 case OMPD_master:
6730 case OMPD_critical:
6731 case OMPD_taskgroup:
6732 case OMPD_distribute:
6733 case OMPD_ordered:
6734 case OMPD_atomic:
6735 case OMPD_distribute_simd:
6736 case OMPD_teams_distribute:
6737 case OMPD_teams_distribute_simd:
6738 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6739 case OMPD_unknown:
6740 llvm_unreachable("Unknown OpenMP directive");
6741 }
6742 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006743 case OMPC_num_threads:
6744 switch (DKind) {
6745 case OMPD_target_parallel:
6746 CaptureRegion = OMPD_target;
6747 break;
6748 case OMPD_cancel:
6749 case OMPD_parallel:
6750 case OMPD_parallel_sections:
6751 case OMPD_parallel_for:
6752 case OMPD_parallel_for_simd:
6753 case OMPD_target:
6754 case OMPD_target_simd:
6755 case OMPD_target_parallel_for:
6756 case OMPD_target_parallel_for_simd:
6757 case OMPD_target_teams:
6758 case OMPD_target_teams_distribute:
6759 case OMPD_target_teams_distribute_simd:
6760 case OMPD_target_teams_distribute_parallel_for:
6761 case OMPD_target_teams_distribute_parallel_for_simd:
6762 case OMPD_teams_distribute_parallel_for:
6763 case OMPD_teams_distribute_parallel_for_simd:
6764 case OMPD_distribute_parallel_for:
6765 case OMPD_distribute_parallel_for_simd:
6766 case OMPD_task:
6767 case OMPD_taskloop:
6768 case OMPD_taskloop_simd:
6769 case OMPD_target_data:
6770 case OMPD_target_enter_data:
6771 case OMPD_target_exit_data:
6772 case OMPD_target_update:
6773 // Do not capture num_threads-clause expressions.
6774 break;
6775 case OMPD_threadprivate:
6776 case OMPD_taskyield:
6777 case OMPD_barrier:
6778 case OMPD_taskwait:
6779 case OMPD_cancellation_point:
6780 case OMPD_flush:
6781 case OMPD_declare_reduction:
6782 case OMPD_declare_simd:
6783 case OMPD_declare_target:
6784 case OMPD_end_declare_target:
6785 case OMPD_teams:
6786 case OMPD_simd:
6787 case OMPD_for:
6788 case OMPD_for_simd:
6789 case OMPD_sections:
6790 case OMPD_section:
6791 case OMPD_single:
6792 case OMPD_master:
6793 case OMPD_critical:
6794 case OMPD_taskgroup:
6795 case OMPD_distribute:
6796 case OMPD_ordered:
6797 case OMPD_atomic:
6798 case OMPD_distribute_simd:
6799 case OMPD_teams_distribute:
6800 case OMPD_teams_distribute_simd:
6801 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6802 case OMPD_unknown:
6803 llvm_unreachable("Unknown OpenMP directive");
6804 }
6805 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00006806 case OMPC_num_teams:
6807 switch (DKind) {
6808 case OMPD_target_teams:
6809 CaptureRegion = OMPD_target;
6810 break;
6811 case OMPD_cancel:
6812 case OMPD_parallel:
6813 case OMPD_parallel_sections:
6814 case OMPD_parallel_for:
6815 case OMPD_parallel_for_simd:
6816 case OMPD_target:
6817 case OMPD_target_simd:
6818 case OMPD_target_parallel:
6819 case OMPD_target_parallel_for:
6820 case OMPD_target_parallel_for_simd:
6821 case OMPD_target_teams_distribute:
6822 case OMPD_target_teams_distribute_simd:
6823 case OMPD_target_teams_distribute_parallel_for:
6824 case OMPD_target_teams_distribute_parallel_for_simd:
6825 case OMPD_teams_distribute_parallel_for:
6826 case OMPD_teams_distribute_parallel_for_simd:
6827 case OMPD_distribute_parallel_for:
6828 case OMPD_distribute_parallel_for_simd:
6829 case OMPD_task:
6830 case OMPD_taskloop:
6831 case OMPD_taskloop_simd:
6832 case OMPD_target_data:
6833 case OMPD_target_enter_data:
6834 case OMPD_target_exit_data:
6835 case OMPD_target_update:
6836 case OMPD_teams:
6837 case OMPD_teams_distribute:
6838 case OMPD_teams_distribute_simd:
6839 // Do not capture num_teams-clause expressions.
6840 break;
6841 case OMPD_threadprivate:
6842 case OMPD_taskyield:
6843 case OMPD_barrier:
6844 case OMPD_taskwait:
6845 case OMPD_cancellation_point:
6846 case OMPD_flush:
6847 case OMPD_declare_reduction:
6848 case OMPD_declare_simd:
6849 case OMPD_declare_target:
6850 case OMPD_end_declare_target:
6851 case OMPD_simd:
6852 case OMPD_for:
6853 case OMPD_for_simd:
6854 case OMPD_sections:
6855 case OMPD_section:
6856 case OMPD_single:
6857 case OMPD_master:
6858 case OMPD_critical:
6859 case OMPD_taskgroup:
6860 case OMPD_distribute:
6861 case OMPD_ordered:
6862 case OMPD_atomic:
6863 case OMPD_distribute_simd:
6864 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
6865 case OMPD_unknown:
6866 llvm_unreachable("Unknown OpenMP directive");
6867 }
6868 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00006869 case OMPC_thread_limit:
6870 switch (DKind) {
6871 case OMPD_target_teams:
6872 CaptureRegion = OMPD_target;
6873 break;
6874 case OMPD_cancel:
6875 case OMPD_parallel:
6876 case OMPD_parallel_sections:
6877 case OMPD_parallel_for:
6878 case OMPD_parallel_for_simd:
6879 case OMPD_target:
6880 case OMPD_target_simd:
6881 case OMPD_target_parallel:
6882 case OMPD_target_parallel_for:
6883 case OMPD_target_parallel_for_simd:
6884 case OMPD_target_teams_distribute:
6885 case OMPD_target_teams_distribute_simd:
6886 case OMPD_target_teams_distribute_parallel_for:
6887 case OMPD_target_teams_distribute_parallel_for_simd:
6888 case OMPD_teams_distribute_parallel_for:
6889 case OMPD_teams_distribute_parallel_for_simd:
6890 case OMPD_distribute_parallel_for:
6891 case OMPD_distribute_parallel_for_simd:
6892 case OMPD_task:
6893 case OMPD_taskloop:
6894 case OMPD_taskloop_simd:
6895 case OMPD_target_data:
6896 case OMPD_target_enter_data:
6897 case OMPD_target_exit_data:
6898 case OMPD_target_update:
6899 case OMPD_teams:
6900 case OMPD_teams_distribute:
6901 case OMPD_teams_distribute_simd:
6902 // Do not capture thread_limit-clause expressions.
6903 break;
6904 case OMPD_threadprivate:
6905 case OMPD_taskyield:
6906 case OMPD_barrier:
6907 case OMPD_taskwait:
6908 case OMPD_cancellation_point:
6909 case OMPD_flush:
6910 case OMPD_declare_reduction:
6911 case OMPD_declare_simd:
6912 case OMPD_declare_target:
6913 case OMPD_end_declare_target:
6914 case OMPD_simd:
6915 case OMPD_for:
6916 case OMPD_for_simd:
6917 case OMPD_sections:
6918 case OMPD_section:
6919 case OMPD_single:
6920 case OMPD_master:
6921 case OMPD_critical:
6922 case OMPD_taskgroup:
6923 case OMPD_distribute:
6924 case OMPD_ordered:
6925 case OMPD_atomic:
6926 case OMPD_distribute_simd:
6927 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
6928 case OMPD_unknown:
6929 llvm_unreachable("Unknown OpenMP directive");
6930 }
6931 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006932 case OMPC_schedule:
6933 case OMPC_dist_schedule:
6934 case OMPC_firstprivate:
6935 case OMPC_lastprivate:
6936 case OMPC_reduction:
6937 case OMPC_linear:
6938 case OMPC_default:
6939 case OMPC_proc_bind:
6940 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006941 case OMPC_safelen:
6942 case OMPC_simdlen:
6943 case OMPC_collapse:
6944 case OMPC_private:
6945 case OMPC_shared:
6946 case OMPC_aligned:
6947 case OMPC_copyin:
6948 case OMPC_copyprivate:
6949 case OMPC_ordered:
6950 case OMPC_nowait:
6951 case OMPC_untied:
6952 case OMPC_mergeable:
6953 case OMPC_threadprivate:
6954 case OMPC_flush:
6955 case OMPC_read:
6956 case OMPC_write:
6957 case OMPC_update:
6958 case OMPC_capture:
6959 case OMPC_seq_cst:
6960 case OMPC_depend:
6961 case OMPC_device:
6962 case OMPC_threads:
6963 case OMPC_simd:
6964 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006965 case OMPC_priority:
6966 case OMPC_grainsize:
6967 case OMPC_nogroup:
6968 case OMPC_num_tasks:
6969 case OMPC_hint:
6970 case OMPC_defaultmap:
6971 case OMPC_unknown:
6972 case OMPC_uniform:
6973 case OMPC_to:
6974 case OMPC_from:
6975 case OMPC_use_device_ptr:
6976 case OMPC_is_device_ptr:
6977 llvm_unreachable("Unexpected OpenMP clause.");
6978 }
6979 return CaptureRegion;
6980}
6981
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006982OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6983 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006984 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006985 SourceLocation NameModifierLoc,
6986 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006987 SourceLocation EndLoc) {
6988 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006989 Stmt *HelperValStmt = nullptr;
6990 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006991 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6992 !Condition->isInstantiationDependent() &&
6993 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006994 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006995 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006996 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006997
Richard Smith03a4aa32016-06-23 19:02:52 +00006998 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006999
7000 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7001 CaptureRegion =
7002 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7003 if (CaptureRegion != OMPD_unknown) {
7004 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7005 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7006 HelperValStmt = buildPreInits(Context, Captures);
7007 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007008 }
7009
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007010 return new (Context)
7011 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7012 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007013}
7014
Alexey Bataev3778b602014-07-17 07:32:53 +00007015OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7016 SourceLocation StartLoc,
7017 SourceLocation LParenLoc,
7018 SourceLocation EndLoc) {
7019 Expr *ValExpr = Condition;
7020 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7021 !Condition->isInstantiationDependent() &&
7022 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007023 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007024 if (Val.isInvalid())
7025 return nullptr;
7026
Richard Smith03a4aa32016-06-23 19:02:52 +00007027 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007028 }
7029
7030 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7031}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007032ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7033 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007034 if (!Op)
7035 return ExprError();
7036
7037 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7038 public:
7039 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007040 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007041 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7042 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007043 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7044 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007045 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7046 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007047 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7048 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007049 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7050 QualType T,
7051 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007052 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7053 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007054 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7055 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007056 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007057 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007058 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007059 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7060 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007061 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7062 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007063 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7064 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007065 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007066 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007067 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007068 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7069 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007070 llvm_unreachable("conversion functions are permitted");
7071 }
7072 } ConvertDiagnoser;
7073 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7074}
7075
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007076static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007077 OpenMPClauseKind CKind,
7078 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007079 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7080 !ValExpr->isInstantiationDependent()) {
7081 SourceLocation Loc = ValExpr->getExprLoc();
7082 ExprResult Value =
7083 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7084 if (Value.isInvalid())
7085 return false;
7086
7087 ValExpr = Value.get();
7088 // The expression must evaluate to a non-negative integer value.
7089 llvm::APSInt Result;
7090 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007091 Result.isSigned() &&
7092 !((!StrictlyPositive && Result.isNonNegative()) ||
7093 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007094 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007095 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7096 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007097 return false;
7098 }
7099 }
7100 return true;
7101}
7102
Alexey Bataev568a8332014-03-06 06:15:19 +00007103OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7104 SourceLocation StartLoc,
7105 SourceLocation LParenLoc,
7106 SourceLocation EndLoc) {
7107 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007108 Stmt *HelperValStmt = nullptr;
7109 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007110
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007111 // OpenMP [2.5, Restrictions]
7112 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007113 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7114 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007115 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007116
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007117 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7118 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7119 if (CaptureRegion != OMPD_unknown) {
7120 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7121 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7122 HelperValStmt = buildPreInits(Context, Captures);
7123 }
7124
7125 return new (Context) OMPNumThreadsClause(
7126 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007127}
7128
Alexey Bataev62c87d22014-03-21 04:51:18 +00007129ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007130 OpenMPClauseKind CKind,
7131 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007132 if (!E)
7133 return ExprError();
7134 if (E->isValueDependent() || E->isTypeDependent() ||
7135 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007136 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007137 llvm::APSInt Result;
7138 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7139 if (ICE.isInvalid())
7140 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007141 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7142 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007143 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007144 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7145 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007146 return ExprError();
7147 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007148 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7149 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7150 << E->getSourceRange();
7151 return ExprError();
7152 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007153 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7154 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007155 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007156 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007157 return ICE;
7158}
7159
7160OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7161 SourceLocation LParenLoc,
7162 SourceLocation EndLoc) {
7163 // OpenMP [2.8.1, simd construct, Description]
7164 // The parameter of the safelen clause must be a constant
7165 // positive integer expression.
7166 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7167 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007168 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007169 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007170 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007171}
7172
Alexey Bataev66b15b52015-08-21 11:14:16 +00007173OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7174 SourceLocation LParenLoc,
7175 SourceLocation EndLoc) {
7176 // OpenMP [2.8.1, simd construct, Description]
7177 // The parameter of the simdlen clause must be a constant
7178 // positive integer expression.
7179 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7180 if (Simdlen.isInvalid())
7181 return nullptr;
7182 return new (Context)
7183 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7184}
7185
Alexander Musman64d33f12014-06-04 07:53:32 +00007186OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7187 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007188 SourceLocation LParenLoc,
7189 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007190 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007191 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007192 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007193 // The parameter of the collapse clause must be a constant
7194 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007195 ExprResult NumForLoopsResult =
7196 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7197 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007198 return nullptr;
7199 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007200 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007201}
7202
Alexey Bataev10e775f2015-07-30 11:36:16 +00007203OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7204 SourceLocation EndLoc,
7205 SourceLocation LParenLoc,
7206 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007207 // OpenMP [2.7.1, loop construct, Description]
7208 // OpenMP [2.8.1, simd construct, Description]
7209 // OpenMP [2.9.6, distribute construct, Description]
7210 // The parameter of the ordered clause must be a constant
7211 // positive integer expression if any.
7212 if (NumForLoops && LParenLoc.isValid()) {
7213 ExprResult NumForLoopsResult =
7214 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7215 if (NumForLoopsResult.isInvalid())
7216 return nullptr;
7217 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007218 } else
7219 NumForLoops = nullptr;
7220 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007221 return new (Context)
7222 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7223}
7224
Alexey Bataeved09d242014-05-28 05:53:51 +00007225OMPClause *Sema::ActOnOpenMPSimpleClause(
7226 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7227 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007228 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007229 switch (Kind) {
7230 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007231 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007232 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7233 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007234 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007235 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007236 Res = ActOnOpenMPProcBindClause(
7237 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7238 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007239 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007240 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007241 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007242 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007243 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007244 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007245 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007246 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007247 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007248 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007249 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007250 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007251 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007252 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007253 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007254 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007255 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007256 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007257 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007258 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007259 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007260 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007261 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007262 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007263 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007264 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007265 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007266 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007267 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007268 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007269 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007270 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007271 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007272 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007273 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007274 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007275 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007276 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007277 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007278 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007279 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007280 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007281 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007282 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007283 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007284 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007285 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007286 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007287 llvm_unreachable("Clause is not allowed.");
7288 }
7289 return Res;
7290}
7291
Alexey Bataev6402bca2015-12-28 07:25:51 +00007292static std::string
7293getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7294 ArrayRef<unsigned> Exclude = llvm::None) {
7295 std::string Values;
7296 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7297 unsigned Skipped = Exclude.size();
7298 auto S = Exclude.begin(), E = Exclude.end();
7299 for (unsigned i = First; i < Last; ++i) {
7300 if (std::find(S, E, i) != E) {
7301 --Skipped;
7302 continue;
7303 }
7304 Values += "'";
7305 Values += getOpenMPSimpleClauseTypeName(K, i);
7306 Values += "'";
7307 if (i == Bound - Skipped)
7308 Values += " or ";
7309 else if (i != Bound + 1 - Skipped)
7310 Values += ", ";
7311 }
7312 return Values;
7313}
7314
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007315OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7316 SourceLocation KindKwLoc,
7317 SourceLocation StartLoc,
7318 SourceLocation LParenLoc,
7319 SourceLocation EndLoc) {
7320 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007321 static_assert(OMPC_DEFAULT_unknown > 0,
7322 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007323 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007324 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7325 /*Last=*/OMPC_DEFAULT_unknown)
7326 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007327 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007328 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007329 switch (Kind) {
7330 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007331 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007332 break;
7333 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007334 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007335 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007336 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007337 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007338 break;
7339 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007340 return new (Context)
7341 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007342}
7343
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007344OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7345 SourceLocation KindKwLoc,
7346 SourceLocation StartLoc,
7347 SourceLocation LParenLoc,
7348 SourceLocation EndLoc) {
7349 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007350 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007351 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7352 /*Last=*/OMPC_PROC_BIND_unknown)
7353 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007354 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007355 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007356 return new (Context)
7357 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007358}
7359
Alexey Bataev56dafe82014-06-20 07:16:17 +00007360OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007361 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007362 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007363 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007364 SourceLocation EndLoc) {
7365 OMPClause *Res = nullptr;
7366 switch (Kind) {
7367 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007368 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7369 assert(Argument.size() == NumberOfElements &&
7370 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007371 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007372 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7373 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7374 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7375 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7376 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007377 break;
7378 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007379 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7380 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7381 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7382 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007383 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007384 case OMPC_dist_schedule:
7385 Res = ActOnOpenMPDistScheduleClause(
7386 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7387 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7388 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007389 case OMPC_defaultmap:
7390 enum { Modifier, DefaultmapKind };
7391 Res = ActOnOpenMPDefaultmapClause(
7392 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7393 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007394 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7395 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007396 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007397 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007398 case OMPC_num_threads:
7399 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007400 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007401 case OMPC_collapse:
7402 case OMPC_default:
7403 case OMPC_proc_bind:
7404 case OMPC_private:
7405 case OMPC_firstprivate:
7406 case OMPC_lastprivate:
7407 case OMPC_shared:
7408 case OMPC_reduction:
7409 case OMPC_linear:
7410 case OMPC_aligned:
7411 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007412 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007413 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007414 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007415 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007416 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007417 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007418 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007419 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007420 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007421 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007422 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007423 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007424 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007425 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007426 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007427 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007428 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007429 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007430 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007431 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007432 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007433 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007434 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007435 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007436 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007437 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007438 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007439 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007440 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007441 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007442 llvm_unreachable("Clause is not allowed.");
7443 }
7444 return Res;
7445}
7446
Alexey Bataev6402bca2015-12-28 07:25:51 +00007447static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7448 OpenMPScheduleClauseModifier M2,
7449 SourceLocation M1Loc, SourceLocation M2Loc) {
7450 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7451 SmallVector<unsigned, 2> Excluded;
7452 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7453 Excluded.push_back(M2);
7454 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7455 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7456 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7457 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7458 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7459 << getListOfPossibleValues(OMPC_schedule,
7460 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7461 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7462 Excluded)
7463 << getOpenMPClauseName(OMPC_schedule);
7464 return true;
7465 }
7466 return false;
7467}
7468
Alexey Bataev56dafe82014-06-20 07:16:17 +00007469OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007470 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007471 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007472 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7473 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7474 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7475 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7476 return nullptr;
7477 // OpenMP, 2.7.1, Loop Construct, Restrictions
7478 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7479 // but not both.
7480 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7481 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7482 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7483 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7484 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7485 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7486 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7487 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7488 return nullptr;
7489 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007490 if (Kind == OMPC_SCHEDULE_unknown) {
7491 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007492 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7493 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7494 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7495 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7496 Exclude);
7497 } else {
7498 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7499 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007500 }
7501 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7502 << Values << getOpenMPClauseName(OMPC_schedule);
7503 return nullptr;
7504 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007505 // OpenMP, 2.7.1, Loop Construct, Restrictions
7506 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7507 // schedule(guided).
7508 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7509 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7510 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7511 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7512 diag::err_omp_schedule_nonmonotonic_static);
7513 return nullptr;
7514 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007515 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007516 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007517 if (ChunkSize) {
7518 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7519 !ChunkSize->isInstantiationDependent() &&
7520 !ChunkSize->containsUnexpandedParameterPack()) {
7521 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7522 ExprResult Val =
7523 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7524 if (Val.isInvalid())
7525 return nullptr;
7526
7527 ValExpr = Val.get();
7528
7529 // OpenMP [2.7.1, Restrictions]
7530 // chunk_size must be a loop invariant integer expression with a positive
7531 // value.
7532 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007533 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7534 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7535 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007536 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007537 return nullptr;
7538 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007539 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7540 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007541 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7542 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7543 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007544 }
7545 }
7546 }
7547
Alexey Bataev6402bca2015-12-28 07:25:51 +00007548 return new (Context)
7549 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007550 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007551}
7552
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007553OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7554 SourceLocation StartLoc,
7555 SourceLocation EndLoc) {
7556 OMPClause *Res = nullptr;
7557 switch (Kind) {
7558 case OMPC_ordered:
7559 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7560 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007561 case OMPC_nowait:
7562 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7563 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007564 case OMPC_untied:
7565 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7566 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007567 case OMPC_mergeable:
7568 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7569 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007570 case OMPC_read:
7571 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7572 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007573 case OMPC_write:
7574 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7575 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007576 case OMPC_update:
7577 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7578 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007579 case OMPC_capture:
7580 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7581 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007582 case OMPC_seq_cst:
7583 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7584 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007585 case OMPC_threads:
7586 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7587 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007588 case OMPC_simd:
7589 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7590 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007591 case OMPC_nogroup:
7592 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7593 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007594 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007595 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007596 case OMPC_num_threads:
7597 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007598 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007599 case OMPC_collapse:
7600 case OMPC_schedule:
7601 case OMPC_private:
7602 case OMPC_firstprivate:
7603 case OMPC_lastprivate:
7604 case OMPC_shared:
7605 case OMPC_reduction:
7606 case OMPC_linear:
7607 case OMPC_aligned:
7608 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007609 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007610 case OMPC_default:
7611 case OMPC_proc_bind:
7612 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007613 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007614 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007615 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007616 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007617 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007618 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007619 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007620 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007621 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007622 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007623 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007624 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007625 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007626 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007627 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007628 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007629 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007630 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007631 llvm_unreachable("Clause is not allowed.");
7632 }
7633 return Res;
7634}
7635
Alexey Bataev236070f2014-06-20 11:19:47 +00007636OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7637 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007638 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007639 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7640}
7641
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007642OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7643 SourceLocation EndLoc) {
7644 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7645}
7646
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007647OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7648 SourceLocation EndLoc) {
7649 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7650}
7651
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007652OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7653 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007654 return new (Context) OMPReadClause(StartLoc, EndLoc);
7655}
7656
Alexey Bataevdea47612014-07-23 07:46:59 +00007657OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7658 SourceLocation EndLoc) {
7659 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7660}
7661
Alexey Bataev67a4f222014-07-23 10:25:33 +00007662OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7663 SourceLocation EndLoc) {
7664 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7665}
7666
Alexey Bataev459dec02014-07-24 06:46:57 +00007667OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7668 SourceLocation EndLoc) {
7669 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7670}
7671
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007672OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7673 SourceLocation EndLoc) {
7674 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7675}
7676
Alexey Bataev346265e2015-09-25 10:37:12 +00007677OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7678 SourceLocation EndLoc) {
7679 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7680}
7681
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007682OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7683 SourceLocation EndLoc) {
7684 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7685}
7686
Alexey Bataevb825de12015-12-07 10:51:44 +00007687OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7688 SourceLocation EndLoc) {
7689 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7690}
7691
Alexey Bataevc5e02582014-06-16 07:08:35 +00007692OMPClause *Sema::ActOnOpenMPVarListClause(
7693 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7694 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7695 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007696 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007697 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7698 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7699 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007700 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007701 switch (Kind) {
7702 case OMPC_private:
7703 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7704 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007705 case OMPC_firstprivate:
7706 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7707 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007708 case OMPC_lastprivate:
7709 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7710 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007711 case OMPC_shared:
7712 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7713 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007714 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007715 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7716 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007717 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007718 case OMPC_linear:
7719 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007720 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007721 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007722 case OMPC_aligned:
7723 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7724 ColonLoc, EndLoc);
7725 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007726 case OMPC_copyin:
7727 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7728 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007729 case OMPC_copyprivate:
7730 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7731 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007732 case OMPC_flush:
7733 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7734 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007735 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007736 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007737 StartLoc, LParenLoc, EndLoc);
7738 break;
7739 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007740 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7741 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7742 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007743 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007744 case OMPC_to:
7745 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7746 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007747 case OMPC_from:
7748 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7749 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007750 case OMPC_use_device_ptr:
7751 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7752 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007753 case OMPC_is_device_ptr:
7754 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7755 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007756 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007757 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007758 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007759 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007760 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007761 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007762 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007763 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007764 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007765 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007766 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007767 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007768 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007769 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007770 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007771 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007772 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007773 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007774 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007775 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007776 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007777 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007778 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007779 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007780 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007781 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007782 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007783 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007784 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007785 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007786 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007787 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007788 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007789 llvm_unreachable("Clause is not allowed.");
7790 }
7791 return Res;
7792}
7793
Alexey Bataev90c228f2016-02-08 09:29:13 +00007794ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007795 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007796 ExprResult Res = BuildDeclRefExpr(
7797 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7798 if (!Res.isUsable())
7799 return ExprError();
7800 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7801 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7802 if (!Res.isUsable())
7803 return ExprError();
7804 }
7805 if (VK != VK_LValue && Res.get()->isGLValue()) {
7806 Res = DefaultLvalueConversion(Res.get());
7807 if (!Res.isUsable())
7808 return ExprError();
7809 }
7810 return Res;
7811}
7812
Alexey Bataev60da77e2016-02-29 05:54:20 +00007813static std::pair<ValueDecl *, bool>
7814getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7815 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007816 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7817 RefExpr->containsUnexpandedParameterPack())
7818 return std::make_pair(nullptr, true);
7819
Alexey Bataevd985eda2016-02-10 11:29:16 +00007820 // OpenMP [3.1, C/C++]
7821 // A list item is a variable name.
7822 // OpenMP [2.9.3.3, Restrictions, p.1]
7823 // A variable that is part of another variable (as an array or
7824 // structure element) cannot appear in a private clause.
7825 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007826 enum {
7827 NoArrayExpr = -1,
7828 ArraySubscript = 0,
7829 OMPArraySection = 1
7830 } IsArrayExpr = NoArrayExpr;
7831 if (AllowArraySection) {
7832 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7833 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7834 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7835 Base = TempASE->getBase()->IgnoreParenImpCasts();
7836 RefExpr = Base;
7837 IsArrayExpr = ArraySubscript;
7838 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7839 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7840 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7841 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7842 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7843 Base = TempASE->getBase()->IgnoreParenImpCasts();
7844 RefExpr = Base;
7845 IsArrayExpr = OMPArraySection;
7846 }
7847 }
7848 ELoc = RefExpr->getExprLoc();
7849 ERange = RefExpr->getSourceRange();
7850 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007851 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7852 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7853 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7854 (S.getCurrentThisType().isNull() || !ME ||
7855 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7856 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007857 if (IsArrayExpr != NoArrayExpr)
7858 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7859 << ERange;
7860 else {
7861 S.Diag(ELoc,
7862 AllowArraySection
7863 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7864 : diag::err_omp_expected_var_name_member_expr)
7865 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7866 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007867 return std::make_pair(nullptr, false);
7868 }
7869 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7870}
7871
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007872OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7873 SourceLocation StartLoc,
7874 SourceLocation LParenLoc,
7875 SourceLocation EndLoc) {
7876 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007877 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007878 for (auto &RefExpr : VarList) {
7879 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007880 SourceLocation ELoc;
7881 SourceRange ERange;
7882 Expr *SimpleRefExpr = RefExpr;
7883 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007884 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007885 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007886 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007887 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007888 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007889 ValueDecl *D = Res.first;
7890 if (!D)
7891 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007892
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007893 QualType Type = D->getType();
7894 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007895
7896 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7897 // A variable that appears in a private clause must not have an incomplete
7898 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007899 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007900 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007901 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007902
Alexey Bataev758e55e2013-09-06 18:03:48 +00007903 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7904 // in a Construct]
7905 // Variables with the predetermined data-sharing attributes may not be
7906 // listed in data-sharing attributes clauses, except for the cases
7907 // listed below. For these exceptions only, listing a predetermined
7908 // variable in a data-sharing attribute clause is allowed and overrides
7909 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007910 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007911 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007912 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7913 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007914 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007915 continue;
7916 }
7917
Kelvin Libf594a52016-12-17 05:48:59 +00007918 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007919 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007920 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007921 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007922 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7923 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007924 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007925 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007926 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007927 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007928 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007929 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007930 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007931 continue;
7932 }
7933
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007934 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7935 // A list item cannot appear in both a map clause and a data-sharing
7936 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007937 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007938 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007939 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007940 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007941 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007942 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007943 CurrDir == OMPD_target_parallel_for_simd ||
7944 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007945 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007946 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007947 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007948 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7949 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7950 ConflictKind = WhereFoundClauseKind;
7951 return true;
7952 })) {
7953 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007954 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007955 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007956 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007957 ReportOriginalDSA(*this, DSAStack, D, DVar);
7958 continue;
7959 }
7960 }
7961
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007962 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7963 // A variable of class type (or array thereof) that appears in a private
7964 // clause requires an accessible, unambiguous default constructor for the
7965 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007966 // Generate helper private variable and initialize it with the default
7967 // value. The address of the original variable is replaced by the address of
7968 // the new private variable in CodeGen. This new variable is not added to
7969 // IdResolver, so the code in the OpenMP region uses original variable for
7970 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007971 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007972 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7973 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00007974 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007975 if (VDPrivate->isInvalidDecl())
7976 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007977 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007978 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007979
Alexey Bataev90c228f2016-02-08 09:29:13 +00007980 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007981 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007982 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007983 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007984 Vars.push_back((VD || CurContext->isDependentContext())
7985 ? RefExpr->IgnoreParens()
7986 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007987 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007988 }
7989
Alexey Bataeved09d242014-05-28 05:53:51 +00007990 if (Vars.empty())
7991 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007992
Alexey Bataev03b340a2014-10-21 03:16:40 +00007993 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7994 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007995}
7996
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007997namespace {
7998class DiagsUninitializedSeveretyRAII {
7999private:
8000 DiagnosticsEngine &Diags;
8001 SourceLocation SavedLoc;
8002 bool IsIgnored;
8003
8004public:
8005 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8006 bool IsIgnored)
8007 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8008 if (!IsIgnored) {
8009 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8010 /*Map*/ diag::Severity::Ignored, Loc);
8011 }
8012 }
8013 ~DiagsUninitializedSeveretyRAII() {
8014 if (!IsIgnored)
8015 Diags.popMappings(SavedLoc);
8016 }
8017};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008018}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008019
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008020OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8021 SourceLocation StartLoc,
8022 SourceLocation LParenLoc,
8023 SourceLocation EndLoc) {
8024 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008025 SmallVector<Expr *, 8> PrivateCopies;
8026 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008027 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008028 bool IsImplicitClause =
8029 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8030 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8031
Alexey Bataeved09d242014-05-28 05:53:51 +00008032 for (auto &RefExpr : VarList) {
8033 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008034 SourceLocation ELoc;
8035 SourceRange ERange;
8036 Expr *SimpleRefExpr = RefExpr;
8037 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008038 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008039 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008040 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008041 PrivateCopies.push_back(nullptr);
8042 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008043 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008044 ValueDecl *D = Res.first;
8045 if (!D)
8046 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008047
Alexey Bataev60da77e2016-02-29 05:54:20 +00008048 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008049 QualType Type = D->getType();
8050 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008051
8052 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8053 // A variable that appears in a private clause must not have an incomplete
8054 // type or a reference type.
8055 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008056 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008057 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008058 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008059
8060 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8061 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008062 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008063 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008064 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008065
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008066 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008067 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008068 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008069 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008070 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008071 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008072 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8073 // A list item that specifies a given variable may not appear in more
8074 // than one clause on the same directive, except that a variable may be
8075 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008076 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00008077 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008078 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008079 << getOpenMPClauseName(DVar.CKind)
8080 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008081 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008082 continue;
8083 }
8084
8085 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8086 // in a Construct]
8087 // Variables with the predetermined data-sharing attributes may not be
8088 // listed in data-sharing attributes clauses, except for the cases
8089 // listed below. For these exceptions only, listing a predetermined
8090 // variable in a data-sharing attribute clause is allowed and overrides
8091 // the variable's predetermined data-sharing attributes.
8092 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8093 // in a Construct, C/C++, p.2]
8094 // Variables with const-qualified type having no mutable member may be
8095 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008096 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008097 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8098 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008099 << getOpenMPClauseName(DVar.CKind)
8100 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008101 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008102 continue;
8103 }
8104
Alexey Bataevf29276e2014-06-18 04:14:57 +00008105 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008106 // OpenMP [2.9.3.4, Restrictions, p.2]
8107 // A list item that is private within a parallel region must not appear
8108 // in a firstprivate clause on a worksharing construct if any of the
8109 // worksharing regions arising from the worksharing construct ever bind
8110 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00008111 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008112 !isOpenMPParallelDirective(CurrDir) &&
8113 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008114 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008115 if (DVar.CKind != OMPC_shared &&
8116 (isOpenMPParallelDirective(DVar.DKind) ||
8117 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008118 Diag(ELoc, diag::err_omp_required_access)
8119 << getOpenMPClauseName(OMPC_firstprivate)
8120 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008121 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008122 continue;
8123 }
8124 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008125 // OpenMP [2.9.3.4, Restrictions, p.3]
8126 // A list item that appears in a reduction clause of a parallel construct
8127 // must not appear in a firstprivate clause on a worksharing or task
8128 // construct if any of the worksharing or task regions arising from the
8129 // worksharing or task construct ever bind to any of the parallel regions
8130 // arising from the parallel construct.
8131 // OpenMP [2.9.3.4, Restrictions, p.4]
8132 // A list item that appears in a reduction clause in worksharing
8133 // construct must not appear in a firstprivate clause in a task construct
8134 // encountered during execution of any of the worksharing regions arising
8135 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008136 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008137 DVar = DSAStack->hasInnermostDSA(
8138 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8139 [](OpenMPDirectiveKind K) -> bool {
8140 return isOpenMPParallelDirective(K) ||
8141 isOpenMPWorksharingDirective(K);
8142 },
8143 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008144 if (DVar.CKind == OMPC_reduction &&
8145 (isOpenMPParallelDirective(DVar.DKind) ||
8146 isOpenMPWorksharingDirective(DVar.DKind))) {
8147 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8148 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008149 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008150 continue;
8151 }
8152 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008153
8154 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8155 // A list item that is private within a teams region must not appear in a
8156 // firstprivate clause on a distribute construct if any of the distribute
8157 // regions arising from the distribute construct ever bind to any of the
8158 // teams regions arising from the teams construct.
8159 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8160 // A list item that appears in a reduction clause of a teams construct
8161 // must not appear in a firstprivate clause on a distribute construct if
8162 // any of the distribute regions arising from the distribute construct
8163 // ever bind to any of the teams regions arising from the teams construct.
8164 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8165 // A list item may appear in a firstprivate or lastprivate clause but not
8166 // both.
8167 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008168 DVar = DSAStack->hasInnermostDSA(
8169 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8170 [](OpenMPDirectiveKind K) -> bool {
8171 return isOpenMPTeamsDirective(K);
8172 },
8173 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008174 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8175 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008176 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008177 continue;
8178 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008179 DVar = DSAStack->hasInnermostDSA(
8180 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8181 [](OpenMPDirectiveKind K) -> bool {
8182 return isOpenMPTeamsDirective(K);
8183 },
8184 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008185 if (DVar.CKind == OMPC_reduction &&
8186 isOpenMPTeamsDirective(DVar.DKind)) {
8187 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008188 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008189 continue;
8190 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008191 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008192 if (DVar.CKind == OMPC_lastprivate) {
8193 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008194 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008195 continue;
8196 }
8197 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008198 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8199 // A list item cannot appear in both a map clause and a data-sharing
8200 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008201 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008202 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008203 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008204 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008205 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008206 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008207 CurrDir == OMPD_target_parallel_for_simd ||
8208 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008209 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008210 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008211 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008212 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8213 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8214 ConflictKind = WhereFoundClauseKind;
8215 return true;
8216 })) {
8217 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008218 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008219 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008220 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8221 ReportOriginalDSA(*this, DSAStack, D, DVar);
8222 continue;
8223 }
8224 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008225 }
8226
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008227 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008228 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008229 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008230 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8231 << getOpenMPClauseName(OMPC_firstprivate) << Type
8232 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8233 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008234 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008235 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008236 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008237 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008238 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008239 continue;
8240 }
8241
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008242 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008243 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8244 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008245 // Generate helper private variable and initialize it with the value of the
8246 // original variable. The address of the original variable is replaced by
8247 // the address of the new private variable in the CodeGen. This new variable
8248 // is not added to IdResolver, so the code in the OpenMP region uses
8249 // original variable for proper diagnostics and variable capturing.
8250 Expr *VDInitRefExpr = nullptr;
8251 // For arrays generate initializer for single element and replace it by the
8252 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008253 if (Type->isArrayType()) {
8254 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008255 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008256 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008257 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008258 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008259 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008260 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008261 InitializedEntity Entity =
8262 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008263 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8264
8265 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8266 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8267 if (Result.isInvalid())
8268 VDPrivate->setInvalidDecl();
8269 else
8270 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008271 // Remove temp variable declaration.
8272 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008273 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008274 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8275 ".firstprivate.temp");
8276 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8277 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008278 AddInitializerToDecl(VDPrivate,
8279 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008280 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008281 }
8282 if (VDPrivate->isInvalidDecl()) {
8283 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008284 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008285 diag::note_omp_task_predetermined_firstprivate_here);
8286 }
8287 continue;
8288 }
8289 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008290 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008291 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8292 RefExpr->getExprLoc());
8293 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008294 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008295 if (TopDVar.CKind == OMPC_lastprivate)
8296 Ref = TopDVar.PrivateCopy;
8297 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008298 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008299 if (!IsOpenMPCapturedDecl(D))
8300 ExprCaptures.push_back(Ref->getDecl());
8301 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008302 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008303 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008304 Vars.push_back((VD || CurContext->isDependentContext())
8305 ? RefExpr->IgnoreParens()
8306 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008307 PrivateCopies.push_back(VDPrivateRefExpr);
8308 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008309 }
8310
Alexey Bataeved09d242014-05-28 05:53:51 +00008311 if (Vars.empty())
8312 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008313
8314 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008315 Vars, PrivateCopies, Inits,
8316 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008317}
8318
Alexander Musman1bb328c2014-06-04 13:06:39 +00008319OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8320 SourceLocation StartLoc,
8321 SourceLocation LParenLoc,
8322 SourceLocation EndLoc) {
8323 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008324 SmallVector<Expr *, 8> SrcExprs;
8325 SmallVector<Expr *, 8> DstExprs;
8326 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008327 SmallVector<Decl *, 4> ExprCaptures;
8328 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008329 for (auto &RefExpr : VarList) {
8330 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008331 SourceLocation ELoc;
8332 SourceRange ERange;
8333 Expr *SimpleRefExpr = RefExpr;
8334 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008335 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008336 // It will be analyzed later.
8337 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008338 SrcExprs.push_back(nullptr);
8339 DstExprs.push_back(nullptr);
8340 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008341 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008342 ValueDecl *D = Res.first;
8343 if (!D)
8344 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008345
Alexey Bataev74caaf22016-02-20 04:09:36 +00008346 QualType Type = D->getType();
8347 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008348
8349 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8350 // A variable that appears in a lastprivate clause must not have an
8351 // incomplete type or a reference type.
8352 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008353 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008354 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008355 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008356
8357 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8358 // in a Construct]
8359 // Variables with the predetermined data-sharing attributes may not be
8360 // listed in data-sharing attributes clauses, except for the cases
8361 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008362 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008363 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8364 DVar.CKind != OMPC_firstprivate &&
8365 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8366 Diag(ELoc, diag::err_omp_wrong_dsa)
8367 << getOpenMPClauseName(DVar.CKind)
8368 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008369 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008370 continue;
8371 }
8372
Alexey Bataevf29276e2014-06-18 04:14:57 +00008373 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8374 // OpenMP [2.14.3.5, Restrictions, p.2]
8375 // A list item that is private within a parallel region, or that appears in
8376 // the reduction clause of a parallel construct, must not appear in a
8377 // lastprivate clause on a worksharing construct if any of the corresponding
8378 // worksharing regions ever binds to any of the corresponding parallel
8379 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008380 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008381 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008382 !isOpenMPParallelDirective(CurrDir) &&
8383 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008384 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008385 if (DVar.CKind != OMPC_shared) {
8386 Diag(ELoc, diag::err_omp_required_access)
8387 << getOpenMPClauseName(OMPC_lastprivate)
8388 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008389 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008390 continue;
8391 }
8392 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008393
8394 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8395 // A list item may appear in a firstprivate or lastprivate clause but not
8396 // both.
8397 if (CurrDir == OMPD_distribute) {
8398 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8399 if (DVar.CKind == OMPC_firstprivate) {
8400 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8401 ReportOriginalDSA(*this, DSAStack, D, DVar);
8402 continue;
8403 }
8404 }
8405
Alexander Musman1bb328c2014-06-04 13:06:39 +00008406 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008407 // A variable of class type (or array thereof) that appears in a
8408 // lastprivate clause requires an accessible, unambiguous default
8409 // constructor for the class type, unless the list item is also specified
8410 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008411 // A variable of class type (or array thereof) that appears in a
8412 // lastprivate clause requires an accessible, unambiguous copy assignment
8413 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008414 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008415 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008416 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008417 D->hasAttrs() ? &D->getAttrs() : nullptr);
8418 auto *PseudoSrcExpr =
8419 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008420 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008421 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008422 D->hasAttrs() ? &D->getAttrs() : nullptr);
8423 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008424 // For arrays generate assignment operation for single element and replace
8425 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008426 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008427 PseudoDstExpr, PseudoSrcExpr);
8428 if (AssignmentOp.isInvalid())
8429 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008430 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008431 /*DiscardedValue=*/true);
8432 if (AssignmentOp.isInvalid())
8433 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008434
Alexey Bataev74caaf22016-02-20 04:09:36 +00008435 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008436 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008437 if (TopDVar.CKind == OMPC_firstprivate)
8438 Ref = TopDVar.PrivateCopy;
8439 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008440 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008441 if (!IsOpenMPCapturedDecl(D))
8442 ExprCaptures.push_back(Ref->getDecl());
8443 }
8444 if (TopDVar.CKind == OMPC_firstprivate ||
8445 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008446 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008447 ExprResult RefRes = DefaultLvalueConversion(Ref);
8448 if (!RefRes.isUsable())
8449 continue;
8450 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008451 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8452 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008453 if (!PostUpdateRes.isUsable())
8454 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008455 ExprPostUpdates.push_back(
8456 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008457 }
8458 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008459 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008460 Vars.push_back((VD || CurContext->isDependentContext())
8461 ? RefExpr->IgnoreParens()
8462 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008463 SrcExprs.push_back(PseudoSrcExpr);
8464 DstExprs.push_back(PseudoDstExpr);
8465 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008466 }
8467
8468 if (Vars.empty())
8469 return nullptr;
8470
8471 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008472 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008473 buildPreInits(Context, ExprCaptures),
8474 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008475}
8476
Alexey Bataev758e55e2013-09-06 18:03:48 +00008477OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8478 SourceLocation StartLoc,
8479 SourceLocation LParenLoc,
8480 SourceLocation EndLoc) {
8481 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008482 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008483 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008484 SourceLocation ELoc;
8485 SourceRange ERange;
8486 Expr *SimpleRefExpr = RefExpr;
8487 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008488 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008489 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008490 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008491 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008492 ValueDecl *D = Res.first;
8493 if (!D)
8494 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008495
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008496 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008497 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8498 // in a Construct]
8499 // Variables with the predetermined data-sharing attributes may not be
8500 // listed in data-sharing attributes clauses, except for the cases
8501 // listed below. For these exceptions only, listing a predetermined
8502 // variable in a data-sharing attribute clause is allowed and overrides
8503 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008504 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008505 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8506 DVar.RefExpr) {
8507 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8508 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008509 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008510 continue;
8511 }
8512
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008513 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008514 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008515 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008516 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008517 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8518 ? RefExpr->IgnoreParens()
8519 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008520 }
8521
Alexey Bataeved09d242014-05-28 05:53:51 +00008522 if (Vars.empty())
8523 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008524
8525 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8526}
8527
Alexey Bataevc5e02582014-06-16 07:08:35 +00008528namespace {
8529class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8530 DSAStackTy *Stack;
8531
8532public:
8533 bool VisitDeclRefExpr(DeclRefExpr *E) {
8534 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008535 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008536 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8537 return false;
8538 if (DVar.CKind != OMPC_unknown)
8539 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008540 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8541 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8542 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008543 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008544 return true;
8545 return false;
8546 }
8547 return false;
8548 }
8549 bool VisitStmt(Stmt *S) {
8550 for (auto Child : S->children()) {
8551 if (Child && Visit(Child))
8552 return true;
8553 }
8554 return false;
8555 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008556 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008557};
Alexey Bataev23b69422014-06-18 07:08:49 +00008558} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008559
Alexey Bataev60da77e2016-02-29 05:54:20 +00008560namespace {
8561// Transform MemberExpression for specified FieldDecl of current class to
8562// DeclRefExpr to specified OMPCapturedExprDecl.
8563class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8564 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8565 ValueDecl *Field;
8566 DeclRefExpr *CapturedExpr;
8567
8568public:
8569 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8570 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8571
8572 ExprResult TransformMemberExpr(MemberExpr *E) {
8573 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8574 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008575 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008576 return CapturedExpr;
8577 }
8578 return BaseTransform::TransformMemberExpr(E);
8579 }
8580 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8581};
8582} // namespace
8583
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008584template <typename T>
8585static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8586 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8587 for (auto &Set : Lookups) {
8588 for (auto *D : Set) {
8589 if (auto Res = Gen(cast<ValueDecl>(D)))
8590 return Res;
8591 }
8592 }
8593 return T();
8594}
8595
8596static ExprResult
8597buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8598 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8599 const DeclarationNameInfo &ReductionId, QualType Ty,
8600 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8601 if (ReductionIdScopeSpec.isInvalid())
8602 return ExprError();
8603 SmallVector<UnresolvedSet<8>, 4> Lookups;
8604 if (S) {
8605 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8606 Lookup.suppressDiagnostics();
8607 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8608 auto *D = Lookup.getRepresentativeDecl();
8609 do {
8610 S = S->getParent();
8611 } while (S && !S->isDeclScope(D));
8612 if (S)
8613 S = S->getParent();
8614 Lookups.push_back(UnresolvedSet<8>());
8615 Lookups.back().append(Lookup.begin(), Lookup.end());
8616 Lookup.clear();
8617 }
8618 } else if (auto *ULE =
8619 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8620 Lookups.push_back(UnresolvedSet<8>());
8621 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008622 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008623 if (D == PrevD)
8624 Lookups.push_back(UnresolvedSet<8>());
8625 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8626 Lookups.back().addDecl(DRD);
8627 PrevD = D;
8628 }
8629 }
8630 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8631 Ty->containsUnexpandedParameterPack() ||
8632 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8633 return !D->isInvalidDecl() &&
8634 (D->getType()->isDependentType() ||
8635 D->getType()->isInstantiationDependentType() ||
8636 D->getType()->containsUnexpandedParameterPack());
8637 })) {
8638 UnresolvedSet<8> ResSet;
8639 for (auto &Set : Lookups) {
8640 ResSet.append(Set.begin(), Set.end());
8641 // The last item marks the end of all declarations at the specified scope.
8642 ResSet.addDecl(Set[Set.size() - 1]);
8643 }
8644 return UnresolvedLookupExpr::Create(
8645 SemaRef.Context, /*NamingClass=*/nullptr,
8646 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8647 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8648 }
8649 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8650 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8651 if (!D->isInvalidDecl() &&
8652 SemaRef.Context.hasSameType(D->getType(), Ty))
8653 return D;
8654 return nullptr;
8655 }))
8656 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8657 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8658 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8659 if (!D->isInvalidDecl() &&
8660 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8661 !Ty.isMoreQualifiedThan(D->getType()))
8662 return D;
8663 return nullptr;
8664 })) {
8665 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8666 /*DetectVirtual=*/false);
8667 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8668 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8669 VD->getType().getUnqualifiedType()))) {
8670 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8671 /*DiagID=*/0) !=
8672 Sema::AR_inaccessible) {
8673 SemaRef.BuildBasePathArray(Paths, BasePath);
8674 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8675 }
8676 }
8677 }
8678 }
8679 if (ReductionIdScopeSpec.isSet()) {
8680 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8681 return ExprError();
8682 }
8683 return ExprEmpty();
8684}
8685
Alexey Bataevc5e02582014-06-16 07:08:35 +00008686OMPClause *Sema::ActOnOpenMPReductionClause(
8687 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8688 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008689 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8690 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008691 auto DN = ReductionId.getName();
8692 auto OOK = DN.getCXXOverloadedOperator();
8693 BinaryOperatorKind BOK = BO_Comma;
8694
8695 // OpenMP [2.14.3.6, reduction clause]
8696 // C
8697 // reduction-identifier is either an identifier or one of the following
8698 // operators: +, -, *, &, |, ^, && and ||
8699 // C++
8700 // reduction-identifier is either an id-expression or one of the following
8701 // operators: +, -, *, &, |, ^, && and ||
8702 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8703 switch (OOK) {
8704 case OO_Plus:
8705 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008706 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008707 break;
8708 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008709 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008710 break;
8711 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008712 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008713 break;
8714 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008715 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008716 break;
8717 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008718 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008719 break;
8720 case OO_AmpAmp:
8721 BOK = BO_LAnd;
8722 break;
8723 case OO_PipePipe:
8724 BOK = BO_LOr;
8725 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008726 case OO_New:
8727 case OO_Delete:
8728 case OO_Array_New:
8729 case OO_Array_Delete:
8730 case OO_Slash:
8731 case OO_Percent:
8732 case OO_Tilde:
8733 case OO_Exclaim:
8734 case OO_Equal:
8735 case OO_Less:
8736 case OO_Greater:
8737 case OO_LessEqual:
8738 case OO_GreaterEqual:
8739 case OO_PlusEqual:
8740 case OO_MinusEqual:
8741 case OO_StarEqual:
8742 case OO_SlashEqual:
8743 case OO_PercentEqual:
8744 case OO_CaretEqual:
8745 case OO_AmpEqual:
8746 case OO_PipeEqual:
8747 case OO_LessLess:
8748 case OO_GreaterGreater:
8749 case OO_LessLessEqual:
8750 case OO_GreaterGreaterEqual:
8751 case OO_EqualEqual:
8752 case OO_ExclaimEqual:
8753 case OO_PlusPlus:
8754 case OO_MinusMinus:
8755 case OO_Comma:
8756 case OO_ArrowStar:
8757 case OO_Arrow:
8758 case OO_Call:
8759 case OO_Subscript:
8760 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008761 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008762 case NUM_OVERLOADED_OPERATORS:
8763 llvm_unreachable("Unexpected reduction identifier");
8764 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008765 if (auto II = DN.getAsIdentifierInfo()) {
8766 if (II->isStr("max"))
8767 BOK = BO_GT;
8768 else if (II->isStr("min"))
8769 BOK = BO_LT;
8770 }
8771 break;
8772 }
8773 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008774 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008775 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008776 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008777
8778 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008779 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008780 SmallVector<Expr *, 8> LHSs;
8781 SmallVector<Expr *, 8> RHSs;
8782 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008783 SmallVector<Decl *, 4> ExprCaptures;
8784 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008785 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8786 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008787 for (auto RefExpr : VarList) {
8788 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008789 // OpenMP [2.1, C/C++]
8790 // A list item is a variable or array section, subject to the restrictions
8791 // specified in Section 2.4 on page 42 and in each of the sections
8792 // describing clauses and directives for which a list appears.
8793 // OpenMP [2.14.3.3, Restrictions, p.1]
8794 // A variable that is part of another variable (as an array or
8795 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008796 if (!FirstIter && IR != ER)
8797 ++IR;
8798 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008799 SourceLocation ELoc;
8800 SourceRange ERange;
8801 Expr *SimpleRefExpr = RefExpr;
8802 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8803 /*AllowArraySection=*/true);
8804 if (Res.second) {
8805 // It will be analyzed later.
8806 Vars.push_back(RefExpr);
8807 Privates.push_back(nullptr);
8808 LHSs.push_back(nullptr);
8809 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008810 // Try to find 'declare reduction' corresponding construct before using
8811 // builtin/overloaded operators.
8812 QualType Type = Context.DependentTy;
8813 CXXCastPath BasePath;
8814 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8815 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8816 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8817 if (CurContext->isDependentContext() &&
8818 (DeclareReductionRef.isUnset() ||
8819 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8820 ReductionOps.push_back(DeclareReductionRef.get());
8821 else
8822 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008823 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008824 ValueDecl *D = Res.first;
8825 if (!D)
8826 continue;
8827
Alexey Bataeva1764212015-09-30 09:22:36 +00008828 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008829 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8830 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8831 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008832 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008833 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008834 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8835 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8836 Type = ATy->getElementType();
8837 else
8838 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008839 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008840 } else
8841 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8842 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008843
Alexey Bataevc5e02582014-06-16 07:08:35 +00008844 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8845 // A variable that appears in a private clause must not have an incomplete
8846 // type or a reference type.
8847 if (RequireCompleteType(ELoc, Type,
8848 diag::err_omp_reduction_incomplete_type))
8849 continue;
8850 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008851 // A list item that appears in a reduction clause must not be
8852 // const-qualified.
8853 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008854 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008855 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008856 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008857 bool IsDecl = !VD ||
8858 VD->isThisDeclarationADefinition(Context) ==
8859 VarDecl::DeclarationOnly;
8860 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008861 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008862 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008863 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008864 continue;
8865 }
8866 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8867 // If a list-item is a reference type then it must bind to the same object
8868 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008869 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008870 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008871 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008872 DSARefChecker Check(DSAStack);
8873 if (Check.Visit(VDDef->getInit())) {
8874 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8875 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8876 continue;
8877 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008878 }
8879 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008880
Alexey Bataevc5e02582014-06-16 07:08:35 +00008881 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8882 // in a Construct]
8883 // Variables with the predetermined data-sharing attributes may not be
8884 // listed in data-sharing attributes clauses, except for the cases
8885 // listed below. For these exceptions only, listing a predetermined
8886 // variable in a data-sharing attribute clause is allowed and overrides
8887 // the variable's predetermined data-sharing attributes.
8888 // OpenMP [2.14.3.6, Restrictions, p.3]
8889 // Any number of reduction clauses can be specified on the directive,
8890 // but a list item can appear only once in the reduction clauses for that
8891 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008892 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008893 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008894 if (DVar.CKind == OMPC_reduction) {
8895 Diag(ELoc, diag::err_omp_once_referenced)
8896 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008897 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008898 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008899 } else if (DVar.CKind != OMPC_unknown) {
8900 Diag(ELoc, diag::err_omp_wrong_dsa)
8901 << getOpenMPClauseName(DVar.CKind)
8902 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008903 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008904 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008905 }
8906
8907 // OpenMP [2.14.3.6, Restrictions, p.1]
8908 // A list item that appears in a reduction clause of a worksharing
8909 // construct must be shared in the parallel regions to which any of the
8910 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008911 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8912 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008913 !isOpenMPParallelDirective(CurrDir) &&
8914 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008915 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008916 if (DVar.CKind != OMPC_shared) {
8917 Diag(ELoc, diag::err_omp_required_access)
8918 << getOpenMPClauseName(OMPC_reduction)
8919 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008920 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008921 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008922 }
8923 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008924
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008925 // Try to find 'declare reduction' corresponding construct before using
8926 // builtin/overloaded operators.
8927 CXXCastPath BasePath;
8928 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8929 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8930 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8931 if (DeclareReductionRef.isInvalid())
8932 continue;
8933 if (CurContext->isDependentContext() &&
8934 (DeclareReductionRef.isUnset() ||
8935 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8936 Vars.push_back(RefExpr);
8937 Privates.push_back(nullptr);
8938 LHSs.push_back(nullptr);
8939 RHSs.push_back(nullptr);
8940 ReductionOps.push_back(DeclareReductionRef.get());
8941 continue;
8942 }
8943 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8944 // Not allowed reduction identifier is found.
8945 Diag(ReductionId.getLocStart(),
8946 diag::err_omp_unknown_reduction_identifier)
8947 << Type << ReductionIdRange;
8948 continue;
8949 }
8950
8951 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8952 // The type of a list item that appears in a reduction clause must be valid
8953 // for the reduction-identifier. For a max or min reduction in C, the type
8954 // of the list item must be an allowed arithmetic data type: char, int,
8955 // float, double, or _Bool, possibly modified with long, short, signed, or
8956 // unsigned. For a max or min reduction in C++, the type of the list item
8957 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8958 // double, or bool, possibly modified with long, short, signed, or unsigned.
8959 if (DeclareReductionRef.isUnset()) {
8960 if ((BOK == BO_GT || BOK == BO_LT) &&
8961 !(Type->isScalarType() ||
8962 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8963 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8964 << getLangOpts().CPlusPlus;
8965 if (!ASE && !OASE) {
8966 bool IsDecl = !VD ||
8967 VD->isThisDeclarationADefinition(Context) ==
8968 VarDecl::DeclarationOnly;
8969 Diag(D->getLocation(),
8970 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8971 << D;
8972 }
8973 continue;
8974 }
8975 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8976 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8977 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8978 if (!ASE && !OASE) {
8979 bool IsDecl = !VD ||
8980 VD->isThisDeclarationADefinition(Context) ==
8981 VarDecl::DeclarationOnly;
8982 Diag(D->getLocation(),
8983 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8984 << D;
8985 }
8986 continue;
8987 }
8988 }
8989
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008990 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008991 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008992 D->hasAttrs() ? &D->getAttrs() : nullptr);
8993 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8994 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008995 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008996 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008997 (!ASE &&
8998 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008999 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009000 // Create pseudo array type for private copy. The size for this array will
9001 // be generated during codegen.
9002 // For array subscripts or single variables Private Ty is the same as Type
9003 // (type of the variable or single array element).
9004 PrivateTy = Context.getVariableArrayType(
9005 Type, new (Context) OpaqueValueExpr(SourceLocation(),
9006 Context.getSizeType(), VK_RValue),
9007 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009008 } else if (!ASE && !OASE &&
9009 Context.getAsArrayType(D->getType().getNonReferenceType()))
9010 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009011 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009012 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
9013 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009014 // Add initializer for private variable.
9015 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009016 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
9017 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
9018 if (DeclareReductionRef.isUsable()) {
9019 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9020 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9021 if (DRD->getInitializer()) {
9022 Init = DRDRef;
9023 RHSVD->setInit(DRDRef);
9024 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009025 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009026 } else {
9027 switch (BOK) {
9028 case BO_Add:
9029 case BO_Xor:
9030 case BO_Or:
9031 case BO_LOr:
9032 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9033 if (Type->isScalarType() || Type->isAnyComplexType())
9034 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
9035 break;
9036 case BO_Mul:
9037 case BO_LAnd:
9038 if (Type->isScalarType() || Type->isAnyComplexType()) {
9039 // '*' and '&&' reduction ops - initializer is '1'.
9040 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009041 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009042 break;
9043 case BO_And: {
9044 // '&' reduction op - initializer is '~0'.
9045 QualType OrigType = Type;
9046 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9047 Type = ComplexTy->getElementType();
9048 if (Type->isRealFloatingType()) {
9049 llvm::APFloat InitValue =
9050 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9051 /*isIEEE=*/true);
9052 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9053 Type, ELoc);
9054 } else if (Type->isScalarType()) {
9055 auto Size = Context.getTypeSize(Type);
9056 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9057 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9058 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9059 }
9060 if (Init && OrigType->isAnyComplexType()) {
9061 // Init = 0xFFFF + 0xFFFFi;
9062 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9063 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9064 }
9065 Type = OrigType;
9066 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009067 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009068 case BO_LT:
9069 case BO_GT: {
9070 // 'min' reduction op - initializer is 'Largest representable number in
9071 // the reduction list item type'.
9072 // 'max' reduction op - initializer is 'Least representable number in
9073 // the reduction list item type'.
9074 if (Type->isIntegerType() || Type->isPointerType()) {
9075 bool IsSigned = Type->hasSignedIntegerRepresentation();
9076 auto Size = Context.getTypeSize(Type);
9077 QualType IntTy =
9078 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9079 llvm::APInt InitValue =
9080 (BOK != BO_LT)
9081 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9082 : llvm::APInt::getMinValue(Size)
9083 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9084 : llvm::APInt::getMaxValue(Size);
9085 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9086 if (Type->isPointerType()) {
9087 // Cast to pointer type.
9088 auto CastExpr = BuildCStyleCastExpr(
9089 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9090 SourceLocation(), Init);
9091 if (CastExpr.isInvalid())
9092 continue;
9093 Init = CastExpr.get();
9094 }
9095 } else if (Type->isRealFloatingType()) {
9096 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9097 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9098 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9099 Type, ELoc);
9100 }
9101 break;
9102 }
9103 case BO_PtrMemD:
9104 case BO_PtrMemI:
9105 case BO_MulAssign:
9106 case BO_Div:
9107 case BO_Rem:
9108 case BO_Sub:
9109 case BO_Shl:
9110 case BO_Shr:
9111 case BO_LE:
9112 case BO_GE:
9113 case BO_EQ:
9114 case BO_NE:
9115 case BO_AndAssign:
9116 case BO_XorAssign:
9117 case BO_OrAssign:
9118 case BO_Assign:
9119 case BO_AddAssign:
9120 case BO_SubAssign:
9121 case BO_DivAssign:
9122 case BO_RemAssign:
9123 case BO_ShlAssign:
9124 case BO_ShrAssign:
9125 case BO_Comma:
9126 llvm_unreachable("Unexpected reduction operation");
9127 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009128 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009129 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00009130 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009131 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00009132 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009133 if (RHSVD->isInvalidDecl())
9134 continue;
9135 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009136 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9137 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009138 bool IsDecl =
9139 !VD ||
9140 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9141 Diag(D->getLocation(),
9142 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9143 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009144 continue;
9145 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009146 // Store initializer for single element in private copy. Will be used during
9147 // codegen.
9148 PrivateVD->setInit(RHSVD->getInit());
9149 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009150 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009151 ExprResult ReductionOp;
9152 if (DeclareReductionRef.isUsable()) {
9153 QualType RedTy = DeclareReductionRef.get()->getType();
9154 QualType PtrRedTy = Context.getPointerType(RedTy);
9155 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9156 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9157 if (!BasePath.empty()) {
9158 LHS = DefaultLvalueConversion(LHS.get());
9159 RHS = DefaultLvalueConversion(RHS.get());
9160 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9161 CK_UncheckedDerivedToBase, LHS.get(),
9162 &BasePath, LHS.get()->getValueKind());
9163 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9164 CK_UncheckedDerivedToBase, RHS.get(),
9165 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009166 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009167 FunctionProtoType::ExtProtoInfo EPI;
9168 QualType Params[] = {PtrRedTy, PtrRedTy};
9169 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9170 auto *OVE = new (Context) OpaqueValueExpr(
9171 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9172 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9173 Expr *Args[] = {LHS.get(), RHS.get()};
9174 ReductionOp = new (Context)
9175 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9176 } else {
9177 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9178 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9179 if (ReductionOp.isUsable()) {
9180 if (BOK != BO_LT && BOK != BO_GT) {
9181 ReductionOp =
9182 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9183 BO_Assign, LHSDRE, ReductionOp.get());
9184 } else {
9185 auto *ConditionalOp = new (Context) ConditionalOperator(
9186 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9187 RHSDRE, Type, VK_LValue, OK_Ordinary);
9188 ReductionOp =
9189 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9190 BO_Assign, LHSDRE, ConditionalOp);
9191 }
9192 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9193 }
9194 if (ReductionOp.isInvalid())
9195 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009196 }
9197
Alexey Bataev60da77e2016-02-29 05:54:20 +00009198 DeclRefExpr *Ref = nullptr;
9199 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009200 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009201 if (ASE || OASE) {
9202 TransformExprToCaptures RebuildToCapture(*this, D);
9203 VarsExpr =
9204 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9205 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009206 } else {
9207 VarsExpr = Ref =
9208 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009209 }
9210 if (!IsOpenMPCapturedDecl(D)) {
9211 ExprCaptures.push_back(Ref->getDecl());
9212 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9213 ExprResult RefRes = DefaultLvalueConversion(Ref);
9214 if (!RefRes.isUsable())
9215 continue;
9216 ExprResult PostUpdateRes =
9217 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9218 SimpleRefExpr, RefRes.get());
9219 if (!PostUpdateRes.isUsable())
9220 continue;
9221 ExprPostUpdates.push_back(
9222 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009223 }
9224 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009225 }
9226 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9227 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009228 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009229 LHSs.push_back(LHSDRE);
9230 RHSs.push_back(RHSDRE);
9231 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009232 }
9233
9234 if (Vars.empty())
9235 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009236
Alexey Bataevc5e02582014-06-16 07:08:35 +00009237 return OMPReductionClause::Create(
9238 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009239 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009240 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9241 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009242}
9243
Alexey Bataevecba70f2016-04-12 11:02:11 +00009244bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9245 SourceLocation LinLoc) {
9246 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9247 LinKind == OMPC_LINEAR_unknown) {
9248 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9249 return true;
9250 }
9251 return false;
9252}
9253
9254bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9255 OpenMPLinearClauseKind LinKind,
9256 QualType Type) {
9257 auto *VD = dyn_cast_or_null<VarDecl>(D);
9258 // A variable must not have an incomplete type or a reference type.
9259 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9260 return true;
9261 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9262 !Type->isReferenceType()) {
9263 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9264 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9265 return true;
9266 }
9267 Type = Type.getNonReferenceType();
9268
9269 // A list item must not be const-qualified.
9270 if (Type.isConstant(Context)) {
9271 Diag(ELoc, diag::err_omp_const_variable)
9272 << getOpenMPClauseName(OMPC_linear);
9273 if (D) {
9274 bool IsDecl =
9275 !VD ||
9276 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9277 Diag(D->getLocation(),
9278 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9279 << D;
9280 }
9281 return true;
9282 }
9283
9284 // A list item must be of integral or pointer type.
9285 Type = Type.getUnqualifiedType().getCanonicalType();
9286 const auto *Ty = Type.getTypePtrOrNull();
9287 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9288 !Ty->isPointerType())) {
9289 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9290 if (D) {
9291 bool IsDecl =
9292 !VD ||
9293 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9294 Diag(D->getLocation(),
9295 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9296 << D;
9297 }
9298 return true;
9299 }
9300 return false;
9301}
9302
Alexey Bataev182227b2015-08-20 10:54:39 +00009303OMPClause *Sema::ActOnOpenMPLinearClause(
9304 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9305 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9306 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009307 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009308 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009309 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009310 SmallVector<Decl *, 4> ExprCaptures;
9311 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009312 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009313 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009314 for (auto &RefExpr : VarList) {
9315 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009316 SourceLocation ELoc;
9317 SourceRange ERange;
9318 Expr *SimpleRefExpr = RefExpr;
9319 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9320 /*AllowArraySection=*/false);
9321 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009322 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009323 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009324 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009325 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009326 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009327 ValueDecl *D = Res.first;
9328 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009329 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009330
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009331 QualType Type = D->getType();
9332 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009333
9334 // OpenMP [2.14.3.7, linear clause]
9335 // A list-item cannot appear in more than one linear clause.
9336 // A list-item that appears in a linear clause cannot appear in any
9337 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009338 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009339 if (DVar.RefExpr) {
9340 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9341 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009342 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009343 continue;
9344 }
9345
Alexey Bataevecba70f2016-04-12 11:02:11 +00009346 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009347 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009348 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009349
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009350 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009351 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9352 D->hasAttrs() ? &D->getAttrs() : nullptr);
9353 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009354 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009355 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009356 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009357 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009358 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009359 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9360 if (!IsOpenMPCapturedDecl(D)) {
9361 ExprCaptures.push_back(Ref->getDecl());
9362 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9363 ExprResult RefRes = DefaultLvalueConversion(Ref);
9364 if (!RefRes.isUsable())
9365 continue;
9366 ExprResult PostUpdateRes =
9367 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9368 SimpleRefExpr, RefRes.get());
9369 if (!PostUpdateRes.isUsable())
9370 continue;
9371 ExprPostUpdates.push_back(
9372 IgnoredValueConversions(PostUpdateRes.get()).get());
9373 }
9374 }
9375 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009376 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009377 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009378 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009379 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009380 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009381 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009382 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9383
9384 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009385 Vars.push_back((VD || CurContext->isDependentContext())
9386 ? RefExpr->IgnoreParens()
9387 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009388 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009389 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009390 }
9391
9392 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009393 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009394
9395 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009396 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009397 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9398 !Step->isInstantiationDependent() &&
9399 !Step->containsUnexpandedParameterPack()) {
9400 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009401 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009402 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009403 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009404 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009405
Alexander Musman3276a272015-03-21 10:12:56 +00009406 // Build var to save the step value.
9407 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009408 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009409 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009410 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009411 ExprResult CalcStep =
9412 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009413 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009414
Alexander Musman8dba6642014-04-22 13:09:42 +00009415 // Warn about zero linear step (it would be probably better specified as
9416 // making corresponding variables 'const').
9417 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009418 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9419 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009420 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9421 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009422 if (!IsConstant && CalcStep.isUsable()) {
9423 // Calculate the step beforehand instead of doing this on each iteration.
9424 // (This is not used if the number of iterations may be kfold-ed).
9425 CalcStepExpr = CalcStep.get();
9426 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009427 }
9428
Alexey Bataev182227b2015-08-20 10:54:39 +00009429 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9430 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009431 StepExpr, CalcStepExpr,
9432 buildPreInits(Context, ExprCaptures),
9433 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009434}
9435
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009436static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9437 Expr *NumIterations, Sema &SemaRef,
9438 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009439 // Walk the vars and build update/final expressions for the CodeGen.
9440 SmallVector<Expr *, 8> Updates;
9441 SmallVector<Expr *, 8> Finals;
9442 Expr *Step = Clause.getStep();
9443 Expr *CalcStep = Clause.getCalcStep();
9444 // OpenMP [2.14.3.7, linear clause]
9445 // If linear-step is not specified it is assumed to be 1.
9446 if (Step == nullptr)
9447 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009448 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009449 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009450 }
Alexander Musman3276a272015-03-21 10:12:56 +00009451 bool HasErrors = false;
9452 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009453 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009454 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009455 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009456 SourceLocation ELoc;
9457 SourceRange ERange;
9458 Expr *SimpleRefExpr = RefExpr;
9459 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9460 /*AllowArraySection=*/false);
9461 ValueDecl *D = Res.first;
9462 if (Res.second || !D) {
9463 Updates.push_back(nullptr);
9464 Finals.push_back(nullptr);
9465 HasErrors = true;
9466 continue;
9467 }
9468 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9469 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9470 ->getMemberDecl();
9471 }
9472 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009473 Expr *InitExpr = *CurInit;
9474
9475 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009476 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009477 Expr *CapturedRef;
9478 if (LinKind == OMPC_LINEAR_uval)
9479 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9480 else
9481 CapturedRef =
9482 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9483 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9484 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009485
9486 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009487 ExprResult Update;
9488 if (!Info.first) {
9489 Update =
9490 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9491 InitExpr, IV, Step, /* Subtract */ false);
9492 } else
9493 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009494 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9495 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009496
9497 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009498 ExprResult Final;
9499 if (!Info.first) {
9500 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9501 InitExpr, NumIterations, Step,
9502 /* Subtract */ false);
9503 } else
9504 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009505 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9506 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009507
Alexander Musman3276a272015-03-21 10:12:56 +00009508 if (!Update.isUsable() || !Final.isUsable()) {
9509 Updates.push_back(nullptr);
9510 Finals.push_back(nullptr);
9511 HasErrors = true;
9512 } else {
9513 Updates.push_back(Update.get());
9514 Finals.push_back(Final.get());
9515 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009516 ++CurInit;
9517 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009518 }
9519 Clause.setUpdates(Updates);
9520 Clause.setFinals(Finals);
9521 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009522}
9523
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009524OMPClause *Sema::ActOnOpenMPAlignedClause(
9525 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9526 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9527
9528 SmallVector<Expr *, 8> Vars;
9529 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009530 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9531 SourceLocation ELoc;
9532 SourceRange ERange;
9533 Expr *SimpleRefExpr = RefExpr;
9534 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9535 /*AllowArraySection=*/false);
9536 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009537 // It will be analyzed later.
9538 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009539 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009540 ValueDecl *D = Res.first;
9541 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009542 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009543
Alexey Bataev1efd1662016-03-29 10:59:56 +00009544 QualType QType = D->getType();
9545 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009546
9547 // OpenMP [2.8.1, simd construct, Restrictions]
9548 // The type of list items appearing in the aligned clause must be
9549 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009550 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009551 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009552 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009553 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009554 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009555 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009556 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009557 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009558 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009559 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009560 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009561 continue;
9562 }
9563
9564 // OpenMP [2.8.1, simd construct, Restrictions]
9565 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009566 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009567 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009568 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9569 << getOpenMPClauseName(OMPC_aligned);
9570 continue;
9571 }
9572
Alexey Bataev1efd1662016-03-29 10:59:56 +00009573 DeclRefExpr *Ref = nullptr;
9574 if (!VD && IsOpenMPCapturedDecl(D))
9575 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9576 Vars.push_back(DefaultFunctionArrayConversion(
9577 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9578 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009579 }
9580
9581 // OpenMP [2.8.1, simd construct, Description]
9582 // The parameter of the aligned clause, alignment, must be a constant
9583 // positive integer expression.
9584 // If no optional parameter is specified, implementation-defined default
9585 // alignments for SIMD instructions on the target platforms are assumed.
9586 if (Alignment != nullptr) {
9587 ExprResult AlignResult =
9588 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9589 if (AlignResult.isInvalid())
9590 return nullptr;
9591 Alignment = AlignResult.get();
9592 }
9593 if (Vars.empty())
9594 return nullptr;
9595
9596 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9597 EndLoc, Vars, Alignment);
9598}
9599
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009600OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9601 SourceLocation StartLoc,
9602 SourceLocation LParenLoc,
9603 SourceLocation EndLoc) {
9604 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009605 SmallVector<Expr *, 8> SrcExprs;
9606 SmallVector<Expr *, 8> DstExprs;
9607 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009608 for (auto &RefExpr : VarList) {
9609 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9610 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009611 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009612 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009613 SrcExprs.push_back(nullptr);
9614 DstExprs.push_back(nullptr);
9615 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009616 continue;
9617 }
9618
Alexey Bataeved09d242014-05-28 05:53:51 +00009619 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009620 // OpenMP [2.1, C/C++]
9621 // A list item is a variable name.
9622 // OpenMP [2.14.4.1, Restrictions, p.1]
9623 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009624 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009625 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009626 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9627 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009628 continue;
9629 }
9630
9631 Decl *D = DE->getDecl();
9632 VarDecl *VD = cast<VarDecl>(D);
9633
9634 QualType Type = VD->getType();
9635 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9636 // It will be analyzed later.
9637 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009638 SrcExprs.push_back(nullptr);
9639 DstExprs.push_back(nullptr);
9640 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009641 continue;
9642 }
9643
9644 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9645 // A list item that appears in a copyin clause must be threadprivate.
9646 if (!DSAStack->isThreadPrivate(VD)) {
9647 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009648 << getOpenMPClauseName(OMPC_copyin)
9649 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009650 continue;
9651 }
9652
9653 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9654 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009655 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009656 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009657 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009658 auto *SrcVD =
9659 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9660 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009661 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009662 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9663 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009664 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9665 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009666 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009667 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009668 // For arrays generate assignment operation for single element and replace
9669 // it by the original array element in CodeGen.
9670 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9671 PseudoDstExpr, PseudoSrcExpr);
9672 if (AssignmentOp.isInvalid())
9673 continue;
9674 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9675 /*DiscardedValue=*/true);
9676 if (AssignmentOp.isInvalid())
9677 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009678
9679 DSAStack->addDSA(VD, DE, OMPC_copyin);
9680 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009681 SrcExprs.push_back(PseudoSrcExpr);
9682 DstExprs.push_back(PseudoDstExpr);
9683 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009684 }
9685
Alexey Bataeved09d242014-05-28 05:53:51 +00009686 if (Vars.empty())
9687 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009688
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009689 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9690 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009691}
9692
Alexey Bataevbae9a792014-06-27 10:37:06 +00009693OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9694 SourceLocation StartLoc,
9695 SourceLocation LParenLoc,
9696 SourceLocation EndLoc) {
9697 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009698 SmallVector<Expr *, 8> SrcExprs;
9699 SmallVector<Expr *, 8> DstExprs;
9700 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009701 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009702 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9703 SourceLocation ELoc;
9704 SourceRange ERange;
9705 Expr *SimpleRefExpr = RefExpr;
9706 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9707 /*AllowArraySection=*/false);
9708 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009709 // It will be analyzed later.
9710 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009711 SrcExprs.push_back(nullptr);
9712 DstExprs.push_back(nullptr);
9713 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009714 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009715 ValueDecl *D = Res.first;
9716 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009717 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009718
Alexey Bataeve122da12016-03-17 10:50:17 +00009719 QualType Type = D->getType();
9720 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009721
9722 // OpenMP [2.14.4.2, Restrictions, p.2]
9723 // A list item that appears in a copyprivate clause may not appear in a
9724 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009725 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9726 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009727 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9728 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009729 Diag(ELoc, diag::err_omp_wrong_dsa)
9730 << getOpenMPClauseName(DVar.CKind)
9731 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009732 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009733 continue;
9734 }
9735
9736 // OpenMP [2.11.4.2, Restrictions, p.1]
9737 // All list items that appear in a copyprivate clause must be either
9738 // threadprivate or private in the enclosing context.
9739 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009740 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009741 if (DVar.CKind == OMPC_shared) {
9742 Diag(ELoc, diag::err_omp_required_access)
9743 << getOpenMPClauseName(OMPC_copyprivate)
9744 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009745 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009746 continue;
9747 }
9748 }
9749 }
9750
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009751 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009752 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009753 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009754 << getOpenMPClauseName(OMPC_copyprivate) << Type
9755 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009756 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009757 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009758 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009759 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009760 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009761 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009762 continue;
9763 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009764
Alexey Bataevbae9a792014-06-27 10:37:06 +00009765 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9766 // A variable of class type (or array thereof) that appears in a
9767 // copyin clause requires an accessible, unambiguous copy assignment
9768 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009769 Type = Context.getBaseElementType(Type.getNonReferenceType())
9770 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009771 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009772 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9773 D->hasAttrs() ? &D->getAttrs() : nullptr);
9774 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009775 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009776 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9777 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009778 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009779 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009780 PseudoDstExpr, PseudoSrcExpr);
9781 if (AssignmentOp.isInvalid())
9782 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009783 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009784 /*DiscardedValue=*/true);
9785 if (AssignmentOp.isInvalid())
9786 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009787
9788 // No need to mark vars as copyprivate, they are already threadprivate or
9789 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009790 assert(VD || IsOpenMPCapturedDecl(D));
9791 Vars.push_back(
9792 VD ? RefExpr->IgnoreParens()
9793 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009794 SrcExprs.push_back(PseudoSrcExpr);
9795 DstExprs.push_back(PseudoDstExpr);
9796 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009797 }
9798
9799 if (Vars.empty())
9800 return nullptr;
9801
Alexey Bataeva63048e2015-03-23 06:18:07 +00009802 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9803 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009804}
9805
Alexey Bataev6125da92014-07-21 11:26:11 +00009806OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9807 SourceLocation StartLoc,
9808 SourceLocation LParenLoc,
9809 SourceLocation EndLoc) {
9810 if (VarList.empty())
9811 return nullptr;
9812
9813 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9814}
Alexey Bataevdea47612014-07-23 07:46:59 +00009815
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009816OMPClause *
9817Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9818 SourceLocation DepLoc, SourceLocation ColonLoc,
9819 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9820 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009821 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009822 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009823 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009824 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009825 return nullptr;
9826 }
9827 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009828 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9829 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009830 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009831 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009832 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9833 /*Last=*/OMPC_DEPEND_unknown, Except)
9834 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009835 return nullptr;
9836 }
9837 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009838 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009839 llvm::APSInt DepCounter(/*BitWidth=*/32);
9840 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9841 if (DepKind == OMPC_DEPEND_sink) {
9842 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9843 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9844 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009845 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009846 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009847 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9848 DSAStack->getParentOrderedRegionParam()) {
9849 for (auto &RefExpr : VarList) {
9850 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009851 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009852 // It will be analyzed later.
9853 Vars.push_back(RefExpr);
9854 continue;
9855 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009856
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009857 SourceLocation ELoc = RefExpr->getExprLoc();
9858 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9859 if (DepKind == OMPC_DEPEND_sink) {
9860 if (DepCounter >= TotalDepCount) {
9861 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9862 continue;
9863 }
9864 ++DepCounter;
9865 // OpenMP [2.13.9, Summary]
9866 // depend(dependence-type : vec), where dependence-type is:
9867 // 'sink' and where vec is the iteration vector, which has the form:
9868 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9869 // where n is the value specified by the ordered clause in the loop
9870 // directive, xi denotes the loop iteration variable of the i-th nested
9871 // loop associated with the loop directive, and di is a constant
9872 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009873 if (CurContext->isDependentContext()) {
9874 // It will be analyzed later.
9875 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009876 continue;
9877 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009878 SimpleExpr = SimpleExpr->IgnoreImplicit();
9879 OverloadedOperatorKind OOK = OO_None;
9880 SourceLocation OOLoc;
9881 Expr *LHS = SimpleExpr;
9882 Expr *RHS = nullptr;
9883 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9884 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9885 OOLoc = BO->getOperatorLoc();
9886 LHS = BO->getLHS()->IgnoreParenImpCasts();
9887 RHS = BO->getRHS()->IgnoreParenImpCasts();
9888 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9889 OOK = OCE->getOperator();
9890 OOLoc = OCE->getOperatorLoc();
9891 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9892 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9893 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9894 OOK = MCE->getMethodDecl()
9895 ->getNameInfo()
9896 .getName()
9897 .getCXXOverloadedOperator();
9898 OOLoc = MCE->getCallee()->getExprLoc();
9899 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9900 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9901 }
9902 SourceLocation ELoc;
9903 SourceRange ERange;
9904 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9905 /*AllowArraySection=*/false);
9906 if (Res.second) {
9907 // It will be analyzed later.
9908 Vars.push_back(RefExpr);
9909 }
9910 ValueDecl *D = Res.first;
9911 if (!D)
9912 continue;
9913
9914 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9915 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9916 continue;
9917 }
9918 if (RHS) {
9919 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9920 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9921 if (RHSRes.isInvalid())
9922 continue;
9923 }
9924 if (!CurContext->isDependentContext() &&
9925 DSAStack->getParentOrderedRegionParam() &&
9926 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9927 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9928 << DSAStack->getParentLoopControlVariable(
9929 DepCounter.getZExtValue());
9930 continue;
9931 }
9932 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009933 } else {
9934 // OpenMP [2.11.1.1, Restrictions, p.3]
9935 // A variable that is part of another variable (such as a field of a
9936 // structure) but is not an array element or an array section cannot
9937 // appear in a depend clause.
9938 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9939 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9940 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9941 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9942 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009943 (ASE &&
9944 !ASE->getBase()
9945 ->getType()
9946 .getNonReferenceType()
9947 ->isPointerType() &&
9948 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009949 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9950 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009951 continue;
9952 }
9953 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009954 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9955 }
9956
9957 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9958 TotalDepCount > VarList.size() &&
9959 DSAStack->getParentOrderedRegionParam()) {
9960 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9961 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9962 }
9963 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9964 Vars.empty())
9965 return nullptr;
9966 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009967 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9968 DepKind, DepLoc, ColonLoc, Vars);
9969 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9970 DSAStack->addDoacrossDependClause(C, OpsOffs);
9971 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009972}
Michael Wonge710d542015-08-07 16:16:36 +00009973
9974OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9975 SourceLocation LParenLoc,
9976 SourceLocation EndLoc) {
9977 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009978
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009979 // OpenMP [2.9.1, Restrictions]
9980 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009981 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9982 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009983 return nullptr;
9984
Michael Wonge710d542015-08-07 16:16:36 +00009985 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9986}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009987
9988static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9989 DSAStackTy *Stack, CXXRecordDecl *RD) {
9990 if (!RD || RD->isInvalidDecl())
9991 return true;
9992
9993 auto QTy = SemaRef.Context.getRecordType(RD);
9994 if (RD->isDynamicClass()) {
9995 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9996 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9997 return false;
9998 }
9999 auto *DC = RD;
10000 bool IsCorrect = true;
10001 for (auto *I : DC->decls()) {
10002 if (I) {
10003 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10004 if (MD->isStatic()) {
10005 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10006 SemaRef.Diag(MD->getLocation(),
10007 diag::note_omp_static_member_in_target);
10008 IsCorrect = false;
10009 }
10010 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10011 if (VD->isStaticDataMember()) {
10012 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10013 SemaRef.Diag(VD->getLocation(),
10014 diag::note_omp_static_member_in_target);
10015 IsCorrect = false;
10016 }
10017 }
10018 }
10019 }
10020
10021 for (auto &I : RD->bases()) {
10022 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10023 I.getType()->getAsCXXRecordDecl()))
10024 IsCorrect = false;
10025 }
10026 return IsCorrect;
10027}
10028
10029static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10030 DSAStackTy *Stack, QualType QTy) {
10031 NamedDecl *ND;
10032 if (QTy->isIncompleteType(&ND)) {
10033 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10034 return false;
10035 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010036 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010037 return false;
10038 }
10039 return true;
10040}
10041
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010042/// \brief Return true if it can be proven that the provided array expression
10043/// (array section or array subscript) does NOT specify the whole size of the
10044/// array whose base type is \a BaseQTy.
10045static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10046 const Expr *E,
10047 QualType BaseQTy) {
10048 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10049
10050 // If this is an array subscript, it refers to the whole size if the size of
10051 // the dimension is constant and equals 1. Also, an array section assumes the
10052 // format of an array subscript if no colon is used.
10053 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10054 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10055 return ATy->getSize().getSExtValue() != 1;
10056 // Size can't be evaluated statically.
10057 return false;
10058 }
10059
10060 assert(OASE && "Expecting array section if not an array subscript.");
10061 auto *LowerBound = OASE->getLowerBound();
10062 auto *Length = OASE->getLength();
10063
10064 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010065 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010066 if (LowerBound) {
10067 llvm::APSInt ConstLowerBound;
10068 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10069 return false; // Can't get the integer value as a constant.
10070 if (ConstLowerBound.getSExtValue())
10071 return true;
10072 }
10073
10074 // If we don't have a length we covering the whole dimension.
10075 if (!Length)
10076 return false;
10077
10078 // If the base is a pointer, we don't have a way to get the size of the
10079 // pointee.
10080 if (BaseQTy->isPointerType())
10081 return false;
10082
10083 // We can only check if the length is the same as the size of the dimension
10084 // if we have a constant array.
10085 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10086 if (!CATy)
10087 return false;
10088
10089 llvm::APSInt ConstLength;
10090 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10091 return false; // Can't get the integer value as a constant.
10092
10093 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10094}
10095
10096// Return true if it can be proven that the provided array expression (array
10097// section or array subscript) does NOT specify a single element of the array
10098// whose base type is \a BaseQTy.
10099static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010100 const Expr *E,
10101 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010102 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10103
10104 // An array subscript always refer to a single element. Also, an array section
10105 // assumes the format of an array subscript if no colon is used.
10106 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10107 return false;
10108
10109 assert(OASE && "Expecting array section if not an array subscript.");
10110 auto *Length = OASE->getLength();
10111
10112 // If we don't have a length we have to check if the array has unitary size
10113 // for this dimension. Also, we should always expect a length if the base type
10114 // is pointer.
10115 if (!Length) {
10116 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10117 return ATy->getSize().getSExtValue() != 1;
10118 // We cannot assume anything.
10119 return false;
10120 }
10121
10122 // Check if the length evaluates to 1.
10123 llvm::APSInt ConstLength;
10124 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10125 return false; // Can't get the integer value as a constant.
10126
10127 return ConstLength.getSExtValue() != 1;
10128}
10129
Samuel Antao661c0902016-05-26 17:39:58 +000010130// Return the expression of the base of the mappable expression or null if it
10131// cannot be determined and do all the necessary checks to see if the expression
10132// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010133// components of the expression.
10134static Expr *CheckMapClauseExpressionBase(
10135 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010136 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10137 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010138 SourceLocation ELoc = E->getExprLoc();
10139 SourceRange ERange = E->getSourceRange();
10140
10141 // The base of elements of list in a map clause have to be either:
10142 // - a reference to variable or field.
10143 // - a member expression.
10144 // - an array expression.
10145 //
10146 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10147 // reference to 'r'.
10148 //
10149 // If we have:
10150 //
10151 // struct SS {
10152 // Bla S;
10153 // foo() {
10154 // #pragma omp target map (S.Arr[:12]);
10155 // }
10156 // }
10157 //
10158 // We want to retrieve the member expression 'this->S';
10159
10160 Expr *RelevantExpr = nullptr;
10161
Samuel Antao5de996e2016-01-22 20:21:36 +000010162 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10163 // If a list item is an array section, it must specify contiguous storage.
10164 //
10165 // For this restriction it is sufficient that we make sure only references
10166 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010167 // exist except in the rightmost expression (unless they cover the whole
10168 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010169 //
10170 // r.ArrS[3:5].Arr[6:7]
10171 //
10172 // r.ArrS[3:5].x
10173 //
10174 // but these would be valid:
10175 // r.ArrS[3].Arr[6:7]
10176 //
10177 // r.ArrS[3].x
10178
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010179 bool AllowUnitySizeArraySection = true;
10180 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010181
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010182 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010183 E = E->IgnoreParenImpCasts();
10184
10185 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10186 if (!isa<VarDecl>(CurE->getDecl()))
10187 break;
10188
10189 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010190
10191 // If we got a reference to a declaration, we should not expect any array
10192 // section before that.
10193 AllowUnitySizeArraySection = false;
10194 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010195
10196 // Record the component.
10197 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10198 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010199 continue;
10200 }
10201
10202 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10203 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10204
10205 if (isa<CXXThisExpr>(BaseE))
10206 // We found a base expression: this->Val.
10207 RelevantExpr = CurE;
10208 else
10209 E = BaseE;
10210
10211 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10212 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10213 << CurE->getSourceRange();
10214 break;
10215 }
10216
10217 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10218
10219 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10220 // A bit-field cannot appear in a map clause.
10221 //
10222 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010223 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10224 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010225 break;
10226 }
10227
10228 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10229 // If the type of a list item is a reference to a type T then the type
10230 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010231 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010232
10233 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10234 // A list item cannot be a variable that is a member of a structure with
10235 // a union type.
10236 //
10237 if (auto *RT = CurType->getAs<RecordType>())
10238 if (RT->isUnionType()) {
10239 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10240 << CurE->getSourceRange();
10241 break;
10242 }
10243
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010244 // If we got a member expression, we should not expect any array section
10245 // before that:
10246 //
10247 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10248 // If a list item is an element of a structure, only the rightmost symbol
10249 // of the variable reference can be an array section.
10250 //
10251 AllowUnitySizeArraySection = false;
10252 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010253
10254 // Record the component.
10255 CurComponents.push_back(
10256 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010257 continue;
10258 }
10259
10260 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10261 E = CurE->getBase()->IgnoreParenImpCasts();
10262
10263 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10264 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10265 << 0 << CurE->getSourceRange();
10266 break;
10267 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010268
10269 // If we got an array subscript that express the whole dimension we
10270 // can have any array expressions before. If it only expressing part of
10271 // the dimension, we can only have unitary-size array expressions.
10272 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10273 E->getType()))
10274 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010275
10276 // Record the component - we don't have any declaration associated.
10277 CurComponents.push_back(
10278 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010279 continue;
10280 }
10281
10282 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010283 E = CurE->getBase()->IgnoreParenImpCasts();
10284
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010285 auto CurType =
10286 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10287
Samuel Antao5de996e2016-01-22 20:21:36 +000010288 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10289 // If the type of a list item is a reference to a type T then the type
10290 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010291 if (CurType->isReferenceType())
10292 CurType = CurType->getPointeeType();
10293
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010294 bool IsPointer = CurType->isAnyPointerType();
10295
10296 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010297 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10298 << 0 << CurE->getSourceRange();
10299 break;
10300 }
10301
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010302 bool NotWhole =
10303 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10304 bool NotUnity =
10305 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10306
Samuel Antaodab51bb2016-07-18 23:22:11 +000010307 if (AllowWholeSizeArraySection) {
10308 // Any array section is currently allowed. Allowing a whole size array
10309 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010310 //
10311 // If this array section refers to the whole dimension we can still
10312 // accept other array sections before this one, except if the base is a
10313 // pointer. Otherwise, only unitary sections are accepted.
10314 if (NotWhole || IsPointer)
10315 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010316 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010317 // A unity or whole array section is not allowed and that is not
10318 // compatible with the properties of the current array section.
10319 SemaRef.Diag(
10320 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10321 << CurE->getSourceRange();
10322 break;
10323 }
Samuel Antao90927002016-04-26 14:54:23 +000010324
10325 // Record the component - we don't have any declaration associated.
10326 CurComponents.push_back(
10327 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010328 continue;
10329 }
10330
10331 // If nothing else worked, this is not a valid map clause expression.
10332 SemaRef.Diag(ELoc,
10333 diag::err_omp_expected_named_var_member_or_array_expression)
10334 << ERange;
10335 break;
10336 }
10337
10338 return RelevantExpr;
10339}
10340
10341// Return true if expression E associated with value VD has conflicts with other
10342// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010343static bool CheckMapConflicts(
10344 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10345 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010346 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10347 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010348 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010349 SourceLocation ELoc = E->getExprLoc();
10350 SourceRange ERange = E->getSourceRange();
10351
10352 // In order to easily check the conflicts we need to match each component of
10353 // the expression under test with the components of the expressions that are
10354 // already in the stack.
10355
Samuel Antao5de996e2016-01-22 20:21:36 +000010356 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010357 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010358 "Map clause expression with unexpected base!");
10359
10360 // Variables to help detecting enclosing problems in data environment nests.
10361 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010362 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010363
Samuel Antao90927002016-04-26 14:54:23 +000010364 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10365 VD, CurrentRegionOnly,
10366 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010367 StackComponents,
10368 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010369
Samuel Antao5de996e2016-01-22 20:21:36 +000010370 assert(!StackComponents.empty() &&
10371 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010372 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010373 "Map clause expression with unexpected base!");
10374
Samuel Antao90927002016-04-26 14:54:23 +000010375 // The whole expression in the stack.
10376 auto *RE = StackComponents.front().getAssociatedExpression();
10377
Samuel Antao5de996e2016-01-22 20:21:36 +000010378 // Expressions must start from the same base. Here we detect at which
10379 // point both expressions diverge from each other and see if we can
10380 // detect if the memory referred to both expressions is contiguous and
10381 // do not overlap.
10382 auto CI = CurComponents.rbegin();
10383 auto CE = CurComponents.rend();
10384 auto SI = StackComponents.rbegin();
10385 auto SE = StackComponents.rend();
10386 for (; CI != CE && SI != SE; ++CI, ++SI) {
10387
10388 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10389 // At most one list item can be an array item derived from a given
10390 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010391 if (CurrentRegionOnly &&
10392 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10393 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10394 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10395 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10396 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010397 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010398 << CI->getAssociatedExpression()->getSourceRange();
10399 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10400 diag::note_used_here)
10401 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010402 return true;
10403 }
10404
10405 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010406 if (CI->getAssociatedExpression()->getStmtClass() !=
10407 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010408 break;
10409
10410 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010411 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010412 break;
10413 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010414 // Check if the extra components of the expressions in the enclosing
10415 // data environment are redundant for the current base declaration.
10416 // If they are, the maps completely overlap, which is legal.
10417 for (; SI != SE; ++SI) {
10418 QualType Type;
10419 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010420 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010421 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010422 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10423 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010424 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10425 Type =
10426 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10427 }
10428 if (Type.isNull() || Type->isAnyPointerType() ||
10429 CheckArrayExpressionDoesNotReferToWholeSize(
10430 SemaRef, SI->getAssociatedExpression(), Type))
10431 break;
10432 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010433
10434 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10435 // List items of map clauses in the same construct must not share
10436 // original storage.
10437 //
10438 // If the expressions are exactly the same or one is a subset of the
10439 // other, it means they are sharing storage.
10440 if (CI == CE && SI == SE) {
10441 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010442 if (CKind == OMPC_map)
10443 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10444 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010445 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010446 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10447 << ERange;
10448 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010449 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10450 << RE->getSourceRange();
10451 return true;
10452 } else {
10453 // If we find the same expression in the enclosing data environment,
10454 // that is legal.
10455 IsEnclosedByDataEnvironmentExpr = true;
10456 return false;
10457 }
10458 }
10459
Samuel Antao90927002016-04-26 14:54:23 +000010460 QualType DerivedType =
10461 std::prev(CI)->getAssociatedDeclaration()->getType();
10462 SourceLocation DerivedLoc =
10463 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010464
10465 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10466 // If the type of a list item is a reference to a type T then the type
10467 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010468 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010469
10470 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10471 // A variable for which the type is pointer and an array section
10472 // derived from that variable must not appear as list items of map
10473 // clauses of the same construct.
10474 //
10475 // Also, cover one of the cases in:
10476 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10477 // If any part of the original storage of a list item has corresponding
10478 // storage in the device data environment, all of the original storage
10479 // must have corresponding storage in the device data environment.
10480 //
10481 if (DerivedType->isAnyPointerType()) {
10482 if (CI == CE || SI == SE) {
10483 SemaRef.Diag(
10484 DerivedLoc,
10485 diag::err_omp_pointer_mapped_along_with_derived_section)
10486 << DerivedLoc;
10487 } else {
10488 assert(CI != CE && SI != SE);
10489 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10490 << DerivedLoc;
10491 }
10492 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10493 << RE->getSourceRange();
10494 return true;
10495 }
10496
10497 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10498 // List items of map clauses in the same construct must not share
10499 // original storage.
10500 //
10501 // An expression is a subset of the other.
10502 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010503 if (CKind == OMPC_map)
10504 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10505 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010506 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010507 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10508 << ERange;
10509 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010510 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10511 << RE->getSourceRange();
10512 return true;
10513 }
10514
10515 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010516 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010517 if (!CurrentRegionOnly && SI != SE)
10518 EnclosingExpr = RE;
10519
10520 // The current expression is a subset of the expression in the data
10521 // environment.
10522 IsEnclosedByDataEnvironmentExpr |=
10523 (!CurrentRegionOnly && CI != CE && SI == SE);
10524
10525 return false;
10526 });
10527
10528 if (CurrentRegionOnly)
10529 return FoundError;
10530
10531 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10532 // If any part of the original storage of a list item has corresponding
10533 // storage in the device data environment, all of the original storage must
10534 // have corresponding storage in the device data environment.
10535 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10536 // If a list item is an element of a structure, and a different element of
10537 // the structure has a corresponding list item in the device data environment
10538 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010539 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010540 // data environment prior to the task encountering the construct.
10541 //
10542 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10543 SemaRef.Diag(ELoc,
10544 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10545 << ERange;
10546 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10547 << EnclosingExpr->getSourceRange();
10548 return true;
10549 }
10550
10551 return FoundError;
10552}
10553
Samuel Antao661c0902016-05-26 17:39:58 +000010554namespace {
10555// Utility struct that gathers all the related lists associated with a mappable
10556// expression.
10557struct MappableVarListInfo final {
10558 // The list of expressions.
10559 ArrayRef<Expr *> VarList;
10560 // The list of processed expressions.
10561 SmallVector<Expr *, 16> ProcessedVarList;
10562 // The mappble components for each expression.
10563 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10564 // The base declaration of the variable.
10565 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10566
10567 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10568 // We have a list of components and base declarations for each entry in the
10569 // variable list.
10570 VarComponents.reserve(VarList.size());
10571 VarBaseDeclarations.reserve(VarList.size());
10572 }
10573};
10574}
10575
10576// Check the validity of the provided variable list for the provided clause kind
10577// \a CKind. In the check process the valid expressions, and mappable expression
10578// components and variables are extracted and used to fill \a Vars,
10579// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10580// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10581static void
10582checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10583 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10584 SourceLocation StartLoc,
10585 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10586 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010587 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10588 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010589 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010590
Samuel Antao90927002016-04-26 14:54:23 +000010591 // Keep track of the mappable components and base declarations in this clause.
10592 // Each entry in the list is going to have a list of components associated. We
10593 // record each set of the components so that we can build the clause later on.
10594 // In the end we should have the same amount of declarations and component
10595 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010596
Samuel Antao661c0902016-05-26 17:39:58 +000010597 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010598 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010599 SourceLocation ELoc = RE->getExprLoc();
10600
Kelvin Li0bff7af2015-11-23 05:32:03 +000010601 auto *VE = RE->IgnoreParenLValueCasts();
10602
10603 if (VE->isValueDependent() || VE->isTypeDependent() ||
10604 VE->isInstantiationDependent() ||
10605 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010606 // We can only analyze this information once the missing information is
10607 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010608 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010609 continue;
10610 }
10611
10612 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010613
Samuel Antao5de996e2016-01-22 20:21:36 +000010614 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010615 SemaRef.Diag(ELoc,
10616 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010617 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010618 continue;
10619 }
10620
Samuel Antao90927002016-04-26 14:54:23 +000010621 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10622 ValueDecl *CurDeclaration = nullptr;
10623
10624 // Obtain the array or member expression bases if required. Also, fill the
10625 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010626 auto *BE =
10627 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010628 if (!BE)
10629 continue;
10630
Samuel Antao90927002016-04-26 14:54:23 +000010631 assert(!CurComponents.empty() &&
10632 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010633
Samuel Antao90927002016-04-26 14:54:23 +000010634 // For the following checks, we rely on the base declaration which is
10635 // expected to be associated with the last component. The declaration is
10636 // expected to be a variable or a field (if 'this' is being mapped).
10637 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10638 assert(CurDeclaration && "Null decl on map clause.");
10639 assert(
10640 CurDeclaration->isCanonicalDecl() &&
10641 "Expecting components to have associated only canonical declarations.");
10642
10643 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10644 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010645
10646 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010647 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010648
10649 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010650 // threadprivate variables cannot appear in a map clause.
10651 // OpenMP 4.5 [2.10.5, target update Construct]
10652 // threadprivate variables cannot appear in a from clause.
10653 if (VD && DSAS->isThreadPrivate(VD)) {
10654 auto DVar = DSAS->getTopDSA(VD, false);
10655 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10656 << getOpenMPClauseName(CKind);
10657 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010658 continue;
10659 }
10660
Samuel Antao5de996e2016-01-22 20:21:36 +000010661 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10662 // A list item cannot appear in both a map clause and a data-sharing
10663 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010664
Samuel Antao5de996e2016-01-22 20:21:36 +000010665 // Check conflicts with other map clause expressions. We check the conflicts
10666 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010667 // environment, because the restrictions are different. We only have to
10668 // check conflicts across regions for the map clauses.
10669 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10670 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010671 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010672 if (CKind == OMPC_map &&
10673 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10674 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010675 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010676
Samuel Antao661c0902016-05-26 17:39:58 +000010677 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010678 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10679 // If the type of a list item is a reference to a type T then the type will
10680 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010681 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010682
Samuel Antao661c0902016-05-26 17:39:58 +000010683 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10684 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010685 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010686 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010687 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10688 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010689 continue;
10690
Samuel Antao661c0902016-05-26 17:39:58 +000010691 if (CKind == OMPC_map) {
10692 // target enter data
10693 // OpenMP [2.10.2, Restrictions, p. 99]
10694 // A map-type must be specified in all map clauses and must be either
10695 // to or alloc.
10696 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10697 if (DKind == OMPD_target_enter_data &&
10698 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10699 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10700 << (IsMapTypeImplicit ? 1 : 0)
10701 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10702 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010703 continue;
10704 }
Samuel Antao661c0902016-05-26 17:39:58 +000010705
10706 // target exit_data
10707 // OpenMP [2.10.3, Restrictions, p. 102]
10708 // A map-type must be specified in all map clauses and must be either
10709 // from, release, or delete.
10710 if (DKind == OMPD_target_exit_data &&
10711 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10712 MapType == OMPC_MAP_delete)) {
10713 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10714 << (IsMapTypeImplicit ? 1 : 0)
10715 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10716 << getOpenMPDirectiveName(DKind);
10717 continue;
10718 }
10719
10720 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10721 // A list item cannot appear in both a map clause and a data-sharing
10722 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010723 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010724 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010725 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010726 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10727 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010728 auto DVar = DSAS->getTopDSA(VD, false);
10729 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010730 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010731 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010732 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010733 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10734 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10735 continue;
10736 }
10737 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010738 }
10739
Samuel Antao90927002016-04-26 14:54:23 +000010740 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010741 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010742
10743 // Store the components in the stack so that they can be used to check
10744 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010745 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10746 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010747
10748 // Save the components and declaration to create the clause. For purposes of
10749 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010750 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010751 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10752 MVLI.VarComponents.back().append(CurComponents.begin(),
10753 CurComponents.end());
10754 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10755 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010756 }
Samuel Antao661c0902016-05-26 17:39:58 +000010757}
10758
10759OMPClause *
10760Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10761 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10762 SourceLocation MapLoc, SourceLocation ColonLoc,
10763 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10764 SourceLocation LParenLoc, SourceLocation EndLoc) {
10765 MappableVarListInfo MVLI(VarList);
10766 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10767 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010768
Samuel Antao5de996e2016-01-22 20:21:36 +000010769 // We need to produce a map clause even if we don't have variables so that
10770 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010771 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10772 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10773 MVLI.VarComponents, MapTypeModifier, MapType,
10774 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010775}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010776
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010777QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10778 TypeResult ParsedType) {
10779 assert(ParsedType.isUsable());
10780
10781 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10782 if (ReductionType.isNull())
10783 return QualType();
10784
10785 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10786 // A type name in a declare reduction directive cannot be a function type, an
10787 // array type, a reference type, or a type qualified with const, volatile or
10788 // restrict.
10789 if (ReductionType.hasQualifiers()) {
10790 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10791 return QualType();
10792 }
10793
10794 if (ReductionType->isFunctionType()) {
10795 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10796 return QualType();
10797 }
10798 if (ReductionType->isReferenceType()) {
10799 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10800 return QualType();
10801 }
10802 if (ReductionType->isArrayType()) {
10803 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10804 return QualType();
10805 }
10806 return ReductionType;
10807}
10808
10809Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10810 Scope *S, DeclContext *DC, DeclarationName Name,
10811 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10812 AccessSpecifier AS, Decl *PrevDeclInScope) {
10813 SmallVector<Decl *, 8> Decls;
10814 Decls.reserve(ReductionTypes.size());
10815
10816 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10817 ForRedeclaration);
10818 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10819 // A reduction-identifier may not be re-declared in the current scope for the
10820 // same type or for a type that is compatible according to the base language
10821 // rules.
10822 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10823 OMPDeclareReductionDecl *PrevDRD = nullptr;
10824 bool InCompoundScope = true;
10825 if (S != nullptr) {
10826 // Find previous declaration with the same name not referenced in other
10827 // declarations.
10828 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10829 InCompoundScope =
10830 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10831 LookupName(Lookup, S);
10832 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10833 /*AllowInlineNamespace=*/false);
10834 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10835 auto Filter = Lookup.makeFilter();
10836 while (Filter.hasNext()) {
10837 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10838 if (InCompoundScope) {
10839 auto I = UsedAsPrevious.find(PrevDecl);
10840 if (I == UsedAsPrevious.end())
10841 UsedAsPrevious[PrevDecl] = false;
10842 if (auto *D = PrevDecl->getPrevDeclInScope())
10843 UsedAsPrevious[D] = true;
10844 }
10845 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10846 PrevDecl->getLocation();
10847 }
10848 Filter.done();
10849 if (InCompoundScope) {
10850 for (auto &PrevData : UsedAsPrevious) {
10851 if (!PrevData.second) {
10852 PrevDRD = PrevData.first;
10853 break;
10854 }
10855 }
10856 }
10857 } else if (PrevDeclInScope != nullptr) {
10858 auto *PrevDRDInScope = PrevDRD =
10859 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10860 do {
10861 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10862 PrevDRDInScope->getLocation();
10863 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10864 } while (PrevDRDInScope != nullptr);
10865 }
10866 for (auto &TyData : ReductionTypes) {
10867 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10868 bool Invalid = false;
10869 if (I != PreviousRedeclTypes.end()) {
10870 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10871 << TyData.first;
10872 Diag(I->second, diag::note_previous_definition);
10873 Invalid = true;
10874 }
10875 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10876 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10877 Name, TyData.first, PrevDRD);
10878 DC->addDecl(DRD);
10879 DRD->setAccess(AS);
10880 Decls.push_back(DRD);
10881 if (Invalid)
10882 DRD->setInvalidDecl();
10883 else
10884 PrevDRD = DRD;
10885 }
10886
10887 return DeclGroupPtrTy::make(
10888 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10889}
10890
10891void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10892 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10893
10894 // Enter new function scope.
10895 PushFunctionScope();
10896 getCurFunction()->setHasBranchProtectedScope();
10897 getCurFunction()->setHasOMPDeclareReductionCombiner();
10898
10899 if (S != nullptr)
10900 PushDeclContext(S, DRD);
10901 else
10902 CurContext = DRD;
10903
10904 PushExpressionEvaluationContext(PotentiallyEvaluated);
10905
10906 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010907 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10908 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10909 // uses semantics of argument handles by value, but it should be passed by
10910 // reference. C lang does not support references, so pass all parameters as
10911 // pointers.
10912 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010913 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010914 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010915 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10916 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10917 // uses semantics of argument handles by value, but it should be passed by
10918 // reference. C lang does not support references, so pass all parameters as
10919 // pointers.
10920 // Create 'T omp_out;' variable.
10921 auto *OmpOutParm =
10922 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10923 if (S != nullptr) {
10924 PushOnScopeChains(OmpInParm, S);
10925 PushOnScopeChains(OmpOutParm, S);
10926 } else {
10927 DRD->addDecl(OmpInParm);
10928 DRD->addDecl(OmpOutParm);
10929 }
10930}
10931
10932void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10933 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10934 DiscardCleanupsInEvaluationContext();
10935 PopExpressionEvaluationContext();
10936
10937 PopDeclContext();
10938 PopFunctionScopeInfo();
10939
10940 if (Combiner != nullptr)
10941 DRD->setCombiner(Combiner);
10942 else
10943 DRD->setInvalidDecl();
10944}
10945
10946void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10947 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10948
10949 // Enter new function scope.
10950 PushFunctionScope();
10951 getCurFunction()->setHasBranchProtectedScope();
10952
10953 if (S != nullptr)
10954 PushDeclContext(S, DRD);
10955 else
10956 CurContext = DRD;
10957
10958 PushExpressionEvaluationContext(PotentiallyEvaluated);
10959
10960 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010961 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10962 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10963 // uses semantics of argument handles by value, but it should be passed by
10964 // reference. C lang does not support references, so pass all parameters as
10965 // pointers.
10966 // Create 'T omp_priv;' variable.
10967 auto *OmpPrivParm =
10968 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010969 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10970 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10971 // uses semantics of argument handles by value, but it should be passed by
10972 // reference. C lang does not support references, so pass all parameters as
10973 // pointers.
10974 // Create 'T omp_orig;' variable.
10975 auto *OmpOrigParm =
10976 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010977 if (S != nullptr) {
10978 PushOnScopeChains(OmpPrivParm, S);
10979 PushOnScopeChains(OmpOrigParm, S);
10980 } else {
10981 DRD->addDecl(OmpPrivParm);
10982 DRD->addDecl(OmpOrigParm);
10983 }
10984}
10985
10986void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10987 Expr *Initializer) {
10988 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10989 DiscardCleanupsInEvaluationContext();
10990 PopExpressionEvaluationContext();
10991
10992 PopDeclContext();
10993 PopFunctionScopeInfo();
10994
10995 if (Initializer != nullptr)
10996 DRD->setInitializer(Initializer);
10997 else
10998 DRD->setInvalidDecl();
10999}
11000
11001Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11002 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11003 for (auto *D : DeclReductions.get()) {
11004 if (IsValid) {
11005 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11006 if (S != nullptr)
11007 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11008 } else
11009 D->setInvalidDecl();
11010 }
11011 return DeclReductions;
11012}
11013
David Majnemer9d168222016-08-05 17:44:54 +000011014OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011015 SourceLocation StartLoc,
11016 SourceLocation LParenLoc,
11017 SourceLocation EndLoc) {
11018 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011019 Stmt *HelperValStmt = nullptr;
11020 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011021
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011022 // OpenMP [teams Constrcut, Restrictions]
11023 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011024 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11025 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011026 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011027
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011028 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11029 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11030 if (CaptureRegion != OMPD_unknown) {
11031 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11032 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11033 HelperValStmt = buildPreInits(Context, Captures);
11034 }
11035
11036 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11037 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011038}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011039
11040OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11041 SourceLocation StartLoc,
11042 SourceLocation LParenLoc,
11043 SourceLocation EndLoc) {
11044 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011045 Stmt *HelperValStmt = nullptr;
11046 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011047
11048 // OpenMP [teams Constrcut, Restrictions]
11049 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011050 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11051 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011052 return nullptr;
11053
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011054 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11055 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11056 if (CaptureRegion != OMPD_unknown) {
11057 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11058 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11059 HelperValStmt = buildPreInits(Context, Captures);
11060 }
11061
11062 return new (Context) OMPThreadLimitClause(
11063 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011064}
Alexey Bataeva0569352015-12-01 10:17:31 +000011065
11066OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11067 SourceLocation StartLoc,
11068 SourceLocation LParenLoc,
11069 SourceLocation EndLoc) {
11070 Expr *ValExpr = Priority;
11071
11072 // OpenMP [2.9.1, task Constrcut]
11073 // The priority-value is a non-negative numerical scalar expression.
11074 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11075 /*StrictlyPositive=*/false))
11076 return nullptr;
11077
11078 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11079}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011080
11081OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11082 SourceLocation StartLoc,
11083 SourceLocation LParenLoc,
11084 SourceLocation EndLoc) {
11085 Expr *ValExpr = Grainsize;
11086
11087 // OpenMP [2.9.2, taskloop Constrcut]
11088 // The parameter of the grainsize clause must be a positive integer
11089 // expression.
11090 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11091 /*StrictlyPositive=*/true))
11092 return nullptr;
11093
11094 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11095}
Alexey Bataev382967a2015-12-08 12:06:20 +000011096
11097OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11098 SourceLocation StartLoc,
11099 SourceLocation LParenLoc,
11100 SourceLocation EndLoc) {
11101 Expr *ValExpr = NumTasks;
11102
11103 // OpenMP [2.9.2, taskloop Constrcut]
11104 // The parameter of the num_tasks clause must be a positive integer
11105 // expression.
11106 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11107 /*StrictlyPositive=*/true))
11108 return nullptr;
11109
11110 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11111}
11112
Alexey Bataev28c75412015-12-15 08:19:24 +000011113OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11114 SourceLocation LParenLoc,
11115 SourceLocation EndLoc) {
11116 // OpenMP [2.13.2, critical construct, Description]
11117 // ... where hint-expression is an integer constant expression that evaluates
11118 // to a valid lock hint.
11119 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11120 if (HintExpr.isInvalid())
11121 return nullptr;
11122 return new (Context)
11123 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11124}
11125
Carlo Bertollib4adf552016-01-15 18:50:31 +000011126OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11127 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11128 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11129 SourceLocation EndLoc) {
11130 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11131 std::string Values;
11132 Values += "'";
11133 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11134 Values += "'";
11135 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11136 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11137 return nullptr;
11138 }
11139 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011140 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011141 if (ChunkSize) {
11142 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11143 !ChunkSize->isInstantiationDependent() &&
11144 !ChunkSize->containsUnexpandedParameterPack()) {
11145 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11146 ExprResult Val =
11147 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11148 if (Val.isInvalid())
11149 return nullptr;
11150
11151 ValExpr = Val.get();
11152
11153 // OpenMP [2.7.1, Restrictions]
11154 // chunk_size must be a loop invariant integer expression with a positive
11155 // value.
11156 llvm::APSInt Result;
11157 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11158 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11159 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11160 << "dist_schedule" << ChunkSize->getSourceRange();
11161 return nullptr;
11162 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011163 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11164 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011165 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11166 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11167 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011168 }
11169 }
11170 }
11171
11172 return new (Context)
11173 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011174 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011175}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011176
11177OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11178 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11179 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11180 SourceLocation KindLoc, SourceLocation EndLoc) {
11181 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011182 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011183 std::string Value;
11184 SourceLocation Loc;
11185 Value += "'";
11186 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11187 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011188 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011189 Loc = MLoc;
11190 } else {
11191 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011192 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011193 Loc = KindLoc;
11194 }
11195 Value += "'";
11196 Diag(Loc, diag::err_omp_unexpected_clause_value)
11197 << Value << getOpenMPClauseName(OMPC_defaultmap);
11198 return nullptr;
11199 }
11200
11201 return new (Context)
11202 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11203}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011204
11205bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11206 DeclContext *CurLexicalContext = getCurLexicalContext();
11207 if (!CurLexicalContext->isFileContext() &&
11208 !CurLexicalContext->isExternCContext() &&
11209 !CurLexicalContext->isExternCXXContext()) {
11210 Diag(Loc, diag::err_omp_region_not_file_context);
11211 return false;
11212 }
11213 if (IsInOpenMPDeclareTargetContext) {
11214 Diag(Loc, diag::err_omp_enclosed_declare_target);
11215 return false;
11216 }
11217
11218 IsInOpenMPDeclareTargetContext = true;
11219 return true;
11220}
11221
11222void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11223 assert(IsInOpenMPDeclareTargetContext &&
11224 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11225
11226 IsInOpenMPDeclareTargetContext = false;
11227}
11228
David Majnemer9d168222016-08-05 17:44:54 +000011229void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11230 CXXScopeSpec &ScopeSpec,
11231 const DeclarationNameInfo &Id,
11232 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11233 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011234 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11235 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11236
11237 if (Lookup.isAmbiguous())
11238 return;
11239 Lookup.suppressDiagnostics();
11240
11241 if (!Lookup.isSingleResult()) {
11242 if (TypoCorrection Corrected =
11243 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11244 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11245 CTK_ErrorRecovery)) {
11246 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11247 << Id.getName());
11248 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11249 return;
11250 }
11251
11252 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11253 return;
11254 }
11255
11256 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11257 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11258 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11259 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11260
11261 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11262 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11263 ND->addAttr(A);
11264 if (ASTMutationListener *ML = Context.getASTMutationListener())
11265 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11266 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11267 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11268 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11269 << Id.getName();
11270 }
11271 } else
11272 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11273}
11274
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011275static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11276 Sema &SemaRef, Decl *D) {
11277 if (!D)
11278 return;
11279 Decl *LD = nullptr;
11280 if (isa<TagDecl>(D)) {
11281 LD = cast<TagDecl>(D)->getDefinition();
11282 } else if (isa<VarDecl>(D)) {
11283 LD = cast<VarDecl>(D)->getDefinition();
11284
11285 // If this is an implicit variable that is legal and we do not need to do
11286 // anything.
11287 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011288 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11289 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11290 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011291 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011292 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011293 return;
11294 }
11295
11296 } else if (isa<FunctionDecl>(D)) {
11297 const FunctionDecl *FD = nullptr;
11298 if (cast<FunctionDecl>(D)->hasBody(FD))
11299 LD = const_cast<FunctionDecl *>(FD);
11300
11301 // If the definition is associated with the current declaration in the
11302 // target region (it can be e.g. a lambda) that is legal and we do not need
11303 // to do anything else.
11304 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011305 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11306 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11307 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011308 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011309 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011310 return;
11311 }
11312 }
11313 if (!LD)
11314 LD = D;
11315 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11316 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11317 // Outlined declaration is not declared target.
11318 if (LD->isOutOfLine()) {
11319 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11320 SemaRef.Diag(SL, diag::note_used_here) << SR;
11321 } else {
11322 DeclContext *DC = LD->getDeclContext();
11323 while (DC) {
11324 if (isa<FunctionDecl>(DC) &&
11325 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11326 break;
11327 DC = DC->getParent();
11328 }
11329 if (DC)
11330 return;
11331
11332 // Is not declared in target context.
11333 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11334 SemaRef.Diag(SL, diag::note_used_here) << SR;
11335 }
11336 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011337 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11338 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11339 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011340 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011341 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011342 }
11343}
11344
11345static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11346 Sema &SemaRef, DSAStackTy *Stack,
11347 ValueDecl *VD) {
11348 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11349 return true;
11350 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11351 return false;
11352 return true;
11353}
11354
11355void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11356 if (!D || D->isInvalidDecl())
11357 return;
11358 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11359 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11360 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11361 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11362 if (DSAStack->isThreadPrivate(VD)) {
11363 Diag(SL, diag::err_omp_threadprivate_in_target);
11364 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11365 return;
11366 }
11367 }
11368 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11369 // Problem if any with var declared with incomplete type will be reported
11370 // as normal, so no need to check it here.
11371 if ((E || !VD->getType()->isIncompleteType()) &&
11372 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11373 // Mark decl as declared target to prevent further diagnostic.
11374 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011375 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11376 Context, OMPDeclareTargetDeclAttr::MT_To);
11377 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011378 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011379 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011380 }
11381 return;
11382 }
11383 }
11384 if (!E) {
11385 // Checking declaration inside declare target region.
11386 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11387 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011388 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11389 Context, OMPDeclareTargetDeclAttr::MT_To);
11390 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011391 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011392 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011393 }
11394 return;
11395 }
11396 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11397}
Samuel Antao661c0902016-05-26 17:39:58 +000011398
11399OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11400 SourceLocation StartLoc,
11401 SourceLocation LParenLoc,
11402 SourceLocation EndLoc) {
11403 MappableVarListInfo MVLI(VarList);
11404 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11405 if (MVLI.ProcessedVarList.empty())
11406 return nullptr;
11407
11408 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11409 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11410 MVLI.VarComponents);
11411}
Samuel Antaoec172c62016-05-26 17:49:04 +000011412
11413OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11414 SourceLocation StartLoc,
11415 SourceLocation LParenLoc,
11416 SourceLocation EndLoc) {
11417 MappableVarListInfo MVLI(VarList);
11418 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11419 if (MVLI.ProcessedVarList.empty())
11420 return nullptr;
11421
11422 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11423 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11424 MVLI.VarComponents);
11425}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011426
11427OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11428 SourceLocation StartLoc,
11429 SourceLocation LParenLoc,
11430 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011431 MappableVarListInfo MVLI(VarList);
11432 SmallVector<Expr *, 8> PrivateCopies;
11433 SmallVector<Expr *, 8> Inits;
11434
Carlo Bertolli2404b172016-07-13 15:37:16 +000011435 for (auto &RefExpr : VarList) {
11436 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11437 SourceLocation ELoc;
11438 SourceRange ERange;
11439 Expr *SimpleRefExpr = RefExpr;
11440 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11441 if (Res.second) {
11442 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011443 MVLI.ProcessedVarList.push_back(RefExpr);
11444 PrivateCopies.push_back(nullptr);
11445 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011446 }
11447 ValueDecl *D = Res.first;
11448 if (!D)
11449 continue;
11450
11451 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011452 Type = Type.getNonReferenceType().getUnqualifiedType();
11453
11454 auto *VD = dyn_cast<VarDecl>(D);
11455
11456 // Item should be a pointer or reference to pointer.
11457 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011458 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11459 << 0 << RefExpr->getSourceRange();
11460 continue;
11461 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011462
11463 // Build the private variable and the expression that refers to it.
11464 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11465 D->hasAttrs() ? &D->getAttrs() : nullptr);
11466 if (VDPrivate->isInvalidDecl())
11467 continue;
11468
11469 CurContext->addDecl(VDPrivate);
11470 auto VDPrivateRefExpr = buildDeclRefExpr(
11471 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11472
11473 // Add temporary variable to initialize the private copy of the pointer.
11474 auto *VDInit =
11475 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11476 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11477 RefExpr->getExprLoc());
11478 AddInitializerToDecl(VDPrivate,
11479 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011480 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011481
11482 // If required, build a capture to implement the privatization initialized
11483 // with the current list item value.
11484 DeclRefExpr *Ref = nullptr;
11485 if (!VD)
11486 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11487 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11488 PrivateCopies.push_back(VDPrivateRefExpr);
11489 Inits.push_back(VDInitRefExpr);
11490
11491 // We need to add a data sharing attribute for this variable to make sure it
11492 // is correctly captured. A variable that shows up in a use_device_ptr has
11493 // similar properties of a first private variable.
11494 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11495
11496 // Create a mappable component for the list item. List items in this clause
11497 // only need a component.
11498 MVLI.VarBaseDeclarations.push_back(D);
11499 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11500 MVLI.VarComponents.back().push_back(
11501 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011502 }
11503
Samuel Antaocc10b852016-07-28 14:23:26 +000011504 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011505 return nullptr;
11506
Samuel Antaocc10b852016-07-28 14:23:26 +000011507 return OMPUseDevicePtrClause::Create(
11508 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11509 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011510}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011511
11512OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11513 SourceLocation StartLoc,
11514 SourceLocation LParenLoc,
11515 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011516 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011517 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011518 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011519 SourceLocation ELoc;
11520 SourceRange ERange;
11521 Expr *SimpleRefExpr = RefExpr;
11522 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11523 if (Res.second) {
11524 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011525 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011526 }
11527 ValueDecl *D = Res.first;
11528 if (!D)
11529 continue;
11530
11531 QualType Type = D->getType();
11532 // item should be a pointer or array or reference to pointer or array
11533 if (!Type.getNonReferenceType()->isPointerType() &&
11534 !Type.getNonReferenceType()->isArrayType()) {
11535 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11536 << 0 << RefExpr->getSourceRange();
11537 continue;
11538 }
Samuel Antao6890b092016-07-28 14:25:09 +000011539
11540 // Check if the declaration in the clause does not show up in any data
11541 // sharing attribute.
11542 auto DVar = DSAStack->getTopDSA(D, false);
11543 if (isOpenMPPrivate(DVar.CKind)) {
11544 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11545 << getOpenMPClauseName(DVar.CKind)
11546 << getOpenMPClauseName(OMPC_is_device_ptr)
11547 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11548 ReportOriginalDSA(*this, DSAStack, D, DVar);
11549 continue;
11550 }
11551
11552 Expr *ConflictExpr;
11553 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011554 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011555 [&ConflictExpr](
11556 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11557 OpenMPClauseKind) -> bool {
11558 ConflictExpr = R.front().getAssociatedExpression();
11559 return true;
11560 })) {
11561 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11562 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11563 << ConflictExpr->getSourceRange();
11564 continue;
11565 }
11566
11567 // Store the components in the stack so that they can be used to check
11568 // against other clauses later on.
11569 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11570 DSAStack->addMappableExpressionComponents(
11571 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11572
11573 // Record the expression we've just processed.
11574 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11575
11576 // Create a mappable component for the list item. List items in this clause
11577 // only need a component. We use a null declaration to signal fields in
11578 // 'this'.
11579 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11580 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11581 "Unexpected device pointer expression!");
11582 MVLI.VarBaseDeclarations.push_back(
11583 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11584 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11585 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011586 }
11587
Samuel Antao6890b092016-07-28 14:25:09 +000011588 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011589 return nullptr;
11590
Samuel Antao6890b092016-07-28 14:25:09 +000011591 return OMPIsDevicePtrClause::Create(
11592 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11593 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011594}